index.vue 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. <template>
  2. <HcNewCard>
  3. <template #header>
  4. <el-button size="large" type="success" @click="connectReader">连接读卡器</el-button>
  5. </template>
  6. <template #extra>
  7. <el-button size="large" type="warning" @click="clearTable">清除表格</el-button>
  8. <el-button size="large" type="danger" @click="closeLink">关闭链接</el-button>
  9. </template>
  10. <hc-table :column="tableColumn" :datas="tableData" :is-index="false" />
  11. </HcNewCard>
  12. </template>
  13. <script setup>
  14. import { onUnmounted, ref } from 'vue'
  15. const tableColumn = [{ key: 'epc', name: 'EPC' }]
  16. const tableData = ref([])
  17. //连接设备
  18. let device
  19. const connectReader = async () => {
  20. tableData.value = []
  21. const devices = await navigator.hid.requestDevice({
  22. filters: [{ vendorId: 1240, productId: 831 }],
  23. })
  24. if (devices.length <= 0) return
  25. device = devices[0]
  26. // 检查设备是否打开
  27. if (!device.opened) {
  28. await device.open() // 打开设备
  29. }
  30. console.log(device)
  31. // 电脑接收到来自设备的消息回调
  32. device.oninputreport = (event) => {
  33. const array = new Uint8Array(event.data.buffer)
  34. const data = array.slice(10, array[0] - 1)
  35. let hexstr = ''
  36. const res = new Uint8Array(data)
  37. for (const data of res) {
  38. hexstr += (Array(2).join(0) + data.toString(16).toUpperCase()).slice(-2) + '' // 将字节数据转换成(XX )形式字符串
  39. }
  40. tableData.value.push({ epc: hexstr })
  41. }
  42. }
  43. //清除表格
  44. const clearTable = () => {
  45. tableData.value = []
  46. }
  47. //关闭设备连接
  48. const closeLink = async () => {
  49. if ((device != null) && (device?.opened)) {
  50. await device.close() // 关闭设备
  51. await device.forget() // 遗忘设备
  52. clearTable()
  53. device = null
  54. }
  55. }
  56. //页面卸载
  57. onUnmounted(() => {
  58. closeLink()
  59. })
  60. </script>
  61. <style lang="scss" scoped>
  62. </style>