网页与串口通信:Web Serial API 使用记录

06-01 915阅读

文章目录

  • 前言
    • 1、打开串口 提示用户选择一个串口(因为浏览器安全策略原因,用户必须选择一次)
    • 2.读取数据
    • 3、解析函数
      • 值得注意的点:
      • 1、如果不想每次都让用户选择串口 可以使用公共变量将用户选择的串口 存储下来(cookie和localstorage不行。)。这样就可以在不同的页面 打开或者关闭同一个串口。重复使用
      • 总结

        前言

        一:Web Serial API 是什么

        串口是一个双向通信接口,允许字节发送和接收数据。

        Web Serial API为网站提供了一种使用JavaScript对串行设备进行读写的方法。串行设备可以通过用户系统上的串行端口连接,也可以通过模拟串行端口的可移动USB和蓝牙设备连接。

        换句话说,Web Serial API通过允许网站与串行设备(如微控制器和3D打印机)通信来连接网络和物理世界。

        该API是JS本身navigator对象上就独有的,所以与任何框架开发都没有太大的关系,不管你是用Vue还是React开发。

        要使用该API需要服务器使用https协议,同时呢,本地开发建议使用http://localhost:端口号。


        二、使用步骤

        大致使用的步骤如下:

        1、请求用户授权访问串行端口

        2、设置串行端口的参数,例如波特率、数据位、停止位、奇偶校验等。

        2、打开和关闭串行端口

        3、读取和写入串行数据

        4、监听来自串行设备的数据

        三:具体代码

        1、打开串口 提示用户选择一个串口(因为浏览器安全策略原因,用户必须选择一次)

         async test() { // 打开串口
              // 浏览器支持serial
              if ('serial' in navigator) {
                // 获取用户之前授予该网站访问权限的所有串口
                if (this.port==null) {
                  console.log("有串口::::",this.globalVariable)
                  if (this.globalVariable) {
                   this.port= this.globalVariable
                   console.log("00000000000::",this.globalVariable)
                   this.open()
                    return
                  }
                  // 提示用户选择一个串口
                  this.port = await navigator.serial.requestPort()
                   this.globalVariable = this.port
                   console.log("11111111111::",this.globalVariable)
                  this.open()
                } else {
                  console.log("你的电脑没有串口")
                }
              } else {
                alert('你的浏览器不支持串口连接')
              }
            },
        

        2.读取数据

        代码如下:

        网页与串口通信:Web Serial API 使用记录
        (图片来源网络,侵删)

        注意点:串口数据是分几次读取到的。所以需要判断的。我这里额外加了一个keepReading 变量来控制读取的开关

        async open() { // 打开串口
              // 等待串口打开
              console.log("进入open")
              await  this.port.open({
                baudRate: 115200, // 波特率
                dataBits: 8, // 每帧的数据位数(7或8)
                stopBits: 1, // 停止位数(1或2)
                parity: 'none', // 校验模式,可以是none,偶数,奇数
                flowControl: 'none' // 流控模式(none或hardware)。
                
              })
              console.log('串口打开成功', this.port)
              if (this.port) {
                //  let _this=this
                this.reader = this.port.readable.getReader()
                let mseeage=''
                while (this.port.readable && this.keepReading) {
                  try {
                    while (true) {
                      let { value, done } = await this.reader.read()
                      console.log("value",value)
                      var weight = this.Uint8ArrayToString(value)
                   
                      if(weight.length>0){
                      mseeage+=weight
                      }
                    
                      if(mseeage.includes('\n')){
                        mseeage=mseeage.split("\n")[0]
                      
                        if(mseeage.indexOf("up")>-1){
                           mseeage=mseeage.substring(mseeage.indexOf("up"),mseeage.length-1)
                        }
                        
                       console.log("iiiiiiiiiiii"+this.keepReading)
                        console.log("接收到的数据:",mseeage)
                       if(this.keepReading){
                         this.ccsOrder=mseeage
                         this.serchOrder()
                          //  alert(mseeage.trim(0))
                       }
                       mseeage=''
                      }
                       this.resetCountdown()
                      //  if(!this.keepReading){
                      //    break
                      //  }
                    }
                  } catch (error) {
                    console.error(error)
                  } finally {
                    // 允许稍后关闭串口。
                    this.reader.releaseLock()
                    this.port.close()
                    console.log('允许稍后关闭串口。')
                  }
                }
              }
            }
        

        3、解析函数

        Uint8ArrayToString(uint8Array) {
        let string = '';
          let i = 0;
          while (i 
免责声明:我们致力于保护作者版权,注重分享,被刊用文章因无法核实真实出处,未能及时与作者取得联系,或有版权异议的,请联系管理员,我们会立即处理! 部分文章是来自自研大数据AI进行生成,内容摘自(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供学习参考,不准确地方联系删除处理! 图片声明:本站部分配图来自人工智能系统AI生成,觅知网授权图片,PxHere摄影无版权图库和百度,360,搜狗等多加搜索引擎自动关键词搜索配图,如有侵权的图片,请第一时间联系我们。

相关阅读

目录[+]

取消
微信二维码
微信二维码
支付宝二维码