The callback function receives an object containing all information about the
connection. The statement above prints a text representation of the serial
connection object that has been created:
Object {
bitrate: 38400
bufferSize: 4096
connectionId: 13
ctsFlowControl: false
dataBits: "eight"
name: ""
parityBit: "no"
paused: false
persistent: false
receiveTimeout: 0
sendTimeout: 0
stopBits: "one"
}
This object contains all properties you’d expect in an object representing a
serial connection. It contains properties for the parity bit and stop bit settings.
One of its most important properties is
connectionId
. If the call to
connect
was
successful, its value is greater than zero.
In a next step, you can add a receive listener that gets called whenever data
arrives at the serial port:
var listener = function(r) { console.log(r.data); }
chrome.serial.onReceive.addListener(listener)
This listener outputs the data it receives on the console. Its output looks like
this:
ArrayBuffer {}
ArrayBuffer {}
ArrayBuffer {}
...
This probably isn’t what you expected. The problem is that the Chrome Serial
API stores the data it receives in an
ArrayBuffer
object. This is necessary because
you can transmit not only textual, but also binary data over a serial connec-
tion. JavaScript doesn’t support binary data out of the box, so you have to
use a few helper classes, such as
ArrayBuffer
.
Using the following function, you can turn the content of an
ArrayBuffer
object
into a JavaScript string:
report erratum • discuss
Exploring the Chrome Serial API • 273
www.it-ebooks.info