notes.dt.in.th

Reading data from OBZ Barcode Reader on the web using Web Serial API

I just purchased a barcode scanner from OBZ. Normally, it functions as a USB keyboard: when you scan a barcode, it types the barcode's value as if you typed it on a keyboard. This means the barcode data is sent to whatever application has focus.

However, the scanner also has a USB-COM mode, which allows it to act as a serial device. This means it can send the barcode data directly to a program that reads from a serial port. Thankfully, the web platform has a Web Serial API that allows web applications to read from serial ports.

Demo

Click the button to connect

Notes

Code

// Connect to the barcode scanner
const port = await navigator.serial.requestPort()
await port.open({ baudRate: 9600 })
const readable = port.readable.pipeThrough(new TextDecoderStream())

// Handler for barcode scans
const onScan = (data) => {
  console.log(`Scanned: ${data}`)
}

// Read data from the barcode scanner
let output = ''
for await (const value of readable) {
  output += value
  for (;;) {
    let index = output.indexOf(String.fromCharCode(13))
    if (index === -1) {
      break
    }
    const line = output.slice(0, index)
    output = output.slice(index + 1)
    onScan(line)
  }
}

It’s great to know that the web platform has powerful APIs that lets us interface with hardware devices.