function arrayBufferToString(buf) {
var bufView = new Uint8Array(buf);
var encodedString = String.fromCharCode.apply(null, bufView);
return decodeURIComponent(escape(encodedString));
};
Although this function comprises only a few statements, it’s very complex. It
expects an
ArrayBuffer
object containing data encoded in UTF-8. That’s why it
creates a
Uint8Array
object first. An
ArrayBuffer
represents an arbitrary chunk of
memory, and using view classes like
Uint8Array
, you can specify how the
memory chunk should be interpreted. In our case, we want to interpret the
data we’ve received as characters encoded in UTF-8.
JavaScript strings are usually encoded in UTF-16, so the next two statements
convert the UTF-8 data we’ve received into a UTF-16 string. They use the
function
arrayBufferToString
to turn
ArrayBuffer
objects into JavaScript strings.
7
var listener = function(r) { console.log(arrayBufferToString(r.data)); }
chrome.serial.onReceive.addListener(listener)
This listener outputs the data received from the Arduino in a readable manner.
Note that you’ll see a lot of unexpected line breaks because the serial API
doesn’t look for newline characters. Whenever it receives a chunk of data, it
hands the chunk over to the listener. It’s the application’s responsibility to
interpret the data, and you’ll learn how to do this in the next section.
You’ve learned how to create your own Chrome apps and how to talk to serial
devices on the JavaScript console. But one of the great things about JavaScript
and Chrome apps is that you can tinker so easily with APIs in the browser.
Writing a SerialDevice Class
Playing with a new library in an interactive environment is a great way to
learn. Still, you eventually have to come up with some proper JavaScript code
that you can actually use in your project.
JavaScript supports object-oriented programming, so it seems logical to put
all code related to accessing the serial port into its own class. This way, you
can reuse it in other projects, and if you have to fix bugs or improve the code,
you have to do it only in one place. In addition, chances are good that there
will be a cross-browser solution for accessing the serial port soon.
8
When this
happens, you can replace the innards of your class with the new standard
7. At
http://ecmanaut.blogspot.de/2006/07/encoding-decoding-utf8-in-javascript.html
, you can find a detailed
explanation of this function. It’s not for the faint of heart!
8.
http://whatwg.github.io/serial/
Appendix 4. Controlling the Arduino with a Browser • 274
report erratum • discuss
www.it-ebooks.info