1
votes

I'm working on a Google Chrome extension that communicates with an Arduino UNO over serial. I wrote the following function sendSerialCmd that takes a port (string), a serial_cmd (ArrayBuffer), and a callback function that gets passed readInfo.data (an ArrayBuffer) that is read in from the serial connection.

var CONNECTION_ID = -1;
var sendSerialCmd = function(port, serial_cmd, callback) {
chrome.serial.open(port, null, function(openInfo){
    CONNECTION_ID = openInfo.connectionId;
    if (CONNECTION_ID == -1) {
        console.log('Could not connect to serial');
        return;
    }
    chrome.serial.write(CONNECTION_ID, serial_cmd, function(writeInfo){
        chrome.serial.read(CONNECTION_ID, 8, function(readInfo){
            callback(readInfo.data);
        });
    })
});
chrome.serial.close(CONNECTION_ID, function(result){ console.log(result) });
};

One of the problems I've run into is the third parameter passed to the chrome.serial.read() function. In the chrome.serial API, the third parameter is the bytesToRead ( integer ): The number of bytes to read, however, the number of bytes coming in from my Arduino are subject to change. Sometimes I may get 8 bytes, other times more. What's the best way of getting all the bytes sent back from my Arduino?

Arduino has a novel solution through a function called Serial.available() which returns the number of bytes available to read. Is there something similar I can do with the Chrome.serial API?

1

1 Answers

3
votes

There is no similar functionality to Serial.available() in the Chrome serial API, but you should just poll for some reasonable number of bytes and process the data at your own pace.

If a read is requested for (say) 1024 bytes and only 8 bytes are available, the read should still succeed quickly with just 8 bytes. If there is an 8-byte message and a 12-byte message available, the read will succeed with 20 bytes and you can apply whatever logic is necessary to parse the resulting data.

FYI, the serial API is changing soon in Canary and you will no longer be responsible for manually polling with read. Instead Chrome will poll for you and fire chrome.serial.onReceive events as data is available from an open device.