uniapp开发app对接蓝牙

本文详细描述了在使用Uniapp开发环境下,如何通过蓝牙适配器、搜索设备、获取服务以及操作特征值等步骤来实现对Modbus协议蓝牙设备的连接和数据交互的过程。

依稀记得去年第一次对接蓝牙设备的啥时候的无助,其实这些流程文档上写的挺清楚的,别人的博客写的也很清晰,但我依然觉得头大。

因为那个项目对接的设备用的是modbus协议,真的是让人好一番琢磨,包括蓝牙设备服务、特征值也搞错过好几次。

苍天不负有心人呀~~

1、初始化蓝牙适配器

// 打开蓝牙适配器
initBlue() {
    var that = this
    //打开蓝牙适配器接口
    uni.openBluetoothAdapter({
        success(res) {
            console.log("打开蓝牙适配器接口成功",res)
            that.findBlue();
        },
        fail(err) { 
            console.log("打开蓝牙适配器接口失败",err)
        }
    })
}

2、开始搜索周围蓝牙设备

// 搜索周边设备
findBlue() {
    var that = this
    uni.startBluetoothDevicesDiscovery({
        allowDuplicatesKey: false,
        interval: 0,
        success: function(res) {
            console.log("开始搜索",err) 
            uni.onBluetoothDeviceFound(devices => {
                // 监听到新设备后重新获取设备列表
                that.getBlue()
            });
        },
        fail: function() {
            console.log("开始搜索失败",err)   
        }
    })
}

3、获取蓝牙初始化后所有的设备

// 获取搜索到的设备信息
getBlue() {
    var that = this
    uni.getBluetoothDevices({
        success(res) {
        console.log("获取设备成功",err)
            that.BluetoothList = res.devices
        },
        fail(err) {
            console.log("获取设备失败",err)       
        }
    })
}

4、连接选中的设备

connetBlue() {
    var that = this;
    let deviceId = that.deviceInfo.deviceId; // 选中后赋值
    uni.createBLEConnection({
        deviceId: that.deviceInfo.deviceId, //设备id
        success(res) {
            // console.log("连接蓝牙成功", res)
            // 连接蓝牙成功之后关闭蓝牙搜索 搜索功能费性能
            uni.stopBluetoothDevicesDiscovery({
                success: function(res) {
                // console.log('关闭蓝牙搜索成功');
                }
            })                                              that.getServiceId(that.deviceInfo) //获取蓝牙设备服务
        },
        fail() {
            // console.log("连接蓝牙失败")
        }
    })
}

5、获取蓝牙设备服务

getServiceId(item) {
    let deviceId = item.deviceId
    var that = this
    // 直接获取服务可能会获取不到 加一个延时
    setTimeout(() => {
        uni.getBLEDeviceServices({
            deviceId: item.deviceId,
            success(res) {
                that.uuid.deviceId = deviceId
                that.uuid.serviceId = res.services[2].uuid //因设备而议:该特征值支持write和notfy服务
                that.getCharacteId(that.uuid) 
            },
            fail() {
                // console.log('获取蓝牙特征值失败')
            }
        })
    }, 1000)
}

6、获取蓝牙特征值

// 获取蓝牙特征值
getCharacteId(item) {
    var that = this
    uni.getBLEDeviceCharacteristics({
        deviceId: item.deviceId,
        serviceId: item.serviceId,
        success(res) {
            // console.log('获取蓝牙特征值成功', res)
            for (var i = 0; i < res.characteristics.length; i++) {
                var model = res.characteristics[i]
                if (model.properties.write) {
                    that.uuid.writeId = model.uuid;
                }
                if (model.properties.notify) {
                    that.uuid.notifyId = model.uuid
                }
            }
            that.startNotice(that.uuid) // 启用 notify 功能
            setTimeout(() => {
                that.sendMy('0103211D00011E30') //写数据
            }, 1000)
        },
        fail() {
            // console.log('获取蓝牙特征值失败', res)
        }
    })
}

7、启用 notify 功能

// 启用 notify 功能
startNotice(e) {
    let that = this
    uni.notifyBLECharacteristicValueChange({
        state: true, // 启用 notify 功能
        deviceId: e.deviceId,
        serviceId: e.serviceId,
        characteristicId: e.notifyId,
        success(res){
            console.log('启用 notify 功能', res)
            //监听设备发送数据
            uni.onBLECharacteristicValueChange((sjRes) => {
    that.getdata = that.ab2hex(sjRes.value)
    console.log('监听设备发送数据', that.getdata)
})
        },
        fail(res) {
            // console.log('启用 notify 功能失败', res)
        }
    })
}

8、写入数据

// 写入数据
sendMy(str) {
    let that = this
    //转换数据格式
    let buffer = that.string2buffer(str);
    uni.writeBLECharacteristicValue({
        deviceId: that.uuid.deviceId, // 蓝牙设备 deviceId
        serviceId:that.uuid.serviceId, // 蓝牙服务uuid
        characteristicId:that.uuid.writeId, // 蓝牙特征值writeId
        value: buffer, // 这里的value是ArrayBuffer类型
        writeType: 'write',
        success(res) {
            console.log('指令下发成功', res)
        },
        fail(err) {
            // console.log('指令发送失败', err)
        }
    })
}

9、断开连接

// 断开连接
cancelConcent(e) {
    let that = this
    if (that.device.name != '--') {
        uni.closeBLEConnection({
            deviceId: that.device.deviceId,
            success(res) {
                console.log(' 断开连接成功', res)
            },
            fail(err) {
                console.log(' 断开连接失败', err)
            },
        })
    }
}

附:app请求打开蓝牙

openBlue() {
    const BluetoothAdapter = plus.android.importClass('android.bluetooth.BluetoothAdapter');
    const blueadapter = BluetoothAdapter.getDefaultAdapter(); //拿到默认蓝牙适配器方法
    if (blueadapter) {
        // 判断蓝牙是否开启
        if (blueadapter.isEnabled()) {
        // 已开启
    } else {
        // 未开启弹出提示框
        uni.showModal({
            title: '提示',
            content: '蓝牙尚未打开,是否打开蓝牙',
            showCancel: true,
            cancelText: '取消',
            confirmText: '确定',
            success(res) {
                // 点击确定后通过系统打开蓝牙
                if (res.confirm) {
                    const blueadapter = BluetoothAdapter.getDefaultAdapter();
                    if (blueadapter != null) {
                    return blueadapter.enable();
                    }
                } 
            }
        })
    }
}

码云:大鱼海棠/blueTooth-uniapp

有问题的话,大家可以探讨一下,我知道的话都会解答的

评论 16
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值