当前位置: 首页 > news >正文

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);// 获取 ArrayBufferconst 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=falseVue.prototype.$stopBluetoothMonitoring()Vue.prototype.$bluetooth.device=nullif(!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=deviceVue.prototype.$bluetooth.connectingInProgress=truethis.$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=trueVue.prototype.$bluetooth.connectingInProgress=false}).catch(error => {Vue.prototype.$bluetooth.isItConnect=falseVue.prototype.$bluetooth.connectingInProgress=falseVue.prototype.$bluetooth.server=nullVue.prototype.$bluetooth.device=nullthis.$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") },});});}// 发现设备时出错});
}

http://www.mrgr.cn/news/30362.html

相关文章:

  • 对 JavaScript 原型的理解
  • ELK企业级日志分析系统
  • 从工厂打螺丝到数据库专家(上)
  • 把设计模式用起来!(4) 用不好模式?之原理不明
  • FortiGate 透明模式下配置注意事项和故障排错技巧
  • 维钧团队与广东能源集团携手共创未来
  • 华为、思科、新华三,三大厂商认证到底选择哪一个?
  • 力扣438 找到字符串中所有字母异位词 Java版本
  • 设计模式之外观设计模式
  • 教师专属:高效查询学生考试成绩系统 - 立即体验吧
  • C++:动态内存分配(new、delete 相比 malloc、free的优势)与运算符重载
  • 完美解决 Async/await 不按预期工作 的正确解决方法,亲测有效!!!
  • python+flask+mongodb+vue撸一个实时监控linux服务资源的网站
  • 从 InnoDB 到 Memory:MySQL 存储引擎的多样性
  • 更换UFS绑定固件与“工程固件”的区别 小米10s机型更换cpu绑定包对比 写入以及修复基带
  • 无人机 PX4 飞控 | EKF 使用传感器汇总与添加传感器方法
  • Pytorch使用集成可形变卷积构建网络并导出onnx模型
  • (六)WebAPI方法的调用
  • 学习风格的类型
  • Scrapy爬虫框架 Pipeline 数据传输管道