微信小程序实现蓝牙连接通讯

由于最近的项目在做小程序蓝牙通讯这块的内容,所以将实现的过程在这简单的记录下。

1、首先要初始化蓝牙-检查蓝牙适配器是否打开

 async initBluetooth(): Promise<void> {
        return new Promise((resolve: any, reject: any) => {
            const _this = this
            if (BluetoothController.adapterOpend) {
                console.log("蓝牙适配器已打开")
                resolve(true)
                return
            }
            wx.openBluetoothAdapter({
                success(res) {
                    BluetoothController.adapterOpend = true
                    console.log("=====*****蓝牙适配器已打开")
                    resolve(true)
                },
                fail(error) { //用来判断蓝牙是否已打开
                    reject(error)
                    BluetoothController.adapterOpend = false
                    console.log("=====*****蓝牙适初始化失败", error)
                }
            })
        })
    }

//使用案例
initBluetooth().then()

2、开始搜寻附近的蓝牙外围设备

 /**
     * @param options 
     * options.keywords  蓝牙名称筛选关键字
     * options.deviceid  可选参数,蓝牙设备id,连接用
     */
    async searchAroundBLE(options: any): Promise<void> {
        return new Promise((resolve: any, reject: any) => {
            const _this = this
            if (_this.startDiscovery) {
                console.log("已开启蓝牙扫描,勿重复开启")
                resolve(true)
                return
            }
            _this.startDiscovery = true
            wx.startBluetoothDevicesDiscovery({
                allowDuplicatesKey: true,
                services: options.services,
                success(res) {
                    console.log('搜索成功', res);
                    resolve(true)

                },
                fail(error) {
                    reject(error)
                    _this.startDiscovery = false
                },
            })
        })

    }


//使用案例
 searchAroundBLE({ 'keywords': [''], services: [] }).then()

3、监听搜索到的设备

 /**
     * @param options 
     * options.keywords  蓝牙名称筛选关键字
     * options.deviceid  可选参数,蓝牙设备id,连接用
     */
    async onBluetoothDeviceFound(options: any): Promise<void> {
        return new Promise((resolve: any, reject: any) => {
            let _this = this
            let { keywords } = options
            // 超时自动结束
            _this.findTimer = setTimeout(() => {
                clearTimeout(_this.findTimer)
                if (!_this.connectStatus) {
                   reject({ 
                        success: false
                    })
             
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值