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") },
                        });
                });
            }
            // 发现设备时出错
        });
}

Vue是一种流行的JavaScript框架,用于构建用户界面。Vue也可以用于构建H5应用程序,并与蓝牙打印机进行通信。在Vue中,我们可以使用Web Bluetooth API来访问蓝牙设备。 要在Vue中使用蓝牙打印,我们需要先确保用户的浏览器支持Web Bluetooth API。我们可以使用库如`web-bluetooth`来简化访问蓝牙设备的过程。 首先,在Vue项目中安装`web-bluetooth`库: ```bash npm install web-bluetooth ``` 然后,我们可以创建一个Vue组件,用于管理蓝牙打印的功能。在此组件中,我们可以使用`navigator.bluetooth`对象来搜索和连接蓝牙设备,以及发送数据到打印机。 ```javascript <template> <div> <button @click="searchDevices">搜索设备</button> <button @click="connectToDevice">连接设备</button> <button @click="printData">打印数据</button> </div> </template> <script> import WebBluetooth from 'web-bluetooth'; export default { data() { return { device: null, // 当前连接蓝牙设备 printerService: null, // 打印服务 printerCharacteristic: null // 打印特征 }; }, methods: { searchDevices() { navigator.bluetooth.requestDevice({ filters: [{ services: ['printer_service_uuid'] }] }) .then(device => { this.device = device; }) .catch(error => { console.error('搜索设备出错', error); }); }, connectToDevice() { if (this.device) { this.device.gatt.connect() .then(server => { return server.getPrimaryService('printer_service_uuid'); }) .then(service => { this.printerService = service; return service.getCharacteristic('printer_characteristic_uuid'); }) .then(characteristic => { this.printerCharacteristic = characteristic; }) .catch(error => { console.error('连接设备出错', error); }); } }, printData() { if (this.printerCharacteristic) { const data = '要打印的数据'; const encoder = new TextEncoder(); const dataBuffer = encoder.encode(data); this.printerCharacteristic.writeValue(dataBuffer) .then(() => { console.log('数据已发送到打印机'); }) .catch(error => { console.error('发送数据出错', error); }); } } } }; </script> ``` 在上面的示例中,我们先通过`navigator.bluetooth.requestDevice`方法搜索并选择一个蓝牙打印设备。然后,我们使用`device.gatt.connect`方法连接设备并获取打印服务。接下来,我们使用`service.getCharacteristic`方法获取打印特征。最后,我们可以使用`characteristic.writeValue`方法将数据发送到打印机。 需要注意的是,`printer_service_uuid`和`printer_characteristic_uuid`需要替换为实际的蓝牙打印设备的服务UUID和特征UUID。 通过上述步骤,就可以在VueH5应用程序中使用蓝牙打印了。当然,具体的实现可能还需要根据不同的蓝牙打印设备和需求进行调整和扩展。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值