发布于 3年前

如何在uni-app读取蓝牙设备

读取蓝牙设备主要逻辑步骤

1、初始化蓝牙

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

3、监听寻找到新设备的事件

4、获取在蓝牙模块生效期间所有已发现的蓝牙设备

<script>
    export default {
        onLoad() {
            //在页面加载时候初始化蓝牙适配器
            uni.openBluetoothAdapter({
                success: e => {
                    console.log('初始化蓝牙成功:' + e.errMsg);
                    this.$data.isOpenBle = true;
                    console.log(this.$data.isOpenBle);
                    // 初始化完毕开始搜索
                    this.startBluetoothDeviceDiscovery()
                },
                fail: e => {
                    console.log('初始化蓝牙失败,错误码:' + (e.errCode || e.errMsg));
                }
            });
        },
        methods: {
            startBluetoothDeviceDiscovery() {
                //在页面显示的时候判断是都已经初始化完成蓝牙适配器若成功,则开始查找设备
                let self = this;
                setTimeout(function() {
                    if (self.isOpenBle) {
                        console.log("开始搜寻智能设备");
                        uni.startBluetoothDevicesDiscovery({
                            success: res => {
                                self.onBluetoothDeviceFound();
                            },
                            fail: res => {
                                console.log("查找设备失败!");
                                uni.showToast({
                                    icon: "none",
                                    title: "查找设备失败!",
                                    duration: 3000
                                })
                            }
                        });
                    } else {
                        console.log("未初始化蓝牙是配饰器:" + self.isOpenBle);
                    }
                }, 300);
            },
            /**
             * 停止搜索蓝牙设备
             */
            stopBluetoothDevicesDiscovery() {
                uni.stopBluetoothDevicesDiscovery({
                    success: e => {
                        console.log('停止搜索蓝牙设备:' + e.errMsg);
                    },
                    fail: e => {
                        console.log('停止搜索蓝牙设备失败,错误码:' + e.errCode);
                    }
                });
            },
            /**
             * 发现外围设备
             */
            onBluetoothDeviceFound() {
                console.log("监听寻找新设备");
                // this.getBluetoothDevices();
                uni.onBluetoothDeviceFound(devices => {
                    console.log('开始监听寻找到新设备的事件');
                    this.getBluetoothDevices();
                });
            },
            /**
             * 获取在蓝牙模块生效期间所有已发现的蓝牙设备。包括已经和本机处于连接状态的设备。
             */
            getBluetoothDevices() {
                console.log("获取蓝牙设备");
                uni.getBluetoothDevices({
                    success: res => {
                        console.log('获取蓝牙设备成功:' + res.errMsg);
                        console.log(res)
                    }
                });
            }
        }
    }
</script>
©2020 edoou.com   京ICP备16001874号-3