• 微信小程序低功耗蓝牙BLE快速开发js


    1、前言

    目的:

    1、为了能三分钟快速开发BLE模块,特此做一个笔记,按照笔记的顺序开发,能够简单、快速、规范。

    2、如果以后觉得有必要改动的地方就在这里更改。

    3、主要是记录BLE连接的步骤。
    在这里插入图片描述

    2、资料

    https://note.youdao.com/ynoteshare/index.html?id=d662c9c1c58121ec28901d78d9aa5e80

    比较完整的微信小程序BLE连接资料

    https://zhuanlan.zhihu.com/p/537636778

    3、BLE连接流程

    BLE连接原理

    • 第一步,扫描周围已打开蓝牙的BLE设备。
    • 第二步,扫描结束后在扫描的结果中选取一个符合条件的BLE设备,在APP扫描(BLE设备广播)的过程中,BLE设备会有以下几个属性用于辨别身份:蓝牙名、MAC、广播数据。
    • 第三步,对选取的BLE设备进行连接。
    • 第四步,连接成功后可以列出这个设备所包含的所有服务和特征,服务和特征是APP与设备进行交互的通道。
    • 第五步,对指定的特征进行通知、读、写等操作。常用的操作是notify和wirte,前者是APP接收BLE发过来的数据,后者是APP向BLE设备发送数据。
    • 第六步,APP与BLE设备断开连接。

    4、index.js页面加载流程详细说明

    (有了解过BLE的同学建议直接代码)

    • 1、首先进入 onLoad: function () 方法
    1、执行wx.openBluetoothAdapter()方法			// 初始化蓝牙模块。
    
    2、执行that.getBluetoothAdapterState();
    
    • 1
    • 2
    • 3
    • 2、that.getBluetoothAdapterState()方法
    1、wx.getBluetoothAdapterState()方法		//获取本机蓝牙适配器状态
    
    2、执行startBluetoothDevicesDiscovery()
    • 1
    • 2
    • 3
    • 3、startBluetoothDevicesDiscovery()方法
    1、执行wx.openBluetoothAdapter()方法		//不是很理解这个操作
    
    2、执行that.closeConnect();
    
    • 1
    • 2
    • 3
    • 4、closeConnect: function () 方法
    // 断开与蓝牙低功耗设备的连接。,确保上一个蓝牙断开(例如刚才连接着音乐什么的)
    1、执行wx.closeBLEConnection()方法 
    
    2、在上一个方法成功回调函数中执行that.closeBluetoothAdapter()方法	//关闭蓝牙适配器
    
    • 1
    • 2
    • 3
    • 4

    3、wx.startBluetoothDevicesDiscovery()方法, //开始搜寻附近的蓝牙外围设备。

    成功之后调用that.getBluetoothDevices()
    
    • 1
    • 5、getBluetoothDevices()方法
    1、执行 wx.getBluetoothDevices() 	 // 获取在蓝牙模块生效期间所有搜索到的蓝牙设备。
    
    真正查找蓝牙设备在这一步。通过指定的蓝牙设备名称去匹配。
    
    2、搜索到设备名称之后 停止搜寻附近的蓝牙外围设备,wx.stopBluetoothDevicesDiscovery
    
    3、调用 that.connectTO()开始连接蓝牙。
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    (温馨提示)连接蓝牙的条件: 设备名字(deviceId)

    以上所有的准备工作都是为了检查手机蓝牙情况、在蓝牙列表里面获取到设备名,只有存在于 蓝牙列表 里面的设备名称才可以连接上,不是单单知道设备名字就可以连接上的。
    
    例如:手机蓝牙A,要连接的设备B
    
    A是主动,B是被动,
    
    要求是A找到B的名字并添加到 蓝牙列表 里面,同时添加的可能会很多(有可能添加了一百个设备),但是我们只要B,所以在 蓝牙列表 里面找出B,最后调用连接的方法,即可连接成功。
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 6、connectTO()方法
    1、wx.createBLEConnection()		// 连接蓝牙
    
    2、调用that.getBLEDeviceServices();方法
    
    • 1
    • 2
    • 3
    • 7、getBLEDeviceServices: function ()
    //获取蓝牙低功耗设备所有服务 (service)。在这里同时选取出所需的服务
    1、调用wx.getBLEDeviceServices方法
    
    
    • 1
    • 2
    • 3
    • 8、getBLEDeviceCharacteristics: function ()
    
    1、 wx.getBLEDeviceCharacteristics()	// 获取蓝牙低功耗设备某个服务中所有特征 (characteristic)。
    
    以上就是连接蓝牙的整个过程
    
    
    • 1
    • 2
    • 3
    • 4
    • 5

    完整代码:

    //index.js
    //获取应用实例
    const app = getApp()
    var that; //把this对象复制到临时变量that
    Page({
        data: {
            status: "未连接",
            msg: "BLEHID",
            deviceId: "",
            connectedDeviceId: "", //已连接设备uuid
            deviceName: "ble2usbhid",
            ServicweId: '',
            writeCharacteristicsId: "",
            strcmd: 'K:ABC123',
    
        },
        //事件处理函数
        bindViewTap: function () {
            wx.navigateTo({
                url: '../logs/logs'
            })
        },
    
        // 当用户离开页面时发生的事件
        onUnload: function () {
            that.closeBLEConnection()
            that.closeBluetoothAdapter()
        },
        onLoad: function () {
            that = this;
            // 1、初始化蓝牙模块。
            if (wx.openBluetoothAdapter) {
                wx.openBluetoothAdapter({
                    success: function (res) {
                        /* 获取本机的蓝牙状态 */
                        that.getBluetoothAdapterState()
                    },
                    fail: function (err) {}
                })
            } else {
    
            }
        },
        // 2、获取本机蓝牙适配器状态
        getBluetoothAdapterState: function () {
            wx.getBluetoothAdapterState({
                success: function (res) {
                    that.startBluetoothDevicesDiscovery()
                },
                fail(res) {
                    console.log(res)
                }
            })
        },
        // 3、关闭蓝牙连接,并且 开始搜寻附近的蓝牙外围设备。 此处方法也应该是“连接蓝牙”按钮的调用方法
        startBluetoothDevicesDiscovery: function () {
            wx.openBluetoothAdapter({})
            that.closeConnect();
            that.setData({
                devices: {}
            })
            setTimeout(() => {
                wx.startBluetoothDevicesDiscovery({
                    success: function (res) {
                        /* 获取蓝牙设备列表 */
                        that.getBluetoothDevices()
                    },
                    fail(res) {}
                })
            }, 500)
        },
    
        /**4、获取在蓝牙模块生效期间所有搜索到的蓝牙设备。
         * 包括已经和本机处于连接状态的设备。
         *  */
        getBluetoothDevices: function () {
            setTimeout(() => {
                wx.getBluetoothDevices({
                    services: [],
                    allowDuplicatesKey: false,
                    interval: 0,
                    success: function (res) {
                        console.log(JSON.stringify(res.devices))
    
                        that.setData({
                            devices: res.devices,
                        })
    
                        if (res.devices.length > 0) {
    
                            for (let i = 0; i < res.devices.length; i++) {
                                console.log(res.devices[i].name);
                                if ('ble2usbhid' === res.devices[i].name) {
                                    /* 根据指定的蓝牙设备名称匹配到deviceId */
    
                                    that.deviceId = res.devices[i].deviceId,
                                        wx.stopBluetoothDevicesDiscovery({
                                            success: function (res) {
                                                console.log(res, '已停止搜索')
                                            },
                                            fail(res) {
                                                console.log(res, '停止搜索失败')
                                            }
                                        })
    
                                    that.connectTO();
    
                                };
                            };
    
                        } else {}
                    },
                    fail(res) {
                        console.log(res, '获取蓝牙设备列表失败=====')
                    }
                })
            }, 50)
        },
    
        // 5、连接蓝牙
        connectTO: function () {
            wx.createBLEConnection({
                deviceId: that.deviceId,
                success: function (res) {
                    that.connectedDeviceId = that.deviceId;
                    /* 4.获取连接设备的service服务 */
                    that.getBLEDeviceServices();
                },
                fail: function (res) {
                    that.setData({
                        status: "连接失败",
                        msg: "连接失败!请重试",
                    })
                }
            })
        },
        // 6、获取蓝牙低功耗设备所有服务 (service)。并且选出 FFE0 服务
        getBLEDeviceServices: function () {
            setTimeout(() => {
                wx.getBLEDeviceServices({
                    deviceId: that.connectedDeviceId,
                    success: function (res) {
                        that.setData({
                            msg: "发现服务" + JSON.stringify(res.services)
                        })
                        for (var i = 0; i < res.services.length; i++) {
    
                            if (res.services[i].uuid.indexOf("FFE0") >= 0) {
                                that.setData({
                                    msg: "已发现服务" + res.services[i].uuid
                                })
                                that.services = res.services[i]
                                /* 获取连接设备的所有特征值 */
                                that.getBLEDeviceCharacteristics()
                                break;
                            }
                        }
                    },
                    fail: (res) => {
                        console.log(res)
                        that.setData({
                            msg: "服务搜索失败"
                        })
                    }
                })
            }, 500)
        },
        // 7、获取蓝牙低功耗设备某个服务中所有特征 (characteristic)。
        getBLEDeviceCharacteristics: function () {
            console.log("find char of " + that.services.uuid)
            setTimeout(() => {
                wx.getBLEDeviceCharacteristics({
                    deviceId: that.connectedDeviceId,
                    serviceId: that.services.uuid,
                    success: function (res) {
                        that.setData({
                            msg: "发现特征" + res.characteristics.length
                        })
                        console.log('蓝牙特征值UUID:', res.characteristics)
                        for (var i = 0; i < res.characteristics.length; i++) {
    
    
                            if (res.characteristics[i].properties.write && res.characteristics[i].uuid.indexOf('FFE3') >= 0) {
                                that.setData({
                                    status: "已就绪",
                                    msg: "连接成功 可以操作",
                                })
                                /* 获取蓝牙特征值 */
                                that.ServicweId = that.services.uuid;
                                that.writeCharacteristicsId = res.characteristics[i].uuid
                                // 启用低功耗蓝牙设备特征值变化时的 notify 功能
                                // that.notifyBLECharacteristicValueChange()
    
                                break;
                            }
                        }
    
                    },
                    fail: function (res) {}
                })
            }, 100)
        },
    
        notifyBLECharacteristicValueChange: function () { // 启用低功耗蓝牙设备特征值变化时的 notify 功能
            console.log('启用低功耗蓝牙设备特征值变化时的 notify 功能')
            wx.notifyBLECharacteristicValueChange({
                state: true,
                deviceId: that.connectedDeviceId,
                serviceId: that.ServicweId,
                characteristicId: that.notifyCharacteristicsId,
                complete(res) {
                    /*用来监听手机蓝牙设备的数据变化*/
                    wx.onBLECharacteristicValueChange(function (res) {
                        that.setData({
                            msg: 'reveive:' + that.receiveData(res.value)
                        })
                    })
                },
                fail(res) {
                    console.log(res, '启用低功耗蓝牙设备监听失败')
                }
            })
        },
    
        // 断开设备连接
        closeConnect: function () {
            if (that.connectedDeviceId) {
                wx.closeBLEConnection({
                    deviceId: that.connectedDeviceId,
                    success: function (res) {
                        that.closeBluetoothAdapter()
                    },
                    fail(res) {}
                })
            } else {
                //that.closeBluetoothAdapter()
            }
        },
        // 关闭蓝牙模块
        closeBluetoothAdapter: function () {
            wx.closeBluetoothAdapter({
                success: function (res) {},
                fail: function (err) {}
            })
        },
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174
    • 175
    • 176
    • 177
    • 178
    • 179
    • 180
    • 181
    • 182
    • 183
    • 184
    • 185
    • 186
    • 187
    • 188
    • 189
    • 190
    • 191
    • 192
    • 193
    • 194
    • 195
    • 196
    • 197
    • 198
    • 199
    • 200
    • 201
    • 202
    • 203
    • 204
    • 205
    • 206
    • 207
    • 208
    • 209
    • 210
    • 211
    • 212
    • 213
    • 214
    • 215
    • 216
    • 217
    • 218
    • 219
    • 220
    • 221
    • 222
    • 223
    • 224
    • 225
    • 226
    • 227
    • 228
    • 229
    • 230
    • 231
    • 232
    • 233
    • 234
    • 235
    • 236
    • 237
    • 238
    • 239
    • 240
    • 241
    • 242
    • 243
    • 244
    • 245
    • 246

    END

  • 相关阅读:
    白盒测试与黑盒测试
    我们一起来谈谈高并发和分布式系统的幂等如何处理!
    13.(开发工具篇github)如何在GitHub上上传本地项目
    【Docker命令】日常使用的Docker命令
    【rainbowzhou 面试11/101】技术提问--说说你做的大数据性能测试案例
    4.3 实现注册模块与登录状态持久化
    数据挖掘技术-掌握pyplot基础语法
    微服务(一) go kratos 用户服务
    nginx 禁止直接访问目录或文件
    c++ 一个学习小组有5个人,每个人有三门课(高数、英语和C语言)的考试成绩,求每人的平均成绩。按行输出每个学生的各科成绩及平均成绩。
  • 原文地址:https://blog.csdn.net/qq_43813351/article/details/127650609