if (this.connectionId < 0) {
throw "No serial device connected.";
}
chrome.serial.send(
this.connectionId,
this.stringToArrayBuffer(data),
function() {});
};
onReceive
basically works like the sample listener we implemented in Exploring
the Chrome Serial API, on page 271. The only difference is that the new imple-
mentation looks for newline characters. Whenever it finds one, it passes the
current read buffer to the function that is listening for
onReadLine
events. Note
that more than one line can be transmitted in a single data chunk. Also note
that
onReceive
checks whether it got data from the correct serial port.
The
onReceiveError
method also makes sure first that it got error information
for the correct connection. In this case, it dispatches the event to the function
that is listening for
onError
events.
For our purposes we don’t need a
send
method, but it doesn’t hurt to add it
for the sake of completeness. This way, you have a
SerialDevice
class that you
can use in many more projects.
Finally, we need our two helper methods for converting
ArrayBuffer
objects into
strings and vice versa:
ChromeApps/SerialDevice/js/serial_device.js
SerialDevice.prototype.arrayBufferToString = function(buf) {
var bufView = new Uint8Array(buf);
var encodedString = String.fromCharCode.apply(null, bufView);
return decodeURIComponent(escape(encodedString));
};
SerialDevice.prototype.stringToArrayBuffer = function(str) {
var encodedString = unescape(encodeURIComponent(str));
var bytes = new Uint8Array(encodedString.length);
for (var i = 0; i < encodedString.length; ++i) {
bytes[i] = encodedString.charCodeAt(i);
}
return bytes.buffer;
};
That’s it! We now have a generic class for communicating with serial devices
from a Chrome app. Let’s use it right away and write a small demo application.
This demo will be the simplest serial monitor possible. It will permanently
read data from a serial port and display it in an HTML page. The HTML page
looks as follows:
Appendix 4. Controlling the Arduino with a Browser • 278
report erratum • discuss
www.it-ebooks.info