微信小程序蓝牙功能

1,347 阅读2分钟

1.初始化蓝牙

function openBluetooth() {
    wx.openBluetoothAdapter({
        success() {
            setTimeout(()=>{
                getBluetoothAdapterState()
            }, 200)
        },
        fail() {
            console.log('手机蓝牙未打开')
        }
    })
}

2.检测蓝牙是否可用

function getBluetoothAdapterState() {
    wx.getBluetoothAdapterState({
        success(res) {
            if (res.available) {
                startBluetoothDevicesDiscovery()
            }
        },
        fail(error) {
            
        }
    })
}

3.开始搜索蓝牙设备

function startBluetoothDevicesDiscovery() {
    wx.startBluetoothDevicesDiscovery({
        success(res) {
            getBluetoothDevices()
        },
        fail(error) {

        }
    })
}

4.获取搜索的蓝牙,监听搜索蓝牙事件

function getBluetoothDevices() {
    wx.getBluetoothDevices({  //获取搜索的蓝牙
        success(res) {
            setTimeout(()=>{
                if(res.devices.length < 1) {
                    wx.stopBluetoothDevicesDiscovery()
                    wx.closeBluetoothAdapter()
                }
            }, 15000)
        }
    })

    wx.onBluetoothDeviceFound(res=>{
        let devices = res.devices
        for(let item of devices) {
            let advertisData = buf2hex(item.advertisData)
            if(advertisData.toUpperCase().indexOf('蓝牙Mac地址') != -1) {
                let deviceId = item.deviceId // 蓝牙设备ID
                wx.stopBluetoothDevicesDiscovery({
                    success(result) {
                        setTimeout(()=>{
                            createBLEConnection(deviceId)
                        }, 200)
                    }
                })
            }
        }
    })
}

5.连接蓝牙

function createBLEConnection(deviceId) {
    wx.createBLEConnection({
        deviceId,
        success(res) {
            getBLEDeviceServices(deviceId)
        }
    })
}

6.获取蓝牙的service服务

function getBLEDeviceServices(deviceId) {
    wx.getBLEDeviceServices({
        deviceId,
        success(res) {
            getBLEDeviceCharacteristics(deviceId)
        }
    })
}

7.获取蓝牙设备特征值,拿到对应的读写的uuid

function getBLEDeviceCharacteristics(deviceId) {
    wx.getBLEDeviceCharacteristics({
        deviceId,
        serviceId: '蓝牙的service uuid',
        success(res) {
            setTimeout(()=>{
                notifyChange(deviceId)
            }, 200)
        }
    })
}

8.启用蓝牙notify功能,用来监听蓝牙之间的数据传输

function notifyChange(deviceId) {
    wx.notifyBLECharacteristicValueChange({
        deviceId,
        serviceId: '蓝牙的service uuid',
        characteristicId: '蓝牙的notify uuid',
        state: true,
        success(res) {
            onBLECharacteristicValueChange()
        }
    })
}

9.监听蓝牙设备之间的数据传输

function onBLECharacteristicValueChange() {
    wx.onBLECharacteristicValueChange(res=>{
        let data = buf2string(res.value) //解析成十进制,正常文本
    })
}

10.向蓝牙发送数据

function sendData() {
    let str = '00010203' // 发送的数据
    //转换成ArrayBuffer格式
    let dataBuffer = new ArrayBuffer(str.length)
    let dataView = new DataView(dataBuffer)
    for (var i = 0; i < str.length; i++) {
        dataView.setUint8(i, str.charAt(i).charCodeAt())
    }
    let dataHex = buf2hex(dataBuffer)

    wx.writeBLECharacteristicValue({
        deviceId: '设备ID',
        serviceId: '蓝牙的service uuid',
        characteristicId: '蓝牙的write uuid',
        value: '需要传输的数据,格式为ArrayBuffer'
    })
}

11.工具方法

// 转成十进制, 正常文字,不常用
function hexCharCodeToStr(hexCharCodeStr) {
    let trimedStr = hexCharCodeStr.trim()
    let rawStr = trimedStr.substr(0, 2).toLowerCase() === '0x' ? trimedStr.substr(2) : trimedStr
    let curCharCode = ''
    let resultStr = []
    for (let i = 0; i < rawStr.length; i = i + 2) {
        curCharCode = parseInt(rawStr.substr(i, 2), 16)
        resultStr.push(String.fromCharCode(curCharCode))
    }
    return resultStr.join('')
}

function receiveData(buffer) {
    return hexCharCodeToStr( buf2hex(buffer) )
}

//转成十进制,正常文字,常用
function buf2string(buffer) {
    let arr = Array.prototype.map.call(new Uint8Array(buffer), x => x)
    return arr.map((char, i) => {
        return String.fromCharCode(char)
    }).join('')
}

// 转成二进制
function buf2hex(buffer) {
    let hexArr = Array.prototype.map.call(new Uint8Array(buffer), bit=>{
        return ('00' + bit.toString(16)).slice(-2)
    })
    return hexArr.join('')
}