How can a web page read from the user's serial port - in the year 2017?

后端 未结 6 1701
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-04 10:28

I have to re-implement an existing system from scratch.

At one point, when the user navigates to a certain web page the server must read data from the user\'s seria

6条回答
  •  孤街浪徒
    2020-12-04 11:04

    Using the serialport package through Node JS as a server is an option. This works on Windows, and apparently on Linux and OSX as well. See https://github.com/node-serialport/node-serialport.

    This is a solution I have used to read micro bit comms through USB to a browser. I did have to rebuild the driver for windows (10) with:

    • npm install --global --production windows-build-tools
    • npm install serialport --build-from-source

    I've pasted some of my code below for reference:

    const serialport = require('serialport')
    
    // list serial ports:
    const find_microbit = (error, success) => {
      serialport.list((err, ports) => {
        if (err) {
          error(err)
        } else {
          let comName = null
          ports.forEach((port) => {
            if ((port.vendorId == '0D28') && (port.productId == '0204')) {
              comName = port.comName
            }
          })
          if (comName != null) {
            success(comName)
          } else {
            error('Could not find micro:bit.')
          }
        }
      })
    }
    
    exports.get_serial = (error, success) => {
      find_microbit(error, (comName) => {
        let serial = new serialport(comName, {baudRate: 115200, parser: serialport.parsers.readline('\n')}, (err) => {
          if (err) {
            error(err)
          } else {
            success(serial)
          }
        })
      })
    }
    /* e.g.
    get_serial((err)=>{console.log("Error:" + err)},
        (serial)=>{
            serial.on('data', (data) => {
                let ubit = JSON.parse(data)
                if (ubit.button == 'a') {
                    console.log('Button A Pressed')
                }
                if (ubit.button == 'b') {
                    console.log('Button B Pressed')
                }
                if (ubit.ir) {
                    console.log('Visitor detected')
                }
            })
        })
        */
    

    This approach works - for me - but it can be time consuming to get it working. It's not, to my mind, an obvious, or simple solution. It requires a fair amount of technical know how - and is, I feel, much more complex and 'tricky' than it should be.

    In particular - rebuilding the library isn't something I would expect to do when using Node JS. One of the possible effects is that you would need to rebuild the serial port binaries for a different platform.

提交回复
热议问题