自学内容网 自学内容网

vue h5 蓝牙连接 webBluetooth API

  1. webBluetooth API的 缺点, 只能固定的几个浏览器使用,其他浏览器打开使用不了这个api,ios也用不了,因为ios的浏览器内核都不属于webBluetooth 的条件
    在这里插入图片描述

  2. 因为使用的地方比较多 所以在main.js 进行全部封装

// 蓝牙服务
Vue.prototype.$bluetooth={
    device:null,//设备
    server:null,//服务
    isItConnect:false,//蓝牙状态判断
    connectingInProgress:false,//蓝牙状态判断
    doYouWantToRefresh:false,//刷新当前页面
    bluetoothInterval:null,//监听
    keyRandomCode:''//密钥随机码
}
// 开始监听蓝牙连接状态
Vue.prototype.$startBluetoothMonitoring=function (){
    Vue.prototype.$bluetooth.bluetoothInterval = setInterval(Vue.prototype.$checkBluetoothConnection, 5000); // 每5秒检查一次
}
// 停止监听蓝牙连接状态
Vue.prototype.$stopBluetoothMonitoring=function() {
    if (Vue.prototype.$bluetooth.bluetoothInterval) {
        clearInterval(Vue.prototype.$bluetooth.bluetoothInterval);
        Vue.prototype.$bluetooth.bluetoothInterval=null
    }
}
    // 检查蓝牙连接状态   因为没法监听蓝牙舒服断开得用定时器去不停的写入指令  如果写入失败就是蓝牙断开了
Vue.prototype.$checkBluetoothConnection=function () {
    // console.log(Vue.prototype.$bluetooth.device,this)
    if (!Vue.prototype.$bluetooth.device) {
        console.log('No device connected.');
        return;
    }
        Vue.prototype.$bluetooth.server.getPrimaryServices().then(services=>{
            let uuid= services.filter(el=>{return el.uuid.indexOf(
                '0000ffc0') != -1})
            if(uuid){
                Vue.prototype.$bluetooth.server.getPrimaryService(uuid[0].uuid).then(service => {
                    service.getCharacteristics().then(characteristics=>{
                        console.log(characteristics,'所有特征')
                        service.getCharacteristic(characteristics[0].uuid).then(characteristic => {
                            var hexArray = [0x66, 0xf1, 0x3b, 0x77];
                            // 创建一个 Uint8Array 实例
                            const uint8Array = new Uint8Array(hexArray);
                            // 获取 ArrayBuffer
                            const arrayBuffer = uint8Array.buffer;
                            characteristic.writeValue(arrayBuffer).then(() => {
                                // 写入成功
                            }).catch(error => {
                                console.log('Error reading characteristic:', error);
                                Vue.prototype.$disconnectConnection()
                                console.log('写入失败')
                                // 写入特征时出错
                            });

                        })
                    })
                })
            }


        })



    
}
// 断开蓝牙
Vue.prototype.$disconnectConnection=function (){
    Vue.prototype.$bluetooth.device.gatt.disconnect()
}
// 处理设备断开连接的情况
Vue.prototype.$onDisconnected=function (event) {
    let device=''
    if(event){
        device=event.target
    }
    console.log(device,'设备断开')
    Vue.prototype.$bluetooth.isItConnect=false
    Vue.prototype.$stopBluetoothMonitoring()
    Vue.prototype.$bluetooth.device=null
    if(!Vue.prototype.$bluetooth.doYouWantToRefresh){
        this.$dialog.alert({
            title: window.$i18n.t('提示'),
            message:  window.$i18n.t('蓝牙已断开请重新连接'),
            confirmButtonText:window.$i18n.t('确定'),
            confirmButtonColor:'#4800E0'
        }).then(() => {
            location.reload()
            // this.getLanya()
            // on close
        });
    }
    console.log('通知用户设备断开连接');
}
//蓝牙搜索并连接
Vue.prototype.$bluetoothConnectivity=function (vmNumber,manufacturerId,source,numIn){
    let optionalServices=[]
    navigator.bluetooth.requestDevice({
        filters: [{
            name: vmNumber //蓝牙名称
        }],
        optionalServices: optionalServices //服务值 小写
    }).then(device => {
        Vue.prototype.$bluetooth.device=device
        Vue.prototype.$bluetooth.connectingInProgress=true
        this.$store.dispatch("bluetooth/setIsItConnect",true);
        // 设备已被发现
        device.gatt.connect().then(server => {
            Vue.prototype.$bluetooth.server=server
            // 蓝牙监听
            device.addEventListener('gattserverdisconnected', Vue.prototype.$onDisconnected);
            this.$store.dispatch("bluetooth/setIsItConnect",true);
            this.$store.dispatch("bluetooth/setConnectingInProgress",false);
            Vue.prototype.$bluetooth.isItConnect=true
            Vue.prototype.$bluetooth.connectingInProgress=false
        })
            .catch(error => {
                Vue.prototype.$bluetooth.isItConnect=false
                Vue.prototype.$bluetooth.connectingInProgress=false
                Vue.prototype.$bluetooth.server=null
                Vue.prototype.$bluetooth.device=null
                this.$store.dispatch("bluetooth/setIsItConnect",false);
                this.$store.dispatch("bluetooth/setConnectingInProgress",false);
                this.$dialog.alert({
                    title: window.$i18n.t('提示'),
                    message:  window.$i18n.t('连接失败请重新连接'),
                    confirmButtonText:window.$i18n.t('确定'),
                    confirmButtonColor:'#4800E0'
                }).then(() => {
Vue.prototype.$bluetoothConnectivity(localStorage.getItem('vmNumber'),localStorage.getItem('manufacturerId'))
                });
                console.log('连接蓝牙失败',error)
                // 建立连接时出错
            });
    })
        .catch(error => {
            if (error.message.includes('Web Bluetooth is not supported on this platform')||error.message.includes('Bluetooth adapter not available')) {
                this.$dialog.alert({
                    title: window.$i18n.t('提示'),
                    message: window.$i18n.t('该浏览器不支持蓝牙'),
                    confirmButtonText: window.$i18n.t('去商城首页'),
                    confirmButtonColor: '#4800E0',
                    closeOnPopstate: false
                }).then(() => {
                    this.$router.push(
                        {
                            path: "/",
                            query: { storeId: localStorage.getItem("storeID") },
                        });
                });
            }
            // 发现设备时出错
        });
}


原文地址:https://blog.csdn.net/qd_ljp/article/details/142365270

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!