Reputation: 55
I have been trying to use a serial device over WebUSB. I can open the device and read/write to it using transferIn
and transferOut
. Since USB devices don't send all their data in one go, I have written a function that sends a command and then reads back the result by calling transferIn
recursively:
/** Send command to a device, and get its response back.
* @param {string} command
* @param {USBDevice} device
* @returns {Promise<string>}
*/
function sendCommand(command, device) {
return new Promise(function (resolve, reject) {
var pieces = [];
device.transferOut(1, new TextEncoder().encode(command + '\n')).then(function readMore() {
device.transferIn(1, 64).then(function (res) {
if (res.status !== 'ok')
reject(new Error('Failed to read result: ' + res.status));
else if (res.data.byteLength > 0) {
pieces.push(res.data);
readMore();
} else
resolve(new TextDecoder().decode(join(pieces))); // join() concatenates an array of arraybuffers
}).catch(reject);
}).catch(reject);
});
}
However, this does not work, as transferIn
waits for new data to be available before it resolves. How can I check if a USB serial device is done sending its response?
Upvotes: 2
Views: 1724
Reputation: 6093
Serial devices are streaming data sources. How do you define "done" when the device can send more data at any time?
If your device sends data in "messages" that is a high-level concept you must define on top of the serial layer. Maybe your device defines a message in terms of a termination character such as a newline or null byte. Maybe it prefixes a message with its length. Perhaps it does neither of these things and the only way to tell it is done is that no new data is received for a defined number of milliseconds.
In USB a common pattern is for a device to respond to a bulk transfer IN request with packets of exactly the endpoint's maximum packet size. If a packet less than that length is received that indicates the end of the message. This does not apply for USB serial devices because serial communication does not have the concept of a packet and the bulk packets are filled with whatever data was in the UART's buffer when the transfer request was received.
Upvotes: 3
Reputation: 566
Serial devices are not supported in WebUSB, however there is a Web Serial API currently in development for Chrome that would unlock this capability.
Upvotes: 0