JavaScript COM API

From SpinetiX Support Wiki

Jump to: navigation, search

Introduction

The JavaScript COM API allows interacting with devices connected to the HMP via the serial port directly from the JavaScript code. It was experimentally introduced within firmware 3.0.0 and stabilized within firmware 3.1.0.

This API defines how to send messages to the external device (writeCOMPort() function) and how to handle incoming messages from the external device (the com event) via the serial port.

The serial port settings can be modified from Control Center.

writeCOMPort()

void writeCOMPort( in DOMString text );
void writeCOMPort( in Array bytes );
void writeCOMPort( in ArrayBuffer typedArray );
void writeCOMPort( in Buffer buffer );

There are different ways to specify the characters to be sent on the serial port.

  • A string, which is convenient for text based protocols. Note that it is not possible to send a zero byte when using a string argument and that each Unicode character code is truncated to 8 bits. Use the Buffer variant if you need to encode non ASCII characters.
  • An array of byte values. The array elements are first cast to an integer number, then truncated to 8 bits.
  • A typed array, e.g. a Uint8Array object, the binary content of which is sent verbatim.
  • A Buffer object which is convenient to format packet structures with any combination of numbers, encoding and byte orders.

Examples:

writeCOMPort( "Hello World !\r\n" );
writeCOMPort( [ 0, 1, 2, 3 ] );
var buf = new Buffer( 256 );
buf.writeUInt32LE( 0xbadcaffe, 0 );
buf.write( "Hello", 4, 32, "utf8" );
writeCOMPort( buf );

com events

To read data from the serial port, simply add an event listener for the "com" event on the document object. The COMEvent object that is passed to the callback function has the following attributes:

  • bytes
    Uint8Array typed array with content read from the serial port.
  • data
    Buffer object with content read from the serial port.
  • portNumber
    This is always set to 1.


Example:

document.addEventListener( "com", function( ev ) {
  alert( 'received: ' + ev.data.toString() );
  alert( 'first byte is: ' + ev.bytes[0] );
});
This page was last modified on 22 March 2016, at 13:20.