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

  • Post author:
  • Post category:小程序




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();
  • 2、that.getBluetoothAdapterState()方法
1、wx.getBluetoothAdapterState()方法		//获取本机蓝牙适配器状态

2、执行startBluetoothDevicesDiscovery()
  • 3、startBluetoothDevicesDiscovery()方法
1、执行wx.openBluetoothAdapter()方法		//不是很理解这个操作

2、执行that.closeConnect();
  • 4、closeConnect: function () 方法
// 断开与蓝牙低功耗设备的连接。,确保上一个蓝牙断开(例如刚才连接着音乐什么的)
1、执行wx.closeBLEConnection()方法 

2、在上一个方法成功回调函数中执行that.closeBluetoothAdapter()方法	//关闭蓝牙适配器

3、

wx.startBluetoothDevicesDiscovery()方法

, //开始搜寻附近的蓝牙外围设备。

成功之后调用that.getBluetoothDevices()
  • 5、getBluetoothDevices()方法
1、执行 wx.getBluetoothDevices() 	 // 获取在蓝牙模块生效期间所有搜索到的蓝牙设备。

真正查找蓝牙设备在这一步。通过指定的蓝牙设备名称去匹配。

2、搜索到设备名称之后 停止搜寻附近的蓝牙外围设备,wx.stopBluetoothDevicesDiscovery

3、调用 that.connectTO()开始连接蓝牙。


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

以上所有的准备工作都是为了检查手机蓝牙情况、在蓝牙列表里面获取到设备名,只有存在于 蓝牙列表 里面的设备名称才可以连接上,不是单单知道设备名字就可以连接上的。

例如:手机蓝牙A,要连接的设备B

A是主动,B是被动,

要求是A找到B的名字并添加到 蓝牙列表 里面,同时添加的可能会很多(有可能添加了一百个设备),但是我们只要B,所以在 蓝牙列表 里面找出B,最后调用连接的方法,即可连接成功。
  • 6、

    connectTO()方法
1、wx.createBLEConnection()		// 连接蓝牙

2、调用that.getBLEDeviceServices();方法
  • 7、

    getBLEDeviceServices: function ()
//获取蓝牙低功耗设备所有服务 (service)。在这里同时选取出所需的服务
1、调用wx.getBLEDeviceServices方法

  • 8、

    getBLEDeviceCharacteristics: function ()

1、 wx.getBLEDeviceCharacteristics()	// 获取蓝牙低功耗设备某个服务中所有特征 (characteristic)。

以上就是连接蓝牙的整个过程



完整代码:

//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) {}
        })
    },
})



END



版权声明:本文为qq_43813351原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。