'Reading a usb serial port-based scale in javascript
We just switched from USB HID-based scales to serial-based scales. I am having trouble retrieving data using javascript from these scales.
(async () => {
const ports=await navigator.serial.getPorts();
const myScale=ports[0];
await myScale.open({ baudRate: 9600,dataBits:8,stopBits: 1, parity: `none`,flowControl: `none`});
console.log(`myScale: `, myScale);
const textDecoder = new TextDecoderStream();
const readableStreamClosed = myScale.readable.pipeTo(textDecoder.writable);
const reader = textDecoder.readable.getReader();
// Listen to data coming from the serial device.
while (true) {
const { value, done } = await reader.read();
if (done) {
// Allow the serial port to be closed later.
reader.releaseLock();
break;
}
// value is a string.
console.log(value);
}
})();
myScale gets created correctly:
myScale:
SerialPort {onconnect: null, ondisconnect: null, readable: ReadableStream, writable: WritableStream}
onconnect: null
ondisconnect: null
readable: ReadableStream
locked: false
[[Prototype]]: ReadableStream
writable: WritableStream
locked: false
[[Prototype]]: WritableStream
[[Prototype]]: SerialPort
close: ƒ close()
getInfo: ƒ getInfo()
getSignals: ƒ getSignals()
onconnect: (...)
ondisconnect: (...)
open: ƒ open()
readable: (...)
setSignals: ƒ setSignals()
writable: (...)
constructor: ƒ SerialPort()
Symbol(Symbol.toStringTag): "SerialPort"
get onconnect: ƒ onconnect()
set onconnect: ƒ onconnect()
get ondisconnect: ƒ ondisconnect()
set ondisconnect: ƒ ondisconnect()
get readable: ƒ readable()
get writable: ƒ writable()
[[Prototype]]: EventTarget
But everything comes to a halt when attempting to read the input from the scale:
const { value, done } = await reader.read();
What am I doing wrong?
Solution 1:[1]
Argh...Unlike the previous HID-based scales, which gave a continual reading, the user needs to press the "Print" button on this scale to send the data.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Chris |
