保姆级微信小程序对接蓝牙设备教程。微信小程序发送不同蓝牙指令(定时发送,断开重连,判断是否有蓝牙权限等)

本文提供了一个完整的微信小程序实现蓝牙设备连接、发送指令、监听返回的示例,包括初始化蓝牙、搜索设备、连接设备、获取服务和特征值、发送和接收指令等关键步骤。同时,文章包含了错误处理和页面生命周期管理,确保设备连接的稳定性和效率。

本文是一个完整的对接设备,发送不同指令监听不同返回的完整示例,可根据实际项目按需更改。

注:app.showModal 为在app.js中封装的showModal方法,then(()=>{})代表用户点击confirm,可用wx.showModal代替。

公用方法

function inArray(arr, key, val) {
   
   
    for (let i = 0; i < arr.length; i++) {
   
   
        if (arr[i][key] === val) {
   
   
            return i;
        }
    }
    return -1;
}

function split_array(arr, len) {
   
   
    var a_len = arr.length;
    var result = [];
    for (var i = 0; i < a_len; i += len) {
   
   
        result.push(arr.slice(i, i + len));
    }
    return result;
}

function calcCrc(dataView) {
   
   
	//计算指令的合取最低8位,是因为这个设备的指令是这个需求,实际按设备对接文档来
    let crc = 0;
    for (let i = 0; i < 15; i++) {
   
   
        crc += dataView.getUint8(i);
    }
    return crc
}
/**
 *ArrayBuffer转16进制字符串
 * @param {buffer} buffer 
 */
function ab2hex(buffer) {
   
   
    let hexArr = Array.prototype.map.call(
        new Uint8Array(buffer),
        function (bit) {
   
   
            return ('00' + bit.toString(16)).slice(-2)
        }
    )
    return hexArr.join('');
},
/**
 * 16进制字符串转字节数组
 * @param {string} str 
 */
function str2Bytes(str) {
   
   
    let pos = 0;
    let len = str.length;
    if (len % 2 != 0) {
   
   
        return null;
    }
    len /= 2;
    let hexA = new Array();
    for (let i = 0; i < len; i++) {
   
   
        let s = str.substr(pos, 2);
        let v = s; //处理
        hexA.push(v);
        pos += 2;
    }
    return hexA;
},
/**
 * 反转
 * @param {string} num 
 */
function reverse(num) {
   
   
    return num.split(',').reverse().join('');
},

请求设备列表

getList() {
   
   
    let ble = wx.getStorageSync('bleLink') || false; //设备是否连接中的变量,跳转其他页面也可使用
    wx.showLoading({
   
   
        title: '加载中...'
    });
    app.get("/getDevice").then(res => {
   
   
        if (res.data.data.length > 0) {
   
   
            console.log('有设备')
            let data = res.data.data[0];
            data.createTime = util.datatotime(data.createTime);
            this.setData({
   
   
                deviceList: [data],
                deviceId: data.deviceId,
                deviceName: data.deviceName,
                hasDevice: true,
                ble
            })
            this._discoveryStarted = false;
            this._deviceId = data.deviceId;
            console.log('--------- getList', this.data.deviceList)
            if (!ble) {
   
   
                console.log('已绑定设备但是未连接')
                this.settingBlue();
            } else {
   
   
                console.log('已绑定设备但是已连接')
                this.getBLEDeviceServices(this._deviceId);
            }
        } else {
   
   
            console.log('暂无设备')
            this._discoveryStarted = false;
        }
    })
},

1. 判断是否有蓝牙权限

/**
 * 开始蓝牙
 */
settingBlue() {
   
   
    wx.showLoading({
   
   
        title: '获取蓝牙中...',
    })
    wx.getSetting({
   
   
        success: (res) => {
   
   
            wx.hideLoading()
            if (res.authSetting.hasOwnProperty('scope.bluetooth')) {
   
   
                //'scope.bluetooth'属性存在,且为false
                if (!res.authSetting['scope.bluetooth']) {
   
   
                    //拒绝授权 弹窗授权
                    app.showModal({
   
   
                        content: '您还未授权使用蓝牙,请点击“确定”开启蓝牙授权~'
                    }).then(() => {
   
   
                        wx.openSetting({
   
   
                            success(res) {
   
   
                            	//监听到用户同意授权蓝牙
                                this.openBluetoothAdapter();
                            }
                        
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

天外来鹿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值