微信小程序蓝牙开发3、读取蓝牙特征值


let blueName = "asdsadsa",//想要连接的蓝牙名
    initFlag = false,//是否继续查找
    connected = false;//是否连接上
Page({
    onLoad: function (options) {
        initFlag = false;
        connected = false;
        this.initBlue();//初始化
    },
    onHide: function () { },
    onUnload: function () {
        initFlag = true;
    },
    initBlue: function () {//1、初始化
        var _this = this;
        wx.openBluetoothAdapter({//初始化蓝牙模块
            success: function (res) {
                _this.startBluetoothDevicesDiscovery();//开始搜索蓝牙设备
            },
            fail(res) {
                _this.showTip();//提示打开蓝牙
                wx.onBluetoothAdapterStateChange(function (res) {//监听蓝牙打开关闭
                    if (res.available && !res.discovering && !connected) {//可用 且不在搜索中 且没有连接
                        _this.startBluetoothDevicesDiscovery()
                    }
                })
            }
        })
    },
    startBluetoothDevicesDiscovery: function () {//2、开始搜寻附近的蓝牙外围设备
        var _this = this;
        wx.startBluetoothDevicesDiscovery({
            //  services:["00000000-0000-0000-0000-000000071920"],//根据uuid过滤蓝牙 搜索速度加快
            allowDuplicatesKey: true,//是否允许重复上报同一设备。
            success: function (res) {
                setTimeout(function () {//28s超时没找到 关闭搜索
                    if (!initFlag) {
                        initFlag = true;//不搜索了
                        _this.stopBluetoothDevicesDiscovery();
                        wx.closeBluetoothAdapter({
                            success(res) {
                                console.log('关闭蓝牙模块');
                            }
                        })
                    }
                }, 28000)
                setTimeout(function () {
                    _this.getBluetoothDevices();//获取搜索到的设备 同时进行
                }, 300);
                _this.onBluetoothDeviceFound();//监听搜索到新设备  同时进行
            },
            fail: function (err) {
                console.log(err);
            }
        });
    },
    getBluetoothDevices: function () {//3、获取在蓝牙模块生效期间所有已发现的蓝牙设备。
        var _this = this;
        wx.getBluetoothDevices({
            success: function (res) {
                let deviceA = res.devices;
                for (let i = 0; i < deviceA.length; i++) {
                    let name = deviceA[i].name;
                    if (name == blueName) {//找到后连接并停止搜素
                        let blueDeviceId = deviceA[i].deviceId;//设置蓝牙设备id
                        wx.setStorageSync('blueDeviceId', blueDeviceId);//设置蓝牙设备id
                        initFlag = true;//停止循环
                        _this.connetBlue(blueDeviceId);//连接蓝牙
                        _this.stopBluetoothDevicesDiscovery();//停止搜索
                        break;
                    }
                }
                if (!initFlag) {//没找到 递归调用
                    setTimeout(function () {
                        _this.getBluetoothDevices();
                    }, 800)
                }
            }
        })
    },
    onBluetoothDeviceFound: function () {//3、监听寻找到新设备的事件 
        var _this = this;
        wx.onBluetoothDeviceFound(function (res) {
            res.devices.forEach(device => {
                if (!device.name) {
                    return;
                }
                let name = device.name;
                if (name == blueName) {//根据设备名查找需要连接的蓝牙
                    let blueDeviceId = device.deviceId;
                    wx.setStorageSync('blueDeviceId', blueDeviceId);//设置蓝牙设备id
                    initFlag = true;//停止循环
                    _this.connetBlue(blueDeviceId);
                    _this.stopBluetoothDevicesDiscovery();
                }
            })

        })
    },
    connetBlue: function (blueDeviceId) {//4、连接低功耗蓝牙设备
        var _this = this;
        if (connected) {//已连接
            return;
        }
        wx.createBLEConnection({
            deviceId: blueDeviceId,
            success: function (res) {
                connected = true;
                _this.getBLEDeviceServices(blueDeviceId);//获取蓝牙服务
            },
            fail: function () {//连接失败 定时重连
                setTimeout(function () {
                    _this.connetBlue(blueDeviceId)
                }, 200)
            }
        })
    },
    getBLEDeviceServices: function (blueDeviceId) {//5、连接成功 获取蓝牙设备所有服务id serviceId
        var _this = this;
        wx.getBLEDeviceServices({
            deviceId: blueDeviceId,
            success: function (res) {
                let services = res.services;
                let serviceId = services[0].uuid;//uuid 第一个服务id
                wx.setStorageSync('blueServiceId', serviceId);
                _this.getBLEDeviceCharacteristics(blueDeviceId, serviceId);
            }
        })
    },
    getBLEDeviceCharacteristics: function (blueDeviceId, serviceId) {//6、获取特征值 并监听
        var _this = this;
        wx.getBLEDeviceCharacteristics({
            deviceId: blueDeviceId,
            serviceId: serviceId,
            success: function (res) {
                let charc = res.characteristics[0];//第一个特征值
                let cd20 = charc.uuid;
                let read = charc.properties.read;//该特征值是否支持 read 操作
                if (!read) { return; }
                wx.readBLECharacteristicValue({//开始读
                    deviceId: blueDeviceId,
                    serviceId: serviceId,
                    characteristicId: cd20,
                    success(res) { },
                    fail(err) { },
                })
                wx.notifyBLECharacteristicValueChange({//监听
                    state: true,
                    deviceId: blueDeviceId,
                    serviceId: serviceId,
                    characteristicId: cd20,
                    success(res) { }
                })
            }, fail: function (res) { }
        })
        _this.readListen(blueDeviceId);//监听特征值
    },
    readListen: function (blueDeviceId) {//7、获取特征值信息 关闭蓝牙连接 关闭模块
        var _this = this;
        wx.onBLECharacteristicValueChange(function (res) {
            if (res.characteristicId.indexOf("000002C0-") != -1) {//这个是电量 根据特征值id过滤想要监听的特征值
                let power = parseInt(_this.ab2hex(res.value));//读到的值buffer转字符串  
                wx.closeBLEConnection({//断开蓝牙连接
                    deviceId: blueDeviceId,
                    success(res) {
                        console.log(res)
                    }
                })
                wx.closeBluetoothAdapter({//关闭蓝牙模块
                    success (res) {
                      console.log(res)
                    }
                  })
            }
        })
    },
    showTip: function () {//提示
        wx.showToast({
            title: '请打开蓝牙',
            duration: 2000
        })
    },
    stopBluetoothDevicesDiscovery: function () {//停止搜索
        wx.stopBluetoothDevicesDiscovery({
            success: function (res) {
                console.log('关闭蓝牙搜索');
            }
        })
    },
    ab2hex: function (buffer) {//buffer 转字符串
        let hexArr = Array.prototype.map.call(
            new Uint8Array(buffer),
            function (bit) {
                return ('' + bit.toString(16)).slice(-2)
            }
        )
        return hexArr.join('');
    }
})


评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值