From 6b7e6c6253811d3f91362cd3faa15520b4894fb5 Mon Sep 17 00:00:00 2001 From: Timothy Harvey Date: Wed, 24 Jan 2018 16:11:14 -0600 Subject: [PATCH 01/18] jfjfjf --- docs/aio.md | 46 +++++++++++++++++++++++----------------------- docs/buffer.md | 28 ++++++++++++++++++++++++++++ 2 files changed, 51 insertions(+), 23 deletions(-) diff --git a/docs/aio.md b/docs/aio.md index 8fd8c99e7..4d342f2e7 100644 --- a/docs/aio.md +++ b/docs/aio.md @@ -3,7 +3,13 @@ ZJS API for Analog I/O (AIO) * [Introduction](#introduction) * [Web IDL](#web-idl) -* [API Documentation](#api-documentation) +* [Class: AIO](#aio-api) + * [aio.open(AIOInit)](#aiopin-openaioinit) +* [Class: AIOPin](#aiopin-api) + * [pin.read()](#pinread) + * [pin.readAsync(ReadCallback)](#pinreadasyncreadcallback) + * [pin.on(eventType, ReadCallback)](#pinoneventtype-readcallback) + * [pin.close()](#pinclose) * [Sample Apps](#sample-apps) Introduction @@ -30,16 +36,15 @@ specific API functions. // require returns an AIO object // var aio = require('aio'); -[NoInterfaceObject] +[ReturnFromRequire] interface AIO { AIOPin open(AIOInit init); }; dictionary AIOInit { - unsigned long pin; + (unsigned long or string) pin; }; -[NoInterfaceObject] interface AIOPin { unsigned long read(); void readAsync(ReadCallback callback); // TODO: change to return a promise @@ -50,11 +55,12 @@ interface AIOPin { callback ReadCallback = void (unsigned long value); ``` -API Documentation ------------------ -### AIO.open - -`AIOPin open(AIOInit init);` +AIO API +------- +### AIOPin open(AIOInit) +* 'init' *object* The AIOInit object has a single field called "pin" + that represents the name of the pin (either an integer or a string, + depending on the board). The `init` object lets you set the pin number. You can either use a raw number for your device or use the board support module such as @@ -63,15 +69,13 @@ specify a named pin. Use the AIOPin object returned to read values from the pin. -### AIOPin.read - -`unsigned long read();` +AIOPin API +---------- +### pin.read() -Returns the latest reading from the pin. Blocks until it gets the result. +Returns the latest reading from the pin (an unsigned integer). Blocks until it gets the result. -### AIOPin.readAsync - -`void readAsync(ReadCallback callback);` +### pin.readAsync(ReadCallback) Pass a function for `callback` that will be called later when the result is obtained. @@ -85,9 +89,7 @@ any given time.* *NOTE: This function will probably be replaced with a version that instead returns a promise.* -### AIOPin.on - -`void on(string eventType, ReadCallback callback);` +### pin.on(eventType, ReadCallback) Currently, the only supported `eventType` is 'change', and `callback` should be either a function or null. When a function is passed for the change event, @@ -96,11 +98,9 @@ it actually gets called periodically even when it hasn't changed.) When null is passed for the change event, the previously registered callback will be discarded and no longer called. -### AIOPin.close - -`void close();` +### pin.close() -Closes the AIOPin. Once it is closed, all event handlers registered will no +Closes the AIOPin. Once it is closed, all registered event handlers will no longer be called. Sample Apps diff --git a/docs/buffer.md b/docs/buffer.md index 17f1bb363..5529eeb96 100644 --- a/docs/buffer.md +++ b/docs/buffer.md @@ -2,6 +2,7 @@ ZJS API for Buffer ================== * [Introduction](#introduction) +* [Web IDL](#web-idl) * [Class: Buffer](#buffer-api) * [new Buffer(array)](#new-bufferarray) * [new Buffer(size)](#new-buffersize) @@ -20,6 +21,33 @@ Buffer is a [Node.js API](https://nodejs.org/dist/latest-v8.x/docs/api/buffer.ht to read and write binary data accurately from JavaScript. ZJS supports a minimal subset of this API that will be expanded as the need arises. +Web IDL +------- + +[ + Constructor(Uint8Array initial_values), + Constructor(unsigned long size), + Constructor(ByteString initial_string) +] +interface Buffer { + readonly attribute unsigned long length; + unsigned long copy(Buffer target, optional unsigned long targetStart, + optional unsigned long sourceStart + optional unsigned long sourceEnd); + octet readUInt8(unsigned long offset); + void writeUInt8(octet value, unsigned long offset); + unsigned short readUInt16BE(unsigned long offset); + void writeUInt16BE(unsigned short value, unsigned long offset); + unsigned short readUInt16LE(unsigned long offset); + void writeUInt16LE(unsigned short value, unsigned long offset); + unsigned long readUInt32BE(unsigned long offset); + void writeUInt32BE(unsigned long value, unsigned long offset); + unsigned long readUInt32LE(unsigned long offset); + void writeUInt32LE(unsigned long value, unsigned long offset); + string toString(string encoding); +}; + + Buffer API ---------- ### new Buffer(array) From b2e4ff7a3dc7cc02cc13510031861d31241a86f2 Mon Sep 17 00:00:00 2001 From: Timothy Harvey Date: Sun, 28 Jan 2018 17:05:16 -0600 Subject: [PATCH 02/18] Reinserted WebIDL for buffer.md; changed the WebIDL in aio and ble to be syntactically correct and to follow the new style of buffer.md. Added a new file that explains some of the differences between WebIDL and Javascript. --- docs/Notes_on_WebIDL.md | 33 +++++++ docs/aio.md | 34 ++++--- docs/ble.md | 194 +++++++++++++++++++++++----------------- docs/buffer.md | 58 ++++++------ 4 files changed, 200 insertions(+), 119 deletions(-) create mode 100644 docs/Notes_on_WebIDL.md diff --git a/docs/Notes_on_WebIDL.md b/docs/Notes_on_WebIDL.md new file mode 100644 index 000000000..dc75a1620 --- /dev/null +++ b/docs/Notes_on_WebIDL.md @@ -0,0 +1,33 @@ +Notes on WebIDL for zephyr.js documentation: + +The WebIDL fragments are for reference only; the description of the +API should be considered correct -- please report discrepancies as +soon as possible. + +Although both WebIDL and Javascript are aimed at web applications, +numerous incompatibilities exist between the two. In general, we try +to use basic (as opposed to "advanced") WebIDL to describe each +API; below, we list some of our conventions. + +We map WebIDL definitions to Javascript objects as follows: + +1. dictionaries -- these map to Javascript objects that simply don't + have methods attached to them. +2. interfaces -- like definitions, these correspond to Javascript + objects, except that they may also include methods. +3. callbacks -- these are type definitions for functions used as + parameters or object fields. +4. enumerations -- these are largely the same in both languages. + +Unless a constructor is explicitly defined/denied (*e.g.*, see the +note about "require", below), we assume the Javascript model that the +object can be constructed with "new" -- WebIDL specifies that the +external attribute "constructor" be applied to a definition that can +be new'd, but putting the attribute on every object would be +cumbersome. + +The node.js notion of "require" is subtly different from constructing +an object with Javascript's "new", but it has appealing semantics. We +annotate WebIDL definitions that should be implemented with node.js's +"require" semantics with the external attribute "ReturnFromRequire". + diff --git a/docs/aio.md b/docs/aio.md index 4d342f2e7..87ccdea55 100644 --- a/docs/aio.md +++ b/docs/aio.md @@ -4,7 +4,7 @@ ZJS API for Analog I/O (AIO) * [Introduction](#introduction) * [Web IDL](#web-idl) * [Class: AIO](#aio-api) - * [aio.open(AIOInit)](#aiopin-openaioinit) + * [aio.open(AIOInit)](#aioopenaioinit) * [Class: AIOPin](#aiopin-api) * [pin.read()](#pinread) * [pin.readAsync(ReadCallback)](#pinreadasyncreadcallback) @@ -29,8 +29,11 @@ not have support for this. Web IDL ------- -This IDL provides an overview of the interface; see below for documentation of -specific API functions. + +This IDL provides an overview of the interface; see below for +documentation of specific API functions. Click +[here](Notes_on_WebIDL.md) for an explanation of zephyr.js' WebIDL +conventions. ```javascript // require returns an AIO object @@ -57,17 +60,17 @@ callback ReadCallback = void (unsigned long value); AIO API ------- -### AIOPin open(AIOInit) -* 'init' *object* The AIOInit object has a single field called "pin" +### aio.open(AIOInit) +* 'AIOInit' *object* The AIOInit object has a single field called "pin" that represents the name of the pin (either an integer or a string, depending on the board). -The `init` object lets you set the pin number. You can either use a raw +When setting the pin number, you can either use a raw number for your device or use the board support module such as [Arduino 101](./boards/arduino_101.md) or [K64F](./boards/frdm_k64f.md) to specify a named pin. -Use the AIOPin object returned to read values from the pin. +Returns an AIOPin object that be used to read values from the pin. AIOPin API ---------- @@ -76,24 +79,29 @@ AIOPin API Returns the latest reading from the pin (an unsigned integer). Blocks until it gets the result. ### pin.readAsync(ReadCallback) +* 'ReadCallback' *callback* User-provided callback function that takes + a single unsigned integer and has no return value. -Pass a function for `callback` that will be called later when the result is +Pass a function for `ReadCallback` that will be called later when the result is obtained. *WARNING: Making an async call like this allocates some memory while the call -is pending, so if you issue them faster than they are fulfilled, you will +is pending; if async calls are issued faster than they are fulfilled, +the system will eventually run out of memory - pretty soon on these small devices. So the best -practice would be to make sure you only have a small, fixed number pending at +practice would be to have only a small, fixed number pending at any given time.* *NOTE: This function will probably be replaced with a version that instead returns a promise.* ### pin.on(eventType, ReadCallback) +* 'eventType' *string* Type of event; currently, the only supported + type is "change". +* 'ReadCallback' *callback* User-provided callback function that takes + a single, unsigned integer and has no return value; can be null. -Currently, the only supported `eventType` is 'change', and `callback` should -be either a function or null. When a function is passed for the change event, -the function will be called any time the analog voltage changes. (At the moment, +The callback function is called any time the analog voltage changes. (At the moment, it actually gets called periodically even when it hasn't changed.) When null is passed for the change event, the previously registered callback will be discarded and no longer called. diff --git a/docs/ble.md b/docs/ble.md index aa127d963..b4cb5fafc 100644 --- a/docs/ble.md +++ b/docs/ble.md @@ -3,7 +3,20 @@ ZJS API for Bluetooth Low Energy (BLE) * [Introduction](#introduction) * [Web IDL](#web-idl) -* [API Documentation](#api-documentation) +* [BLE-supported Events](#ble\-supported-events) +* [Class: BLE](#ble-api) + * [ble.disconnect(address)](#bledisconnectaddress) + * [ble.startAdvertising(name, uuids, url)](#blestartadvertisingname-uuids-url) + * [ble.stopAdvertising()](#blestopadvertising) + * [ble.setServices(primaryServices)](#blesetservicesprimaryservices) + * [ble.newPrimaryService(init)](#blenewprimaryserviceinit) + * [ble.newCharacteristic(init)](#blenewcharacteristicinit) + * [ble.newDescriptor(init)](#blenewdescriptorinit) +* [Class: Characteristic](#characteristic-api) +* [Supporting Objects](#supporting-objects) + * [PrimaryServiceInit](#primaryserviceinit) + * [CharacteristicInit](#characteristicinit) + * [DescriptorInit](#descriptorinit) * [Client Requirements](#client-requirements) * [Sample Apps](#sample-apps) @@ -25,21 +38,23 @@ treat them like decimals.* Web IDL ------- This IDL provides an overview of the interface; see below for documentation of -specific API functions. +specific API functions. Click [here](Notes_on_WebIDL.md) for an +explanation of zephyr.js' WebIDL conventions. + ```javascript // require returns a BLE object // var ble = require('ble'); -[NoInterfaceObject] +[ReturnFromRequire] interface BLE: EventEmitter { void disconnect(string address); void startAdvertising(string name, string[] uuids, string url); void stopAdvertising(); - void setServices(PrimaryService services[]); - PrimaryService PrimaryService(PrimaryServiceInit init); - Characteristic Characteristic(CharacteristicInit init); - Descriptor Descriptor(DescriptorInit init); + void setServices(PrimaryService[] services); + PrimaryService newPrimaryService(PrimaryServiceInit init); + Characteristic newCharacteristic(CharacteristicInit init); + Descriptor newDescriptor(DescriptorInit init); }; dictionary PrimaryServiceInit { @@ -58,36 +73,36 @@ dictionary CharacteristicInit { NotifyCallback onNotify; // optional }; -callback ReadCallback = void (unsigned long offset, FulfillReadCallback); +interface Characteristic { + attribute ReadCallback onReadRequest; + attribute WriteCallback onWriteRequest; + attribute SubscribeCallback onSubscribe; + attribute UnsubscribeCallback onUnsubscribe; + attribute NotifyCallback onNotify; + attribute CharacteristicResult response; +}; + +callback ReadCallback = void (unsigned long offset, + FulfillReadCallback fulfillreadcallback); callback WriteCallback = void (Buffer data, unsigned long offset, - boolean withoutResponse, FulfillWriteCallback); + boolean withoutResponse, + FulfillWriteCallback fulfillwritecallback); callback SubscribeCallback = void (unsigned long maxValueSize, - FulfillSubscribeCallback); + FulfillSubscribeCallback fullfillsubscribecallback); callback FulfillReadCallback = void (CharacteristicResult result, Buffer data); callback FulfillWriteCallback = void (CharacteristicResult result); callback FulfillSubscribeCallback = void (Buffer data); +enum CharacteristicResult { "RESULT_SUCCESS", "RESULT_INVALID_OFFSET", "RESULT_INVALID_ATTRIBUTE_LENGTH", "RESULT_UNLIKELY_ERROR" } ; + dictionary DescriptorInit { string uuid; string value; }; - -[NoInterfaceObject] -interface Characteristic { - attribute ReadCallback onReadRequest; - attribute WriteCallback onWriteRequest; - attribute SubscribeCallback onSubscribe; - attribute UnsubscribeCallback onUnsubscribe; - attribute NotifyCallback onNotify; - unsigned long RESULT_SUCCESS; - unsigned long RESULT_INVALID_OFFSET; - unsigned long RESULT_INVALID_ATTRIBUTE_LENGTH; - unsigned long RESULT_UNLIKELY_ERROR; -}; ``` -API Documentation ------------------ +BLE-supported Events +-------------------- BLE is an [EventEmitter](./events.md) with the following events: ### Event: 'accept' @@ -118,97 +133,114 @@ one previously sent with the 'accept' event. Emitted with 'poweredOn' when the BLE stack is ready to be used. No other states are supported at this time. -### BLE.disconnect - -`void disconnect(string address);` +BLE API +------- +### ble.disconnect(address) +*'address' *string* The address of the connected client. Disconnect the remote client. -The `address` is the address of the connected client. +### ble.startAdvertising(name, uuids, url) +* name *string* The `name` is limited to 26 characters and will be + advertised as the device name to nearby BLE devices. +* uuids *string[]* The `uuids` array may contain at most 7 16-bit + UUIDs (four hex digits each). These UUIDs identify available + services to nearby BLE devices. +* url *string* The `url` is optional and limited to around 24 + characters (slightly more if part of the URL is able to be + [encoded](https://github.com/google/eddystone/tree/master/eddystone-url). If + provided, this will be used to create a physical web advertisement + that will direct users to the given URL. At that URL they might be + able to interact with the advertising device somehow. + +Advertises the name of the device. + +### ble.stopAdvertising() -### BLE.startAdvertising +Currently does nothing. -`void startAdvertising(string name, string[] uuids, string url);` +### ble.setServices(primaryServices) +* primaryServices *array of PrimaryService objects* The PrimaryService + objects are used to set up the services that are implemented by your + app. + +The PrimaryService object contains the following fields: -The `name` is limited to 26 characters and will be advertised as the device -name to nearby BLE devices. -The `uuids` array may contain at most 7 16-bit UUIDs (four hex digits each). -These UUIDs identify available services to nearby BLE devices. +### ble.newPrimaryService(init) +* 'init' *PrimaryServiceInit*(#primaryserviceinit) -The `url` is optional and limited to around 24 characters (slightly more -if part of the URL is able to be [encoded](https://github.com/google/eddystone/tree/master/eddystone-url). If provided, -this will be used to create a physical web advertisement that will direct users -to the given URL. At that URL they might be able to interact with the -advertising device somehow. +Returns a new PrimaryService object. -### BLE.stopAdvertising +### ble.newCharacteristic(init) +* init *CharacteristicInit* -`void stopAdvertising();` +Returns a new Characteristic object. -Currently does nothing. -### BLE.setServices +### ble.newDescriptor(init) +* 'init' *DescriptorInit*(#descriptorinit-struct) -`void setServices(PrimaryService[]);` +Returns a new DescriptorInit object. -Pass an array of PrimaryService objects to set up the services that are -implemented by your app. -### BLE.PrimaryService constructor +Characteristic API +------------------ +The "Characteristic" object contains the set of callbacks that...[[TODO!!!]] -`PrimaryService(PrimaryServiceInit init);` +Explanation of common arguments to the above functions: +* `offset` is a 0-based integer index into the data the characteristic + represents. +* `result` is one of these values defined in the Characteristic object. + * RESULT_SUCCESS + * RESULT_INVALID_OFFSET + * RESULT_INVALID_ATTRIBUTE_LENGTH + * RESULT_UNLIKELY_ERROR +* `data` is a [Buffer](./buffer.md) object. + +Supporting Objects +------------------ + +### PrimaryServiceInit -The `init` object should contain a `uuid` field with a 16-bit service UUID (4 -hex chars) and a `characteristics` field with an array of Characteristic -objects. +This object has two fields: +1. 'uuid' *string* This field is a 16-bit service UUID (4 hex chars). +2. `characteristics` *array of [Characteristics](#characteristic)* -### BLE.Characteristic constructor -`Characteristic(CharacteristicInit init);` +### CharacteristicInit -The `init` object should contain: -* `uuid` field with a 16-bit characteristic UUID (4 hex chars) -* `properties` field with an array of strings that may include 'read', 'write', - and 'notify', depending on what is supported -* `descriptors` field with an array of Descriptor objects +This object has 3 required fields: +1. `uuid` *string* This field is a 16-bit characteristic UUID (4 hex chars). +2. `properties` *array of strings* Possible values: 'read', 'write', and 'notify', depending on what is supported. +3. `descriptors` *array of [Descriptors](#descriptor)* It may also contain these optional callback fields: -* `onReadRequest` function(offset, callback(result, data)) +1. `onReadRequest` *ReadCallback* * Called when the client is requesting to read data from the characteristic. * See below for common argument definitions -* `onWriteRequest` function(data, offset, withoutResponse, callback(result)) +2. `onWriteRequest` *WriteCallback* * Called when the client is requesting to write data to the characteristic. * `withoutResponse` is true if the client doesn't want a response * *TODO: verify this* -* `onSubscribe` function(maxValueSize, callback(data)) +3. `onSubscribe` *SubscribeCallback* * Called when a client signs up to receive notify events when the characteristic changes. * `maxValueSize` is the maximum data size the client wants to receive. -* `onUnsubscribe` function() +4. `onUnsubscribe` *UnsubscribeCallback* * *NOTE: Never actually called currently.* -* `onNotify` function() +5. `onNotify` *NotifyCallback* * *NOTE: Never actually called currently.* -Explanation of common arguments to the above functions: -* `offset` is a 0-based integer index into the data the characteristic - represents. -* `result` is one of these values defined in the Characteristic object. - * RESULT_SUCCESS - * RESULT_INVALID_OFFSET - * RESULT_INVALID_ATTRIBUTE_LENGTH - * RESULT_UNLIKELY_ERROR -* `data` is a [Buffer](./buffer.md) object. - -### BLE.Descriptor constructor -`Descriptor(DescriptorInit init);` +### DescriptorInit -The `init` object should contain: -* `uuid` field with a 16-bit descriptor UUID (4 hex chars) - * Defined descriptors are listed here in [Bluetooth Specifications](https://www.bluetooth.com/specifications/gatt/descriptors) -* `value` field with a string supplying the defined information - * *NOTE: Values can also be Buffer objects, but that's not currently supported.* +This object has two fields: +1. 'uuid' *string* This is a 16-bit descriptor UUID (4 hex chars) + * Defined descriptors are listed here in [Bluetooth Specifications](https://www.bluetooth.com/specifications/gatt/descriptors) +2. 'value' *string* This string supplies the defined information. + * *NOTE: Values can also be Buffer objects, but that's not currently + supported.* Client Requirements ------------------- diff --git a/docs/buffer.md b/docs/buffer.md index 5529eeb96..8d9054f65 100644 --- a/docs/buffer.md +++ b/docs/buffer.md @@ -23,54 +23,62 @@ subset of this API that will be expanded as the need arises. Web IDL ------- +This IDL provides an overview of the interface; see below for documentation of +specific API functions. Click [here](Notes_on_WebIDL.md) for an +explanation of zephyr.js' WebIDL conventions. -[ - Constructor(Uint8Array initial_values), +```javascript +[ Constructor(Uint8Array initial_values), Constructor(unsigned long size), - Constructor(ByteString initial_string) -] + Constructor(ByteString initial_string) ] interface Buffer { readonly attribute unsigned long length; - unsigned long copy(Buffer target, optional unsigned long targetStart, - optional unsigned long sourceStart - optional unsigned long sourceEnd); - octet readUInt8(unsigned long offset); - void writeUInt8(octet value, unsigned long offset); - unsigned short readUInt16BE(unsigned long offset); - void writeUInt16BE(unsigned short value, unsigned long offset); - unsigned short readUInt16LE(unsigned long offset); - void writeUInt16LE(unsigned short value, unsigned long offset); - unsigned long readUInt32BE(unsigned long offset); - void writeUInt32BE(unsigned long value, unsigned long offset); - unsigned long readUInt32LE(unsigned long offset); - void writeUInt32LE(unsigned long value, unsigned long offset); + unsigned long copy(Buffer target, optional unsigned long targetStart = 0, + optional unsigned long sourceStart = 0, + optional unsigned long sourceEnd = this.length); + this fill((string or Buffer or long) value, optional long offset = 0, + optional long end = this.length, + optional string encoding = "utf8"); + octet readUInt8(optional unsigned long offset = 0); + short readUInt16BE(optional unsigned long offset = 0); + short readUInt16LE(optional unsigned long offset = 0); + long readUInt32BE(optional unsigned long offset = 0); + long readUInt32LE(optional unsigned long offset = 0); string toString(string encoding); + long write(string value, optional long offset = 0, + optional long length = this.length-offset, + optional string encoding = "utf8"); + long writeUInt8(octet value, unsigned long offset); + long writeUInt16BE(unsigned short value, unsigned long offset); + long writeUInt16LE(unsigned short value, unsigned long offset); + long writeUInt32BE(unsigned long value, unsigned long offset); + long writeUInt32LE(unsigned long value, unsigned long offset); }; - +``` Buffer API ---------- ### new Buffer(array) * `array` *integer[]* Array of octets to use as initial data. -The `array` argument should be an array of numbers that will be treated as -UInt8 integers. A new buffer object will be returned with the same size as the -array and initialized with its contents. If there is not enough available -memory, an error will be thrown. +A new Buffer object will be returned with the same size as the array +and initialized with the array's contents. If there is not enough +available memory, an error will be thrown. ### new Buffer(size) * `size` *integer* Length in bytes of the new buffer. The `size` argument specifies the length in bytes of the array that the Buffer represents. If a negative length is passed, a 0-length Buffer will be returned. -If the size is too long and there is not enough available memory, an error will +If there is not enough available memory to allocate the Buffer, an error will be thrown. ### new Buffer(string) * `string` *string* String to use as initial data. -The `string` argument will be treated as UTF8 and used to initialize the new -buffer. If there is not enough available memory, an error will be thrown. +The `string` argument will be treated as an array of UTF8 values and +will be used to initialize the new buffer. If there is not enough +available memory, an error will be thrown. ### buf.copy(target[, targetStart, [sourceStart[, sourceEnd]]]) * `target` *Buffer* Buffer to receive the copied data. From 3dce399124182c1cd24c9d2690016a1098158e71 Mon Sep 17 00:00:00 2001 From: Timothy Harvey Date: Thu, 1 Feb 2018 20:33:48 -0600 Subject: [PATCH 03/18] Made changes based on the first round of pull request 1800 --- docs/Notes_on_WebIDL.md | 13 ++++----- docs/aio.md | 24 +++++++--------- docs/ble.md | 62 +++++++++++++++++++---------------------- docs/buffer.md | 19 ++++++------- 4 files changed, 54 insertions(+), 64 deletions(-) diff --git a/docs/Notes_on_WebIDL.md b/docs/Notes_on_WebIDL.md index dc75a1620..d4dab86e8 100644 --- a/docs/Notes_on_WebIDL.md +++ b/docs/Notes_on_WebIDL.md @@ -4,30 +4,29 @@ The WebIDL fragments are for reference only; the description of the API should be considered correct -- please report discrepancies as soon as possible. -Although both WebIDL and Javascript are aimed at web applications, +Although both WebIDL and JavaScript are aimed at web applications, numerous incompatibilities exist between the two. In general, we try to use basic (as opposed to "advanced") WebIDL to describe each API; below, we list some of our conventions. -We map WebIDL definitions to Javascript objects as follows: +We map WebIDL definitions to JavaScript objects as follows: -1. dictionaries -- these map to Javascript objects that simply don't +1. dictionaries -- these map to JavaScript objects that simply don't have methods attached to them. -2. interfaces -- like definitions, these correspond to Javascript +2. interfaces -- like definitions, these correspond to JavaScript objects, except that they may also include methods. 3. callbacks -- these are type definitions for functions used as parameters or object fields. 4. enumerations -- these are largely the same in both languages. Unless a constructor is explicitly defined/denied (*e.g.*, see the -note about "require", below), we assume the Javascript model that the +note about "require", below), we assume the JavaScript model that the object can be constructed with "new" -- WebIDL specifies that the external attribute "constructor" be applied to a definition that can be new'd, but putting the attribute on every object would be cumbersome. The node.js notion of "require" is subtly different from constructing -an object with Javascript's "new", but it has appealing semantics. We +an object with JavaScript's "new", but it has appealing semantics. We annotate WebIDL definitions that should be implemented with node.js's "require" semantics with the external attribute "ReturnFromRequire". - diff --git a/docs/aio.md b/docs/aio.md index 87ccdea55..dfd9e919d 100644 --- a/docs/aio.md +++ b/docs/aio.md @@ -31,9 +31,7 @@ Web IDL ------- This IDL provides an overview of the interface; see below for -documentation of specific API functions. Click -[here](Notes_on_WebIDL.md) for an explanation of zephyr.js' WebIDL -conventions. +documentation of specific API functions. We have a short document explaining [ZJS WebIDL conventions](Notes_on_WebIDL.md). ```javascript // require returns an AIO object @@ -60,26 +58,24 @@ callback ReadCallback = void (unsigned long value); AIO API ------- -### aio.open(AIOInit) -* 'AIOInit' *object* The AIOInit object has a single field called "pin" +### aio.open(init) +* 'init' *AIOInit object* The AIOInit object has a single field called "pin" that represents the name of the pin (either an integer or a string, depending on the board). +* Returns: an AIOPin object that may be used to read values from the pin. When setting the pin number, you can either use a raw number for your device or use the board support module such as [Arduino 101](./boards/arduino_101.md) or [K64F](./boards/frdm_k64f.md) to specify a named pin. -Returns an AIOPin object that be used to read values from the pin. - AIOPin API ---------- ### pin.read() +* Returns: the latest reading from the pin (an unsigned integer). Blocks until it gets the result. -Returns the latest reading from the pin (an unsigned integer). Blocks until it gets the result. - -### pin.readAsync(ReadCallback) -* 'ReadCallback' *callback* User-provided callback function that takes +### pin.readAsync(callback) +* 'callback' *ReadCallback* User-provided callback function that takes a single unsigned integer and has no return value. Pass a function for `ReadCallback` that will be called later when the result is @@ -95,11 +91,11 @@ any given time.* *NOTE: This function will probably be replaced with a version that instead returns a promise.* -### pin.on(eventType, ReadCallback) +### pin.on(eventType, callback) * 'eventType' *string* Type of event; currently, the only supported type is "change". -* 'ReadCallback' *callback* User-provided callback function that takes - a single, unsigned integer and has no return value; can be null. +* 'callback' *ReadCallback* User-provided callback function that takes + a single, unsigned integer and has no return value; can be null. The callback function is called any time the analog voltage changes. (At the moment, it actually gets called periodically even when it hasn't changed.) When null is diff --git a/docs/ble.md b/docs/ble.md index b4cb5fafc..0092ac732 100644 --- a/docs/ble.md +++ b/docs/ble.md @@ -38,8 +38,7 @@ treat them like decimals.* Web IDL ------- This IDL provides an overview of the interface; see below for documentation of -specific API functions. Click [here](Notes_on_WebIDL.md) for an -explanation of zephyr.js' WebIDL conventions. +specific API functions. We also have a short document explaining [ZJS WebIDL conventions](Notes_on_WebIDL.md). ```javascript @@ -79,16 +78,16 @@ interface Characteristic { attribute SubscribeCallback onSubscribe; attribute UnsubscribeCallback onUnsubscribe; attribute NotifyCallback onNotify; - attribute CharacteristicResult response; + attribute CharacteristicResult response; }; callback ReadCallback = void (unsigned long offset, - FulfillReadCallback fulfillreadcallback); + FulfillReadCallback fulfillReadCallback); callback WriteCallback = void (Buffer data, unsigned long offset, boolean withoutResponse, - FulfillWriteCallback fulfillwritecallback); + FulfillWriteCallback fulfillWriteCallback); callback SubscribeCallback = void (unsigned long maxValueSize, - FulfillSubscribeCallback fullfillsubscribecallback); + FulfillSubscribeCallback fullfillSubscribeCallback); callback FulfillReadCallback = void (CharacteristicResult result, Buffer data); callback FulfillWriteCallback = void (CharacteristicResult result); callback FulfillSubscribeCallback = void (Buffer data); @@ -105,83 +104,80 @@ BLE-supported Events -------------------- BLE is an [EventEmitter](./events.md) with the following events: -### Event: 'accept' +### Event: `accept` * `string` `clientAddress` Emitted when a BLE client has connected. `clientAddress` is a unique BLE address for the client in colon-separated format (e.g. 01:23:45:67:89:AB). -### Event: 'advertisingStart' +### Event: `advertisingStart` * `int` `status` Emitted when BLE services have begun to be advertised. The `status` will be 0 for success, otherwise for an error. -### Event: 'disconnect' +### Event: `disconnect` * `string` `clientAddress` Emitted when a BLE client has disconnected. `clientAddress` will be the same as -one previously sent with the 'accept' event. +one previously sent with the `accept` event. -### Event: 'stateChange' +### Event: `stateChange` * `string` `newState` -Emitted with 'poweredOn' when the BLE stack is ready to be used. No other states +Emitted with `poweredOn` when the BLE stack is ready to be used. No other states are supported at this time. BLE API ------- ### ble.disconnect(address) -*'address' *string* The address of the connected client. +* `address` *string* The address of the connected client. Disconnect the remote client. ### ble.startAdvertising(name, uuids, url) -* name *string* The `name` is limited to 26 characters and will be +* `name` *string* The `name` is limited to 26 characters and will be advertised as the device name to nearby BLE devices. -* uuids *string[]* The `uuids` array may contain at most 7 16-bit +* `uuids` *string[]* The `uuids` array may contain at most 7 16-bit UUIDs (four hex digits each). These UUIDs identify available services to nearby BLE devices. -* url *string* The `url` is optional and limited to around 24 +* `url` *string* The `url` is optional and limited to around 24 characters (slightly more if part of the URL is able to be [encoded](https://github.com/google/eddystone/tree/master/eddystone-url). If provided, this will be used to create a physical web advertisement that will direct users to the given URL. At that URL they might be able to interact with the advertising device somehow. - -Advertises the name of the device. + +Advertises the name and url of the device. ### ble.stopAdvertising() Currently does nothing. ### ble.setServices(primaryServices) -* primaryServices *array of PrimaryService objects* The PrimaryService +* `primaryServices` *array of [PrimaryService](#primaryservice) objects* The PrimaryService objects are used to set up the services that are implemented by your app. - + The PrimaryService object contains the following fields: ### ble.newPrimaryService(init) -* 'init' *PrimaryServiceInit*(#primaryserviceinit) - -Returns a new PrimaryService object. +* `init` [*PrimaryServiceInit*](#primaryserviceinit) +* Returns: a new PrimaryService object. ### ble.newCharacteristic(init) -* init *CharacteristicInit* - -Returns a new Characteristic object. +* `init` [*CharacteristicInit*](#characteristicinit) +* Returns: a new Characteristic object. ### ble.newDescriptor(init) -* 'init' *DescriptorInit*(#descriptorinit-struct) - -Returns a new DescriptorInit object. +* `init` [*DescriptorInit*](#descriptorinit) +* Returns: a new DescriptorInit object. Characteristic API @@ -204,8 +200,8 @@ Supporting Objects ### PrimaryServiceInit This object has two fields: -1. 'uuid' *string* This field is a 16-bit service UUID (4 hex chars). -2. `characteristics` *array of [Characteristics](#characteristic)* +1. `uuid` *string* This field is a 16-bit service UUID (4 hex chars). +2. `characteristics` *array of [Characteristics](#characteristic-api)* ### CharacteristicInit @@ -236,9 +232,9 @@ It may also contain these optional callback fields: ### DescriptorInit This object has two fields: -1. 'uuid' *string* This is a 16-bit descriptor UUID (4 hex chars) +1. `uuid` *string* This is a 16-bit descriptor UUID (4 hex chars) * Defined descriptors are listed here in [Bluetooth Specifications](https://www.bluetooth.com/specifications/gatt/descriptors) -2. 'value' *string* This string supplies the defined information. +2. `value` *string* This string supplies the defined information. * *NOTE: Values can also be Buffer objects, but that's not currently supported.* diff --git a/docs/buffer.md b/docs/buffer.md index 8d9054f65..0449e39b3 100644 --- a/docs/buffer.md +++ b/docs/buffer.md @@ -24,20 +24,19 @@ subset of this API that will be expanded as the need arises. Web IDL ------- This IDL provides an overview of the interface; see below for documentation of -specific API functions. Click [here](Notes_on_WebIDL.md) for an -explanation of zephyr.js' WebIDL conventions. +specific API functions. We have a short document explaining [ZJS WebIDL conventions](Notes_on_WebIDL.md). ```javascript -[ Constructor(Uint8Array initial_values), +[ Constructor(Uint8Array initialValues), Constructor(unsigned long size), - Constructor(ByteString initial_string) ] + Constructor(ByteString initialString) ] interface Buffer { readonly attribute unsigned long length; unsigned long copy(Buffer target, optional unsigned long targetStart = 0, optional unsigned long sourceStart = 0, - optional unsigned long sourceEnd = this.length); + optional unsigned long sourceEnd); this fill((string or Buffer or long) value, optional long offset = 0, - optional long end = this.length, + optional long end, optional string encoding = "utf8"); octet readUInt8(optional unsigned long offset = 0); short readUInt16BE(optional unsigned long offset = 0); @@ -58,8 +57,8 @@ interface Buffer { Buffer API ---------- -### new Buffer(array) -* `array` *integer[]* Array of octets to use as initial data. +### new Buffer(initialValues) +* `initialValues` *integer[]* Array of octets to use as initial data. A new Buffer object will be returned with the same size as the array and initialized with the array's contents. If there is not enough @@ -73,8 +72,8 @@ represents. If a negative length is passed, a 0-length Buffer will be returned. If there is not enough available memory to allocate the Buffer, an error will be thrown. -### new Buffer(string) -* `string` *string* String to use as initial data. +### new Buffer(initialString) +* `initialString` *string* String to use as initial data. The `string` argument will be treated as an array of UTF8 values and will be used to initialize the new buffer. If there is not enough From 6e2ab61cb0e921e5f2b9f9a487ce580e4ffa8078 Mon Sep 17 00:00:00 2001 From: Timothy Harvey Date: Tue, 5 Jun 2018 21:38:18 -0500 Subject: [PATCH 04/18] jfjfjf --- docs/aio.md | 11 ++- docs/ble.md | 28 +++--- docs/board.md | 29 +++--- docs/buffer.md | 17 ++-- docs/fs.md | 216 +++++++++++++++++++++++---------------------- docs/gpio.md | 127 +++++++++++++------------- docs/grove_lcd.md | 175 +++++++++++++++++------------------- docs/i2c.md | 77 ++++++++-------- docs/mathstubs.md | 27 +++--- docs/net-config.md | 60 ++++++------- docs/spi.md | 116 ++++++++++++------------ docs/uart.md | 88 +++++++++--------- docs/web-socket.md | 97 +++++++++++--------- 13 files changed, 541 insertions(+), 527 deletions(-) diff --git a/docs/aio.md b/docs/aio.md index dfd9e919d..4a1e9acc8 100644 --- a/docs/aio.md +++ b/docs/aio.md @@ -31,9 +31,12 @@ Web IDL ------- This IDL provides an overview of the interface; see below for -documentation of specific API functions. We have a short document explaining [ZJS WebIDL conventions](Notes_on_WebIDL.md). +documentation of specific API functions. We have a short document +explaining [ZJS WebIDL conventions](Notes_on_WebIDL.md). -```javascript +
+Click to show WebIDL +
 // require returns an AIO object
 // var aio = require('aio');
 
@@ -53,8 +56,8 @@ interface AIOPin {
     void close();
 };
 
-callback ReadCallback = void (unsigned long value);
-```
+callback ReadCallback = void (unsigned long value);
+
AIO API ------- diff --git a/docs/ble.md b/docs/ble.md index 0092ac732..5529ed05d 100644 --- a/docs/ble.md +++ b/docs/ble.md @@ -37,14 +37,15 @@ treat them like decimals.* Web IDL ------- + This IDL provides an overview of the interface; see below for documentation of specific API functions. We also have a short document explaining [ZJS WebIDL conventions](Notes_on_WebIDL.md). - - -```javascript +
+ Click to show/hide WebIDL +
 // require returns a BLE object
 // var ble = require('ble');
-
+

[ReturnFromRequire] interface BLE: EventEmitter { void disconnect(string address); @@ -55,12 +56,12 @@ interface BLE: EventEmitter { Characteristic newCharacteristic(CharacteristicInit init); Descriptor newDescriptor(DescriptorInit init); }; - +

dictionary PrimaryServiceInit { string uuid; Characteristic[] characteristics; }; - +

dictionary CharacteristicInit { string uuid; string[] properties; // 'read', 'write', 'notify' @@ -71,7 +72,7 @@ dictionary CharacteristicInit { UnsubscribeCallback onUnsubscribe; // optional NotifyCallback onNotify; // optional }; - +

interface Characteristic { attribute ReadCallback onReadRequest; attribute WriteCallback onWriteRequest; @@ -80,7 +81,7 @@ interface Characteristic { attribute NotifyCallback onNotify; attribute CharacteristicResult response; }; - +

callback ReadCallback = void (unsigned long offset, FulfillReadCallback fulfillReadCallback); callback WriteCallback = void (Buffer data, unsigned long offset, @@ -91,14 +92,15 @@ callback SubscribeCallback = void (unsigned long maxValueSize, callback FulfillReadCallback = void (CharacteristicResult result, Buffer data); callback FulfillWriteCallback = void (CharacteristicResult result); callback FulfillSubscribeCallback = void (Buffer data); - -enum CharacteristicResult { "RESULT_SUCCESS", "RESULT_INVALID_OFFSET", "RESULT_INVALID_ATTRIBUTE_LENGTH", "RESULT_UNLIKELY_ERROR" } ; - +

+enum CharacteristicResult { "RESULT_SUCCESS", "RESULT_INVALID_OFFSET", + "RESULT_INVALID_ATTRIBUTE_LENGTH", "RESULT_UNLIKELY_ERROR" } ; +

dictionary DescriptorInit { string uuid; string value; -}; -``` +};

+
BLE-supported Events -------------------- diff --git a/docs/board.md b/docs/board.md index e4edf85de..3ce746b7c 100644 --- a/docs/board.md +++ b/docs/board.md @@ -3,7 +3,9 @@ ZJS Board API * [Introduction](#introduction) * [Web IDL](#web-idl) -* [API Documentation](#api-documentation) +* [Class: Board](#board-api) + * [board.name](#boardname) + * [board.version](#boardversion) * [Sample Apps](#sample-apps) Introduction @@ -15,23 +17,24 @@ but both that and ZJS are under a lot of change at the moment. Web IDL ------- -This IDL provides an overview of the interface; see below for documentation of -specific API functions. -```javascript -// require returns the Board API object +This IDL provides an overview of the interface; see below for +documentation of specific API functions. We have a short document explaining [ZJS WebIDL conventions](Notes_on_WebIDL.md). +
+ Click to show/hide WebIDL +
// require returns the Board API object
 // var board = require('board');
-
+

[NoInterfaceObject] interface Board { string name; string version; -}; -``` +};

+
-API Documentation +Board API ----------------- -### Board.name +### board.name `string name;` @@ -42,14 +45,14 @@ When code is run under Linux with the jslinux utility, it currently reports a board name of "linux (partially simulating arduino_101)". Any other board will show up with "unknown". Even if the board is unknown, you -can still use the [GPIO API](gpio.md) at least by consulting Zephyr +can still use the [GPIO API](gpio.md) by consulting Zephyr documentation for the board's GPIO port names and pin numbers. -### Board.version +### board.version `string version;` -For now, just returns "0.1". Stay tuned! +Currently, this value is always set to "0.1". Stay tuned! Sample Apps ----------- diff --git a/docs/buffer.md b/docs/buffer.md index 0449e39b3..da52337b1 100644 --- a/docs/buffer.md +++ b/docs/buffer.md @@ -4,9 +4,9 @@ ZJS API for Buffer * [Introduction](#introduction) * [Web IDL](#web-idl) * [Class: Buffer](#buffer-api) - * [new Buffer(array)](#new-bufferarray) + * [new Buffer(initialValues)](#new-bufferinitialvalues) * [new Buffer(size)](#new-buffersize) - * [new Buffer(string)](#new-bufferstring) + * [new Buffer(initialString)](#new-bufferinitialstring) * [buf.copy(target[, targetStart, [sourceStart[, sourceEnd]]])](#bufcopytarget-targetstart-sourcestart-sourceend) * [buf.fill(value[, offset[, end[, encoding]]])](#buffillvalue-offset-end-encoding) * [buf.readUInt*(offset)](#bufreaduint-family) @@ -26,12 +26,15 @@ Web IDL This IDL provides an overview of the interface; see below for documentation of specific API functions. We have a short document explaining [ZJS WebIDL conventions](Notes_on_WebIDL.md). -```javascript -[ Constructor(Uint8Array initialValues), +
+ Click to show/hide WebIDL +
+[ Constructor(sequence < Uint8 > initialValues),
   Constructor(unsigned long size),
   Constructor(ByteString initialString) ]
 interface Buffer {
     readonly attribute unsigned long length;
+    attribute ArrayBuffer buffer;
     unsigned long copy(Buffer target, optional unsigned long targetStart = 0,
                                       optional unsigned long sourceStart = 0,
                                       optional unsigned long sourceEnd);
@@ -52,13 +55,13 @@ interface Buffer {
     long writeUInt16LE(unsigned short value, unsigned long offset);
     long writeUInt32BE(unsigned long value, unsigned long offset);
     long writeUInt32LE(unsigned long value, unsigned long offset);
-};
-```
+};
+
Buffer API ---------- ### new Buffer(initialValues) -* `initialValues` *integer[]* Array of octets to use as initial data. +* `initialValues` *integer-array* of octets to use as initial data. A new Buffer object will be returned with the same size as the array and initialized with the array's contents. If there is not enough diff --git a/docs/fs.md b/docs/fs.md index c6a6afb34..232768f66 100644 --- a/docs/fs.md +++ b/docs/fs.md @@ -2,21 +2,36 @@ ZJS API for File System ================== * [Introduction](#introduction) -* [API Documentation](#api-documentation) -* [Sample Apps](#sample-apps) +* [Web IDL](#web-idl) +* [Class FS](#fs-api) + * [fs.openSync(path, mode)](#fsopensyncpath-mode) + * [fs.closeSync(fd)](#fsclosesyncfd) + * [fs.unlinkSync(path)](#fsunlinksyncpath) + * [fs.rmdirSync(path)](#fsrmdirsyncpath) + * [fs.writeSync(fd, data, offset, length, position)](#fswritesyncfd-data-offset-length-position) + * [fs.readSync(fd, data, offset, length, position)](#fsreadsyncfd-data-offset-length-position) + * [fs.truncateSync(path, length)](#fstruncatesyncpath-length) + * [fs.mkdirSync(path)](#fsmkdirsyncpath) + * [fs.readdirSync(path)](#fsreaddirsyncpath) + * [fs.statSync(path)](#fsstatsyncpath) + * [writeFileSync(file, data)](#writefilesyncfile-data) +* [Class Stat](#stat-api) + * [stat.isFile()](#statisfile) + * [stat.isDirectory()](#statisdirectory) Introduction ------------ -ZJS provides File System API's which match Node.js' FS module. We describe them -here as there could potentially be minor differences. It should be noted that by -default the FS module only contains the synchronous Node.js API's. The -asynchronous API's can be compiled in by enabling the pre-processor define -`ZJS_FS_ASYNC_APIS`. They are compiled out because all of Zephyr's File -System API's are synchronous, so making the JavaScript API's asynchronous was -only adding ROM space. - -On the Arduino 101 the flash file system uses SPI and the pins are shared with -IO10-13. For this reason you will not be able to use these GPIO pins at the + +ZJS provides File System APIs that match Node.js' FS module. We +describe them here to document any minor differences. It should be +noted that by default, the FS module only contains the synchronous +Node.js APIs. The asynchronous APIs can be compiled in by enabling the +pre-processor value `ZJS_FS_ASYNC_APIS`. The default is to leave them +out, because all of Zephyr's File System APIs are synchronous, so +making the JavaScript APIs asynchronous was only adding ROM space. + +On the Arduino 101, the flash file system uses SPI, and the pins are shared with +IO10-13. For this reason, you will not be able to use these GPIO pins at the same time as the file system. Available file modes: @@ -27,148 +42,141 @@ not exist. `'r+'` - Open a file for reading and writing. An error will be thrown if the file does not exist. -`'w'` - Opens a file for writing. The file will be overwritten if it already +`'w'` - Open a file for writing. The file will be overwritten if it already exists. -`'w+'` - Opens a file for writing and reading. The file will be overwritten if +`'w+'` - Open a file for writing and reading. The file will be overwritten if it already exists. `'a'` - Opens a file for appending. The write pointer will always seek to the end of the file during a write. -`'a+'` - Opens a file for appending and reading. As with `'a'` the write -pointer will seek to the end for writes, but reads can be done from the -start of the file (read pointer saved across different read calls). +`'a+'` - Opens a file for appending and reading. The write +pointer will seek to the end for writes, but reads will be done from the +start of the file (the read pointer is saved across different read calls). Web IDL ------- -This IDL provides an overview of the interface; see below for documentation of -specific API functions. +This IDL provides an overview of the interface; see below for +documentation of specific API functions. We have a short document +explaining [ZJS WebIDL conventions](Notes_on_WebIDL.md). -```javascript +
+Click to show WebIDL +
 // require returns a FS object
 // var fs = require('fs');
-
-interface Stat {
+

+[ReturnFromRequire, ExternalInterface=(buffer,Buffer)] +interface FS { + FileDescriptor openSync(string path, FileMode mode); + void closeSync(FileDescriptor fd); + void unlinkSync(string path); + void rmdirSync(string path); + long writeSync(FileDescriptor fd, (string or Buffer) data, long offset, + long length, optional long position); + long readSync(FileDescriptor fd, Buffer data, long offset, + long length, long position); + void truncateSync(string path, long length); + void mkdirSync(string path); + sequence < string > readdirSync(string path); + Stat statSync(string path); + void writeFileSync(string file, (string or Buffer) data); +};

// file descriptors are inherently platform specific, so we leave this +// as a placeholder +definition FileDescriptor { +};

interface Stat { boolean isFile(); boolean isDirectory(); -}; -``` +};

enum FileMode { "r", "w", "a", "r+", "w+", "a+" };

+
-API Documentation ------------------ +FS API +------ -### FS.openSync -`object openSync(string path, string mode);` +### fs.openSync(path, mode) +* `path` *string* The name and path of the file to open. +* `mode` *FileMode* The mode in which to open the file. +* Returns: an object representing the file descriptor. Opens a file. -`path` is the name/path of the file to open. - -`mode` is the mode to open the file in (r/w/a/r+/w+/a+). - -Returns an object representing the file descriptor. - -### FS.closeSync -`void closeSync(object fd);` +### fs.closeSync(fd) +* `fd` *FileDescriptor* The file descriptor for the file that will be closed. Closes a file. -`fd` is the descriptor returned from `openSync()`. - -### FS.unlinkSync -`void unlinkSync(string path);` +### fs.unlinkSync(path) +* `path` *string* The name and path of the file to remove. Unlink (remove) a file from the file system. -`path` is the file to remove. - -### FS.rmdirSync -`void rmdirSync(string path);` +### fs.rmdirSync(path) +* `path` *string* The name and path of the directory to be removed. Remove a directory from the file system. -`path` is the name of the directory. - -### FS.writeSync -`number writeSync(object fd, Buffer data, number offset, number length, optional number position);` +### fs.writeSync(fd, data, offset, length, position) +* `fd` *FileDescriptor* The file descriptor returned from `openSync()`. +* `data` *string or Buffer* The data to write to 'fd'. +* `offset` *long* The position in 'data' from which to start writing. +* `length` *long* The number of bytes to write to 'fd' from 'data'. +* `position` *long* The offset from the beginning of the file where + 'data' should be written. The parameter is optional; the default value is 0. +* Returns: the number of bytes actually written (this may be different from 'length'). Write bytes to an opened file. -`fd` is the file descriptor returned from `openSync()`. - -`data` is either a string or buffer to write. - -`offset` is the position in `data` to start writing from. - -`length` is the number of bytes to write from `data`. - -`position` is the offset from the beginning of the file where `data` should be -written. Default is 0. - -Returns the number of bytes actually written (this may be different from `length`). - -### FS.readSync -`number readSync(object fd, buffer data, number offset, number length, number position);` +### fs.readSync(fd, data, offset, length, position) +* `fd` *FileDescriptor* The file descriptor returned from 'openSync()'. +* `data` *Buffer* The buffer into which the data will be read. +* `offset` *long* The offset in 'data' at which to start writing. +* `length` *long* The number of bytes to read. +* `position` *long* The position in the file from which to start reading. +* Returns: the number of bytes actually read. This may be different from +'length' if there was a read error or if the file had no more data left to read. Read bytes from a file. -`fd` is the file descriptor returned from `openSync()`. - -`data` is a buffer where the data will be read into. - -`offset` is the offset in `data` to start writing at. - -`length` is the number of bytes to read. - -`position` is the position in the file to start reading from. - -Returns the number of bytes actually read. This may be different from `length` -if there was a read error or if the file had no more data left to read. - -### FS.truncateSync -`void truncateSync(string path, number length);` +### fs.truncateSync(path, length) +* `path` *string* The name and path of the file. +* `length` *long* The new length of the file. Truncate a file. If the length passed in is shorter than the existing file -length then the trailing file data will be lost. - -`path` is the name of the file. +length, then the trailing file data will be lost. -`length` is the new length of the file. +### fs.mkdirSync(path) +* `path` *string* The name and path of the directory. -### FS.mkdirSync -`void mkdirSync(string path)` +Create a directory. There is no effect if the directory already exists. -Create a directory. If the directory already exists there is no effect. - -`path` is the name of the directory. - -### FS.readdirSync -`string[] readdirSync(string path);` +### fs.readdirSync(path) +* `path` *string* The name and path of the directory to read. +* Returns: an array of filenames and directories found in 'path'. Read the contents of a directory. -`path` directory path to read. - -Returns an array of filenames and directories found in `path`. - -### FS.statSync -`Stat statSync(string path);` +### fs.statSync(path) +* `path` *string* The name and path of the file or directory. +* Returns: a 'Stat' object for the file or directory or undefined if the +file or directory does not exist. Get stats about a file or directory. -`path` name of file or directory. - -Returns a `Stat` object for that file or directory or undefined if file or directory does not exist. - -### FS.writeFileSync -`void writeFileSync(string file, [string|buffer] data);` +### writeFileSync(file, data) +* `file` *string* The name of the file to which to write. +* `data` *string or Buffer* The data to write into the file. Open and write data to a file. This will replace the file if it already exists. -`file` is the name of the file to write to. +Stat API +-------- + +### stat.isFile() +* Returns: true if the file descriptor is a file. -`data` is the bytes to write into the file. +### stat.isDirectory() +* Returns: true if the file descriptor is a directory. Sample Apps ----------- diff --git a/docs/gpio.md b/docs/gpio.md index 19277a89a..e9f12b94d 100644 --- a/docs/gpio.md +++ b/docs/gpio.md @@ -3,7 +3,13 @@ ZJS API for General Purpose I/O (GPIO) * [Introduction](#introduction) * [Web IDL](#web-idl) -* [API Documentation](#api-documentation) +* [Class GPIO](#gpio-api) + * [GPIO.open(init)](#gpioopeninit) +* [Class GPIOPin](#gpiopin-api) + * [pin.read()](#pinread) + * [pin.write()](#pinwritevalue) + * [pin.close()](#pinclose) + * [pin.onchange](#pinonchange) * [Sample Apps](#sample-apps) Introduction @@ -17,108 +23,95 @@ but both that and ZJS are under a lot of change at the moment. Web IDL ------- This IDL provides an overview of the interface; see below for documentation of -specific API functions. +specific API functions. We have a short document explaining [ZJS WebIDL conventions](Notes_on_WebIDL.md). -```javascript +
+ Click to show/hide WebIDL +
 // require returns a GPIO object
-// var gpio = require('gpio');
-
-[NoInterfaceObject]
+// var gpio = require('gpio');

+[ReturnFromRequire] interface GPIO { - GPIOPin open(number or string or GPIOInit init); -}; - -dictionary GPIOInit { - number or string pin; + GPIOPin open( (long or string or GPIOInit) init); +};

dictionary GPIOInit { + (long or string) pin; boolean activeLow = false; - string mode = "out"; // in, out - string edge = "none"; // none, rising, falling, any - string state = "none"; // none, up, down -}; - -[NoInterfaceObject] -interface GPIOPin { - number read(); - void write(number value); + GPIOMode mode = "out"; + GPIOEdge edge = "none"; + GPIOState state = "none"; +};

interface GPIOPin { + long read(); + void write(long value); void close(); attribute ChangeCallback onchange; -}; - -callback ChangeCallback = void (GPIOEvent); - -dictionary GPIOEvent { - number value; -} -``` - -API Documentation ------------------ -### GPIO.open - -`GPIOPin open(number or string or GPIOInit init);` - -If the argument is a number, it is a pin number. If it is a string, it is a -pin name. Otherwise, it must be a GPIOInit object. - -The `init` object lets you set the pin number or name with the `pin` property. +};

callback ChangeCallback = void (GPIOEvent event);

dictionary GPIOEvent { + long value; +};

enum GPIOMode { "out", "in" }; +enum GPIOEdge { "none", "rising", "falling", "any" }; +enum GPIOState { "none", "up", "down" };

+
+ +GPIO API +-------- +### gpio.open(init) +* `init` *long or string or GPIOInit* If the argument is a number, it is a pin number. If it is a +string, it is a pin name. Otherwise, it must be a GPIOInit object. +* Returns: a GPIOPin object that can be used to read or write the pin. If the pin number or name is valid for the given board, the call will succeed. You can use a pin name like "GPIO_0.10" where "GPIO_0" is the name of a Zephyr gpio port device for your board and 10 is the pin number. This will work on any board as long as you find the right values in Zephyr documentation. But for -boards with specific ZJS support, you can use friendly names. Currently this +boards with specific ZJS support, you can use friendly names. Currently, this means Arduino 101 and FRDM-K64F. For the A101, you can use numbers 0-13 or strings "IO0" through "IO13", as well as "LED0" through "LED2". For K64F, you can use numbers 0-15 or strings "D0" through "D15", as well as "LEDR", "LEDG", and "LEDB" for the RGB LED, and "SW2" and "SW3" for onboard switches. -The other values are optional. The `activeLow` setting determines whether -high (default) or low means active. When you read or write a boolean value, -true means 'active' and false means 'inactive'. +The GPIOInit object can take a string or number as the pin argument, +and all of the rest of the fields are optional. The `activeLow` +setting determines whether high (default) or low means active. When +you read or write a boolean value, true means 'active' and false means +'inactive'. The `mode` value determines whether the pin is an input ('in') or output -('out', default). +('out'). The `edge` value is for input pins and tells whether the `onchange` callback will be called on the rising edge of the signal, falling edge, or both. -The `state` value is to enable an internal pullup or pulldown resistor. This -would be used for inputs to provide a default (high or low) when the input is -floating (not being intentionally driven to a particular value). +The `state` value is useful when the architecture has an internal +pullup or pulldown resistor. This would be used for inputs to provide +a default (high or low) when the input is floating (not being +intentionally driven to a particular value). *NOTE: When we last checked, Zephyr did not use this state setting, at least for -Arduino 101. Perhaps there is no hardware support, but in any case it didn't +Arduino 101. Perhaps there is no hardware support, but in any case, it didn't work. You can always provide an external resistor for this purpose instead.* -The function returns a GPIOPin object that can be used to read or write the pin. - -### GPIOPin.read - -`number read();` +GPIOPin API +----------- +### pin.read() +* Returns: the current reading from the pin. -Returns the current reading from the pin. This is a synchronous function because -it should be nearly instantaneous on the devices we've tested with so far. The -value will be 1 if the pin is active (high by default, low for a pin configured +This is a synchronous function, because it is nearly +instantaneous on the devices we've tested with so far. The value will +be 1 if the pin is active (high by default, low for a pin configured active low), 0 if inactive. -### GPIOPin.write - -`void write(number value);` - -Pass 1 for `value` to make an output pin active (high by default, low for a pin -configured active low), 0 to make it inactive. - -### GPIOPin.close +### pin.write(value) +* `value` *long* Pass 1 for `value` to make an output pin active +(high by default, low for a pin configured active low), 0 to make it inactive. -`void close();` +### pin.close() Free up resources associated with the pin. The onchange function for this pin will no longer be called, and the object should not be used for reading and writing anymore. -### GPIOPin.onchange +### pin.onchange -`attribute ChangeCallback onchange;` +* `onchange` *ChangeCallback* Set this attribute to a function that will receive events whenever the pin changes according to the edge condition specified at pin initialization. The diff --git a/docs/grove_lcd.md b/docs/grove_lcd.md index 24e489d32..49be72a3c 100644 --- a/docs/grove_lcd.md +++ b/docs/grove_lcd.md @@ -3,106 +3,108 @@ ZJS API for Grove LCD * [Introduction](#introduction) * [Web IDL](#web-idl) -* [API Documentation](#api-documentation) +* [GroveLCD API](#grovelcd-api) + * [grove_lcd.init()](#grove_lcdinit) +* [GroveLCDDevice API](#grovelcddevice-api) + * [groveLCDDevice.print(string text)](#grovelcddeviceprinttext) + * [groveLCDDevice.clear()](#grovelcddeviceclear) + * [groveLCDDevice.setCursorPos(col, row)](#grovelcddevicesetcursorposcol-row) + * [groveLCDDevice.selectColor(index)](#grovelcddeviceselectcolorindex) + * [groveLCDDevice.setColor(r, g, b)](#grovelcddevicesetcolorr-g-b) + * [groveLCDDevice.setFunction(config)](#grovelcddevicesetfunctionconfig) + * [groveLCDDevice.getFunction()](#grovelcddevicegetfunction) + * [groveLCDDevice.setDisplayState(config)](#grovelcddevicesetdisplaystateconfig) + * [GroveLCDDevice.getDisplayState()](#grovelcddevicegetdisplaystate) + * [Sample Apps](#sample-apps) Introduction ------------ The Grove LCD API is the JavaScript version of the Zephyr API that supports the Grove LCD. It works over I2C to allow user to send text to the LCD screen -and also configure LCD to different RGB backlight colors. +and also configure the LCD to different RGB backlight colors. Web IDL ------- -This IDL provides an overview of the interface; see below for documentation of -specific API functions. - -```javascript -// require returns a GroveLCD object -// var grove_lcd = require('grove_lcd'); - -[NoInterfaceObject] +This IDL provides an overview of the interface; see below for +documentation of specific API functions. We have a short document +explaining [ZJS WebIDL conventions](Notes_on_WebIDL.md). + +
+Click to show WebIDL +
// require returns a GroveLCD object
+// var grove_lcd = require('grove_lcd');

[ReturnFromRequire] interface GroveLCD { GroveLCDDevice init(); - unsigned long GLCD_FS_8BIT_MODE; - unsigned long GLCD_FS_ROWS_2; - unsigned long GLCD_FS_ROWS_1; - unsigned long GLCD_FS_DOT_SIZE_BIG; - unsigned long GLCD_FS_DOT_SIZE_LITTLE; - - unsigned long GLCD_DS_DISPLAY_ON; - unsigned long GLCD_DS_DISPLAY_OFF; - unsigned long GLCD_DS_CURSOR_ON; - unsigned long GLCD_DS_CURSOR_OFF; - unsigned long GLCD_DS_BLINK_ON; - unsigned long GLCD_DS_BLINK_OFF; - - unsigned long GLCD_IS_SHIFT_INCREMENT; - unsigned long GLCD_IS_SHIFT_DECREMENT; - unsigned long GLCD_IS_ENTRY_LEFT; - unsigned long GLCD_IS_ENTRY_RIGHT; - - unsigned long GROVE_RGB_WHITE; - unsigned long GROVE_RGB_RED; - unsigned long GROVE_RGB_GREEN; - unsigned long GROVE_RGB_BLUE; -}; - -[NoInterfaceObject] -interface GroveLCDDevice { + attribute unsigned long GLCD_FS_8BIT_MODE; + attribute unsigned long GLCD_FS_ROWS_2; + attribute unsigned long GLCD_FS_ROWS_1; + attribute unsigned long GLCD_FS_DOT_SIZE_BIG; + attribute unsigned long GLCD_FS_DOT_SIZE_LITTLE; +

+ attribute unsigned long GLCD_DS_DISPLAY_ON; + attribute unsigned long GLCD_DS_DISPLAY_OFF; + attribute unsigned long GLCD_DS_CURSOR_ON; + attribute unsigned long GLCD_DS_CURSOR_OFF; + attribute unsigned long GLCD_DS_BLINK_ON; + attribute unsigned long GLCD_DS_BLINK_OFF; +

+ attribute unsigned long GLCD_IS_SHIFT_INCREMENT; + attribute unsigned long GLCD_IS_SHIFT_DECREMENT; + attribute unsigned long GLCD_IS_ENTRY_LEFT; + attribute unsigned long GLCD_IS_ENTRY_RIGHT; +

+ attribute unsigned long GROVE_RGB_WHITE; + attribute unsigned long GROVE_RGB_RED; + attribute unsigned long GROVE_RGB_GREEN; + attribute unsigned long GROVE_RGB_BLUE; +};

interface GroveLCDDevice { void print(string text); void clear(); void setCursorPos(unsigned long col, unsigned long row); void selectColor(unsigned long index); void setColor(unsigned long r, unsigned long g, unsigned long b); void setFunction(unsigned long config); - unsigned long getFunction(); + attribute unsigned long getFunction(); void setDisplayState(unsigned long config); - unsigned long getDisplayState(); -}; -``` - -API Documentation ------------------ -### GroveLCD.init - -`GroveLCDDevice init();` - -Initialize the Grove LCD panel + attribute unsigned long getDisplayState(); +};

+
-*NOTE: Zephyr's Grove LCD API is on top of the I2C which is only accessible -from the ARC side on the Arduino 101, so all the API in here will use the -IPM to send commands over to the API, and all the API will be synchronous* - -The function returns a GroveLCDDevice object instance that can be used to +GroveLCD API +------------ +### grove_lcd.init() +* Returns: a GroveLCDDevice object that can be used to talk to the Grove LCD panel. -### GroveLCDDevice.print +Initializes the Grove LCD panel. + +*NOTE: Zephyr's Grove LCD API is on top of the I2C, which is only accessible +from the ARC side on the Arduino 101, so all the APIs in here will use the +IPM to send commands over to the API, and all this API will be synchronous.* -`void print(string text);` +GroveLCDDevice API +------------------ +### groveLCDDevice.print(text) +* `text` *string* The text to be printed. Send text to the screen on the current line cursor is set to, if the text is longer than number of characters it can fit on that line, any additional characters will not wrap around and be dropped, so a 16x2 LCD will have a maximum of 16 characters. -### GroveLCDDevice.clear - -`void clear();` +### groveLCDDevice.clear() Clear the current display. -### GroveLCDDevice.setCursorPos - -`void setCursorPos(unsigned long col, unsigned long row);` +### groveLCDDevice.setCursorPos(col, row) +* `col` *unsigned long* The column for the cursor to be moved to (0-15). +* `row` *unsigned long* The row the column should be moved to (0 or 1). -Set text cursor position for next additions. -The `col` is the column for the cursor to be moved to (0-15). -The `row` is the row it should be moved to (0 or 1). +Set text cursor position for the next print. -### GroveLCDDevice.selectColor - -`void selectColor(unsigned long index);` +### groveLCDDevice.selectColor(index) +* `index` *unsigned long* The color selection, as defined, below. Set LCD background to a predfined color. @@ -116,25 +118,21 @@ GroveLCD.GROVE_RGB_GREEN GroveLCD.GROVE_RGB_BLUE -### GroveLCDDevice.setColor - -`void setColor(unsigned long r, unsigned long g, unsigned long b);` - -Set LCD background to custom RGB color value +### groveLCDDevice.setColor(r, g, b) +* `r` *unsigned long* The numeric value for the red color (max is 255). +* `g` *unsigned long* The numeric value for the green color (max is 255). +* `b` *unsigned long* The numeric value for the blue color (max is 255). -The `r` is a numeric value for the red color (max is 255). -The `g` is a numeric value for the green color (max is 255). -The `b` is a numeric value for the blue color (max is 255). +Set LCD background to custom RGB color value. -### GroveLCDDevice.setFunction - -`void setFunction(unsigned long config);` +### groveLCDDevice.setFunction(config) +* `config` *unsigned long* The bit mask to change the display state, as described, below. This function provides the user the ability to change the state of the display, controlling things like the number of rows, dot size, and text display quality. -The `config` is bit mask of the following configurations: +The `config` bit mask can take the following configurations: GroveLCD.GLCD_FS_8BIT_MODE @@ -146,15 +144,11 @@ GroveLCD.GLCD_FS_DOT_SIZE_BIG GroveLCD.GLCD_FS_DOT_SIZE_LITTLE -### GroveLCDDevice.getFunction +### groveLCDDevice.getFunction() +*Returns: the function-features set associated with the device. -`unsigned long getFunction();` - -Return the function features set associated with the device. - -### GroveLCDDevice.setDisplayState - -`void setDisplayState(unsigned long config);` +### groveLCDDevice.setDisplayState(config) +* `config` *unsigned long* The bit mask to change the display state, as described, below. This function provides the user the ability to change the state of the display, controlling things like powering on or off @@ -175,11 +169,8 @@ GroveLCD.GLCD_DS_BLINK_ON GroveLCD.GLCD_DS_BLINK_OFF -### GroveLCDDevice.getDisplayState - -`unsigned long getDisplayState();` - -Return the display feature set associated with the device. +### GroveLCDDevice.getDisplayState() +* Returns: the display-feature set associated with the device. Sample Apps ----------- diff --git a/docs/i2c.md b/docs/i2c.md index 7849e318f..c5c2c4122 100644 --- a/docs/i2c.md +++ b/docs/i2c.md @@ -3,7 +3,12 @@ ZJS API for I2C * [Introduction](#introduction) * [Web IDL](#web-idl) -* [API Documentation](#api-documentation) +* [I2C API](#i2c-api) + * [i2c.open(init)](#i2copeninit) +* [I2CBus API](#i2cbus-api) + * [i2cBus.write(device, data)](#i2cbuswritedevice-data) + * [i2cBus.read(device, size, registerAddress)](#i2cbusreaddevice-size-registeraddress) + * [I2CBus.burstRead(device, size, registerAddress)](#i2cbusburstreaddevice-size-registeraddress) * [Sample Apps](#sample-apps) Introduction @@ -14,60 +19,58 @@ and SCL. SDA is the data signal and SCL is the clock signal. Web IDL ------- -This IDL provides an overview of the interface; see below for documentation of -specific API functions. - -```javascript -// require returns a I2C object -// var i2c = require('i2c'); - -[NoInterfaceObject] +This IDL provides an overview of the interface; see below for +documentation of specific API functions. We have a short document +explaining [ZJS WebIDL conventions](Notes_on_WebIDL.md). + +
+Click to show WebIDL +
// require returns a I2C object
+// var i2c = require('i2c');

[ReturnFromRequire] interface I2C { I2CBus open(I2CInit init); -}; - -dictionary I2CInit { +};

dictionary I2CInit { octet bus; I2CBusSpeed speed; -}; - -[NoInterfaceObject] +};

[ExternalInterface=(buffer,Buffer)] interface I2CBus { // has all the properties of I2CInit as read-only attributes - write(octet device, Buffer data); - read(octet device, unsigned int size, octet registerAddress); - burstRead(octet device, unsigned int size, octet registerAddress); -}; -``` - -API Documentation ------------------ -### I2C.open + void write(octet device, Buffer data); + void read(octet device, unsigned long size, octet registerAddress); + void burstRead(octet device, unsigned long size, octet registerAddress); +};

+
-`I2CBus open(I2CInit init);` - -The `init` object lets you set the I2C bus you wish to use and the speed you -want to operate at. Speed options are 10, 100, 400, 1000, and 34000. Speed is +I2C API +------- +### i2c.open(init) +* `init` *I2CInit* Lets you set the I2C bus you wish to use and the speed you +want to operate at. Speed options are 10, 100, 400, 1000, and 34000. Speed is measured in kbs. +* Returns: an I2CBus object. -### I2CBus.write - -`void write(octet device, Buffer data);` +I2CBus API +---------- +### i2cBus.write(device, data) +* `device` *octet* The device address. +* `data` *Buffer* The data to be written. Writes the data to the given device address. The first byte of data typically contains the register you want to write the data to. This will vary from device to device. -### I2CBus.read - -`Buffer read(octet device, unsigned int size, octet registerAddress);` +### i2cBus.read(device, size, registerAddress) +* `device` *octet* The device address. +* `size` *unsigned long* The number of bytes of data to read. +* `registerAddress` *octet* The register on the device from which to read. Reads 'size' bytes of data from the device at the registerAddress. The default value of registerAdress is 0x00; -### I2CBus.burstRead - -`Buffer burstRead(octet device, unsigned int size, octet registerAddress);` +### I2CBus.burstRead(device, size, registerAddress) +* `device` *octet* The device address. +* `size` *long* The number of bytes of data to read. +* `registerAddress` *octet* The number of the starting address from which to read. Reads 'size' bytes of data from the device across multiple addresses starting at the registerAddress. The default value of registerAdress is 0x00; diff --git a/docs/mathstubs.md b/docs/mathstubs.md index 6d27a3a17..515f7e36a 100644 --- a/docs/mathstubs.md +++ b/docs/mathstubs.md @@ -3,12 +3,13 @@ ZJS API for MathStubs * [Introduction](#introduction) * [Web IDL](#web-idl) -* [API Documentation](#api-documentation) +* [Mathstubs API](#mathstubs-api) + * [random()](#mathstubsrandom) * [Sample Apps](#sample-apps) Introduction ------------ -"MathStubs" module implements a subset of the Math libary's functions such +The "MathStubs" module implements a subset of the Math library's functions such as random(). This module is served as a replacement for the JerryScript's Math libary when you only need certain math functions without the need to import Math so your application can be smaller, since enabling the whole Math @@ -19,18 +20,22 @@ round(), floor(), etc. Web IDL ------- This IDL provides an overview of the interface; see below for documentation of -specific API functions. +specific API functions. We have a short document explaining [ZJS WebIDL conventions](Notes_on_WebIDL.md). -```javascript -double MathStubs.random(); -``` +
+ Click to show/hide WebIDL +
// require returns a MathStubs object
+// var mathStubs = require('mathstubs');

[ReturnFromRequire] +interface MathStubs { + double MathStubs.random(); +}; +

+
-API Documentation +Mathstubs API ----------------- -### random -`double random();` - -Returns a floating-point, pseudo-random number between 0 (inclusive)and 1 (exclusive). +### mathStubs.random() +* Returns: a floating-point, pseudo-random number between 0 (inclusive) and 1 (exclusive). Sample Apps ----------- diff --git a/docs/net-config.md b/docs/net-config.md index 752438acb..da585d0de 100644 --- a/docs/net-config.md +++ b/docs/net-config.md @@ -3,8 +3,12 @@ ZJS API for Network Configuration * [Introduction](#introduction) * [Web IDL](#web-idl) -* [API Documentation](#api-documentation) -* [Sample Apps](#sample-apps) +* [NetConfig API](#netconfig-api) + * [Event: 'netup'](#event-netup) + * [Event: 'netdown'](#event-netdown) + * [net_cfg.setStaticIP(ip)](#net_cfgsetstaticipip) + * [net_cfg.dhcp(callback)](#net_cfgdhcpcallback) + * [net_cfg.setBleAddress(address)](#net_cfgsetbleaddressaddress) Introduction ------------ @@ -19,26 +23,23 @@ static IP addresses of 192.0.2.1 and 2001:db8::1. Web IDL ------- This IDL provides an overview of the interface; see below for documentation of -specific API functions. +specific API functions. We have a short document explaining [ZJS WebIDL conventions](Notes_on_WebIDL.md). -```javascript +
+ Click to show/hide WebIDL +
 // require returns a Net object
-// var net_cfg = require('netconfig');
-
+// var net_cfg = require('netconfig');

[ExternalInterface=(eventemitter, EventEmitter)] interface NetConfig: EventEmitter { - // set a static IP - Boolean setStaticIP(String ip); - // start DHCP + boolean setStaticIP(string ip); void dhcp(DHCPCallback callback); - // set the BLE MAC address - void setBleAddress(String address); -}; - -callback DHCPCallback = void (String address, String subnet, String gateway); -``` + void setBleAddress(string address); +};

callback DHCPCallback = void (string address, string subnet, string gateway); +

+
-API Documentation ------------------ +NetConfig API +------------- NetConfig is an [EventEmitter](./events.md) with the following events: ### Event: 'netup' @@ -51,35 +52,30 @@ wait for a BLE connection before issuing any socket connections. Emitted when the networking interface goes offline. -### NetConfig.setStaticIP -`Boolean setStaticIP(String ip)` +### net_cfg.setStaticIP(ip) +* `ip` *string* This should be either an IPv4 or IPv6 string. +* Returns: true if the IP was successfully set and false if there was a problem setting the IP. Set the device to use a static IP address. -`ip` should be either an IPv4 or IPv6 string. - -This returns a true if the IP was successfully set. It will return false if -there was a problem setting that IP. An error will be returned if there was +An error will be returned if there was a misconfiguration, e.g. setting an IPv6 address when IPv6 was not built. -### NetConfig.dhcp -`void dhcp(DHCPCallback callback)` +### net_cfg.dhcp(callback) +* `callback` *DHCPCallback* Start DHCP to obtain an IP address. -`callback` should be a `DHCPCallback` type. This event listener will be called -when DHCP has finished. The callback will contain 3 arguments: `address`, +This `callback` event listener will be called when DHCP has +finished. The callback will contain 3 arguments: `address`, `subnet`, and `gateway`. -### NetConfig.setBleAddress -`void setBleAddress(string address);` +### net_cfg.setBleAddress(address) +* `address` *string* The MAC address string in the format `XX:XX:XX:XX:XX:XX`, where each character is in HEX format (0-9, A-F). Sets the device's BLE MAC address. This function is only defined on Zephyr boards with BLE capabilities (e.g. Arduino 101). -The `address` parameter should be a MAC address string in the format -`XX:XX:XX:XX:XX:XX` where each character is in HEX format (0-9, A-F). - Note: This function has be called when the JS is initially run when loaded. This means no calling from within any callback functions like setTimeout(), setInterval() and promises. Also, If the image was built diff --git a/docs/spi.md b/docs/spi.md index 8c8544bdf..90fc3515e 100644 --- a/docs/spi.md +++ b/docs/spi.md @@ -3,89 +3,93 @@ ZJS API for SPI * [Introduction](#introduction) * [Web IDL](#web-idl) -* [API Documentation](#api-documentation) -* [Sample Apps](#sample-apps) +* [SPI API](#spi-api) + * [spi.open(options)](#spiopenoptions) +* [SPIBus API](#spibus-api) + * [spiBus.transceive(target, data, direction)](#spibustransceivetarget-data-direction) + * [spiBus.close()](#spibusclose) Introduction ------------ The SPI API supports the Serial Peripheral Interface, a synchronous -serial protocol that allows multiple slave chips to communicate with a master chip. -A single SPI bus uses the following pins: SCLK for clock, -MOSI (Master Out, Slave In) for write, MISO (Master In, Slave Out) for read, and -one or more SS (Slave Select) for selecting the slave device. - -For each clock signal one bit is written from the master to the selected slave and -one bit is read by the master from the selected slave, so there is no separate -read and write, but one transceive operation. - -When a slave device's chip select is 0 (low), then it communicates with the -master, otherwise it ignores the master. The master can select multiple slaves in -a write-only configuration; in this case no slave is writing data, they only read. - -Since the SS pins may be connected to slave chip select through a demultiplexer -and thereby work as an address bus, slave devices are identified by an index in -this API, rather than by SS pins. Also, since multiple SPI buses may be present -on a board, these are identified by an index in this API. Implementations SHOULD -encapsulate the mapping from SPI bus number and device number to the physical SPI +serial protocol that allows multiple slave chips to communicate with a +master chip. A single SPI bus uses the following pins: SCLK for +clock, MOSI (Master Out, Slave In) for write, MISO (Master In, Slave +Out) for read, and one or more SS (Slave Select) for selecting the +slave device. + +For each clock signal, one bit is written from the master to the +selected slave, and one bit is read by the master from the selected +slave, so there is one transceive operation, instead of a separate +read and write. + +When a slave device's chip select is 0 (low), it communicates with the +master; otherwise it ignores the master. The master can select +multiple slaves in a write-only configuration; in this case, no slave +is writing data, each only reads. + +Since the SS pins may be connected to slave chip select through a +demultiplexer and thereby work as an address bus, slave devices are +identified by an index in this API, rather than by SS pins. Also, +since multiple SPI buses may be present on a board, these are +identified by an index in this API. Implementations SHOULD encapsulate +the mapping from SPI bus number and device number to the physical SPI pins. -Note that on the Arduino 101, using SPI will cause one of the onboard LED to +Note that on the Arduino 101, using SPI will cause one of the onboard LEDs to become unavailable. Web IDL ------- -This IDL provides an overview of the interface; see below for documentation of -specific API functions. - -```javascript -// require returns a SPI object -// var spi = require('spi'); - -[NoInterfaceObject] +This IDL provides an overview of the interface; see below for +documentation of specific API functions. We have a short document +explaining [ZJS WebIDL conventions](Notes_on_WebIDL.md). + +
+Click to show WebIDL +
// require returns a SPI object
+// var spi = require('spi');

[ReturnFromRequire] interface SPI { SPIBus open(SPIOptions init); -}; - -dictionary SPIOptions { +};

dictionary SPIOptions { octet bus; long speed; // bus clock frequency in Hz - bool msbFirst; + boolean msbFirst; long polarity; long phase; unsigned long frameGap; string topology; - -}; - -[NoInterfaceObject] +};

[ExternalInterface=(buffer,Buffer)] interface SPIBus { - transceive(octet target, Buffer data, string direction); + void transceive(octet target, Buffer data, string direction); close(); }; -``` - -API Documentation ------------------ -### SPI.open - -`SPIBus open(SPIOptions options);` +

+
-The `options` object lets you pass optional values to use instead of the defaults. -Note these values can't be changed once the SPI object is created. If you need -to change the settings afterwards, you'll need to use the 'close' command and -create a new SPI object with the settings you desire. - -### SPIBus.transceive - -`Buffer transceive(octet target, Buffer data, string direction);` +SPI API +------- +### spi.open(options) +* `options` *SPIOptions* The `options` object lets you pass optional values to use instead of the defaults. +* Returns: an SPIBus object. + +Note these `options` values can't be changed once the SPI object is +created. If you need to change the settings afterwards, you'll need +to use the 'close' command and create a new SPI object with the +settings you desire. + +SPIBus API +---------- +### spiBus.transceive(target, data, direction) +* `target` *octet* The number identifying the slave. +* `data` *Buffer* The data to be written to, and returned from, the slave. +* `direction` *string* Writes data buffer using SPI to the slave identified by the target argument, and reads from the slave device into a readBuffer that is returned. The read and write buffers are the same size. -### SPIBus.close - -`void close();` +### spiBus.close() Closes the SPI connection. diff --git a/docs/uart.md b/docs/uart.md index 4a201703c..5d7708f35 100644 --- a/docs/uart.md +++ b/docs/uart.md @@ -3,13 +3,17 @@ Zephyr.js API for UART * [Introduction](#introduction) * [Web IDL](#web-idl) -* [API Documentation](#api-documentation) -* [Sample Apps](#sample-apps) +* [Class UART](#uart-api) + * [uart.init(options)](#uartinitoptions) +* [UARTConnection API](#uartconnection-api) + * [Event: 'read'](#event-read) + * [uartConnection.write(data)](#uartconnectionwritedata) + * [uartConnection.setReadRange(min, max)](#uartconnectionsetreadrangemin-max) Introduction ------------ -The UART module supports both read and write capabilities. Write is achieved -with a 'write' function, and read is done via a callback function property that +The UART module supports both read and write capabilities. Writes are +done through the 'write' function, and reads are done via a callback function property that can be set. Read and write data should be a JavaScript string. The module can be used on both QEMU and the Arduino 101. When using QEMU, you @@ -18,69 +22,59 @@ read/written from the serial console just as print does. Web IDL ------- -This IDL provides an overview of the interface; see below for documentation of -specific API functions. Commented out properties or functions are not -implemented because the feature is not available on Zephyr. - -```javascript -// require returns a UART object -// var uart = require('uart'); - -enum UARTParity { "none", "event", "odd" } - -interface UART { +This IDL provides an overview of the interface; see below for +documentation of specific API functions. We have a short document +explaining [ZJS WebIDL conventions](Notes_on_WebIDL.md). + +
+Click to show WebIDL +
// require returns a UART object
+// var uart = require('uart');

interface UART { UARTConnection init(UARTOptions options); -}; - -dictionary UARTOptions { +};

dictionary UARTOptions { string port; - // number baud = 115200; - // number dataBits = 8; - // number stopBits = 1; + // long baud = 115200; + // long dataBits = 8; + // long stopBits = 1; // UARTParity parity = "none"; // boolean flowControl = false; -}; - -[NoInterfaceObject] +};

[ExternalInterface=(buffer,Buffer)] interface UARTConnection: EventEmitter { // void close(); void write(Buffer data); - void setReadRange(number min, number max); -}; -``` + void setReadRange(long min, long max); +};

enum UARTParity { "none", "event", "odd" } +

+
-API Documentation ------------------ -## UART interface +UART API +-------- +### uart.init(options) +* `options` *UARTOptions* The `UARTOptions` object lets you choose the + UART device/port you would like to initialize. The Arduino 101, for + example, should be "tty0". +* Returns: UARTConnection interface, described below. -### UART.init +UARTConnection API +------------------ -`UARTConnection init(UARTOptions options);` - -The `options` object lets you choose the UART device/port you would like to -initialize. The Arduino 101, for example, should be "tty0". - -## UARTConnection interface -UARTConnection is an [EventEmitter](./events.md) with the following events: +A UARTConnection is an [EventEmitter](./events.md) with the following events: ### Event: 'read' - * `Buffer` `data` Emitted when data is received on the UART RX line. The `data` parameter is a `Buffer` with the received data. -### UARTConnection.write - -`void write(Buffer data);` - -Write data out to the UART TX line. `data` is a string that will be written. +### uartConnection.write(data) +* `data` *Buffer* The data to be written. -### UARTConnection.setReadRange +Write data out to the UART TX line. -`void setReadRange(number min, number max);` +### uartConnection.setReadRange(min, max);` +* `min` *long* The minimum number of bytes for triggering the `onread` event. +* `max` *long* The maximum number of bytes for triggering the `onread` event. -Set the minimum and maximum number of bytes for triggering the `onread` event. Whenever at least the `min` number of bytes is available, a `Buffer` object containing at most `max` number of bytes is sent with the `onread` event. diff --git a/docs/web-socket.md b/docs/web-socket.md index f3fc58cd1..18fb04cd1 100644 --- a/docs/web-socket.md +++ b/docs/web-socket.md @@ -3,47 +3,58 @@ ZJS API for Web Sockets * [Introduction](#introduction) * [Web IDL](#web-idl) -* [API Documentation](#api-documentation) +* [WebSocket API](#websocket-api) + * [ws.Server(options)](#wsserveroptions) +* [WebSocketServer API](#websocketserver-api) + * [Event: 'connection'](#event-connection) +* [WebSocket API](#websocket-api) + * [Event: 'close'](#event-close) + * [Event: 'error'](#event-error) + * [Event: 'message'](#event-message) + * [Event: 'ping'](#event-ping) + * [Event: 'pong'](#event-pong) +* [WebSocketConnection API](#websocketconnection-api) + * [webSocketConnection.send(data, mask)](#websocketconnectionsenddata-mask) + * [webSocketConnection.ping(data, mask)](#websocketconnectionpingdata-mask) + * [webSocketConnection.pong(data, mask)](#websocketconnectionpongdata-mask) * [Sample Apps](#sample-apps) Introduction ------------ The Web Socket API is modeled after Node.js' 'ws' module. This module only -supports the Web Socket server portion of the API. +supports the Web Socket server portion of that API. Web IDL ------- -This IDL provides an overview of the interface; see below for documentation of -specific API functions. - -```javascript -// require returns a WebSocket object -// var ws = require('ws'); - +This IDL provides an overview of the interface; see below for +documentation of specific API functions. We have a short document +explaining [ZJS WebIDL conventions](Notes_on_WebIDL.md). + +
+Click to show WebIDL +
// require returns a WebSocket object
+// var ws = require('ws');

[ReturnFromRequire] interface WebSocket { WebSocketServer Server(Object options); -}; - -interface WebSocketServer: EventEmitter; - +};

interface WebSocketServer: EventEmitter;

[ExternalInterface=(buffer,Buffer)] interface WebSocketConnection: EventEmitter { - // WebSocketConnection methods - void send(Buffer data, Boolean mask); - void ping(Buffer data, Boolean mask); - void pong(Buffer data, Boolean mask); -}; -``` + void send(Buffer data, boolean mask); + void ping(Buffer data, boolean mask); + void pong(Buffer data, boolean mask); +};

+
-WebSocket API Documentation ---------------------------- +WebSocket API +------------- -### WebSocket.Server -`WebSocketServer Server(Object options)` +### ws.Server(options) +* `options` *Object* +* Returns: a WebSocketServer object. Create a Web Socket server object. Options object may contain: -WebSocketServer API Documentation ---------------------------------- +WebSocketServer API +------------------- WebSocketServer is [EventEmitter](./events.md) with the following events: @@ -70,10 +81,10 @@ strings from the handler. Returns a `WebSocketServer` object. -WebSocketConnection API Documentation -------------------------------------- +WebSocket API +------------- -WebSocketServer is [EventEmitter](./events.md) with the following events: +WebSocketServer is an [EventEmitter](./events.md) with the following events: ### Event: 'close' @@ -107,29 +118,27 @@ the `data` argument. Emitted when the socket has received a pong. The pong's payload is contained in the `data` argument. -### WebSocketConnection.send - -`void send(Buffer data, Boolean mask)` -Send data to the other end of the web socket connection. The `data` parameter -should contain the data payload to send. The `mask` parameter says whether the -data payload should be masked. +WebSocketConnection API +----------------------- -### WebSocketConnection.ping +### webSocketConnection.send(data, mask) +* `data` *Buffer* The data payload to send. +* `mask` *boolean* Describes whether the data payload should be masked. -`void ping(Buffer data, Boolean mask)` +Send data to the other end of the web socket connection. -Send a ping to the other end of the web socket connection. The `data` parameter -should contain the data payload to send. The `mask` parameter says whether the -data payload should be masked. +### webSocketConnection.ping(data, mask) +* `data` *Buffer* Contains the data payload to send. +* `mask` *boolean* Describes whether the data payload should be masked. -### WebSocketConnection.pong +Send a ping to the other end of the web socket connection. -`void pong(Buffer data, Boolean mask)` +### webSocketConnection.pong(data, mask) +* `data` *Buffer* The data payload to send. +* `mask` *boolean* Describes whether the data payload should be masked. -Send a pong to the other end of the web socket connection. The `data` parameter -should contain the data payload to send. The `mask` parameter says whether the -data payload should be masked. +Send a pong to the other end of the web socket connection. Sample Apps ----------- From 123533a2a0846d111219fe51ebf850f5765b2485 Mon Sep 17 00:00:00 2001 From: Timothy Harvey Date: Fri, 29 Jun 2018 16:16:31 -0500 Subject: [PATCH 05/18] Modified format and fixed WebIDL --- docs/aio.md | 17 +-- docs/ble.md | 21 ++-- docs/board.md | 8 +- docs/buffer.md | 4 +- docs/console.md | 80 +++++++++---- docs/dgram.md | 103 +++++++++------- docs/events.md | 132 +++++++++------------ docs/fs.md | 3 +- docs/gfx.md | 160 +++++++++++++++---------- docs/grove_lcd.md | 4 +- docs/i2c.md | 4 +- docs/mathstubs.md | 2 +- docs/net-config.md | 2 +- docs/net.md | 235 +++++++++++++++++++----------------- docs/ocf.md | 283 ++++++++++++++++++++------------------------ docs/performance.md | 54 +++++---- docs/pme.md | 232 ++++++++++++++---------------------- docs/pwm.md | 100 ++++++++-------- docs/sensors.md | 98 ++++++--------- docs/timers.md | 114 ++++++++---------- docs/uart.md | 4 +- docs/web-socket.md | 4 +- 22 files changed, 819 insertions(+), 845 deletions(-) diff --git a/docs/aio.md b/docs/aio.md index 4a1e9acc8..3d3cc3ec4 100644 --- a/docs/aio.md +++ b/docs/aio.md @@ -38,25 +38,18 @@ explaining [ZJS WebIDL conventions](Notes_on_WebIDL.md). Click to show WebIDL
 // require returns an AIO object
-// var aio = require('aio');
-
-[ReturnFromRequire]
+// var aio = require('aio');

[ReturnFromRequire] interface AIO { AIOPin open(AIOInit init); -}; - -dictionary AIOInit { +};

dictionary AIOInit { (unsigned long or string) pin; -}; - -interface AIOPin { +};

interface AIOPin { unsigned long read(); void readAsync(ReadCallback callback); // TODO: change to return a promise void on(string eventType, ReadCallback callback); void close(); -}; - -callback ReadCallback = void (unsigned long value);

+};

callback ReadCallback = void (unsigned long value); + AIO API diff --git a/docs/ble.md b/docs/ble.md index 5529ed05d..3e3e2a132 100644 --- a/docs/ble.md +++ b/docs/ble.md @@ -46,26 +46,30 @@ specific API functions. We also have a short document explaining [ZJS WebIDL co // require returns a BLE object // var ble = require('ble');

-[ReturnFromRequire] +[ReturnFromRequire,ExternalInterface=(eventemitter, EventEmitter)] interface BLE: EventEmitter { void disconnect(string address); - void startAdvertising(string name, string[] uuids, string url); + void startAdvertising(string name, sequence < string > uuids, string url); void stopAdvertising(); - void setServices(PrimaryService[] services); + void setServices(sequence < PrimaryService > services); PrimaryService newPrimaryService(PrimaryServiceInit init); Characteristic newCharacteristic(CharacteristicInit init); - Descriptor newDescriptor(DescriptorInit init); + DescriptorInit newDescriptor(DescriptorInit init); };

dictionary PrimaryServiceInit { string uuid; - Characteristic[] characteristics; + sequence < Characteristic > characteristics; +};

+dictionary PrimaryService { + string uuid; + sequence < Characteristic > characteristics; };

dictionary CharacteristicInit { string uuid; - string[] properties; // 'read', 'write', 'notify' - Descriptor[] descriptors; + sequence < string > properties; // 'read', 'write', 'notify' + sequence < DescriptorInit > descriptors; ReadCallback onReadRequest; // optional WriteCallback onWriteRequest; // optional SubscribeCallback onSubscribe; // optional @@ -84,6 +88,7 @@ interface Characteristic {

callback ReadCallback = void (unsigned long offset, FulfillReadCallback fulfillReadCallback); +[ExternalInterface=(buffer,Buffer)] callback WriteCallback = void (Buffer data, unsigned long offset, boolean withoutResponse, FulfillWriteCallback fulfillWriteCallback); @@ -92,6 +97,8 @@ callback SubscribeCallback = void (unsigned long maxValueSize, callback FulfillReadCallback = void (CharacteristicResult result, Buffer data); callback FulfillWriteCallback = void (CharacteristicResult result); callback FulfillSubscribeCallback = void (Buffer data); +callback NotifyCallback = void (any... params); +callback UnsubscribeCallback = void (any... params);

enum CharacteristicResult { "RESULT_SUCCESS", "RESULT_INVALID_OFFSET", "RESULT_INVALID_ATTRIBUTE_LENGTH", "RESULT_UNLIKELY_ERROR" } ; diff --git a/docs/board.md b/docs/board.md index 3ce746b7c..33d88f2db 100644 --- a/docs/board.md +++ b/docs/board.md @@ -24,11 +24,11 @@ documentation of specific API functions. We have a short document explaining [Z

Click to show/hide WebIDL
// require returns the Board API object
 // var board = require('board');
-

-[NoInterfaceObject] +

+[ReturnFromRequire] interface Board { - string name; - string version; + attribute string name5; + attribute string version; };

diff --git a/docs/buffer.md b/docs/buffer.md index da52337b1..56b8b25e3 100644 --- a/docs/buffer.md +++ b/docs/buffer.md @@ -31,7 +31,7 @@ specific API functions. We have a short document explaining [ZJS WebIDL convent
 [ Constructor(sequence < Uint8 > initialValues),
   Constructor(unsigned long size),
-  Constructor(ByteString initialString) ]
+  Constructor(ByteString initialString), ]
 interface Buffer {
     readonly attribute unsigned long length;
     attribute ArrayBuffer buffer;
@@ -48,7 +48,7 @@ interface Buffer {
     long readUInt32LE(optional unsigned long offset = 0);
     string toString(string encoding);
     long write(string value, optional long offset = 0,
-                             optional long length = this.length-offset,
+                             optional long length = 0,
                              optional string encoding = "utf8");
     long writeUInt8(octet value, unsigned long offset);
     long writeUInt16BE(unsigned short value, unsigned long offset);
diff --git a/docs/console.md b/docs/console.md
index a03aebed8..149b08ce9 100644
--- a/docs/console.md
+++ b/docs/console.md
@@ -2,55 +2,83 @@ ZJS API for Console
 ==================
 
 * [Introduction](#introduction)
-* [API Documentation](#api-documentation)
+* [Web IDL](#web-idl)
+* [Class: Console](#console-api)
+  * [console.assert(value, message)](#consoleassertvalue-message)
+  * [console.error(data)](#consoleerrordata)
+  * [console.warn(data)](#consolewarndata)
+  * [console.log(data)](#consolelogdata)
+  * [console.info(data)](#consoleinfodata)
+  * [console.time(label)](#consoletimelabel)
+  * [console.timeEnd(label)](#consoletimeendlabel)
 * [Sample Apps](#sample-apps)
 
 Introduction
 ------------
-ZJS provides console API's which match Node.js' Console module. We describe them here as there could
-potentially be minor differences.
-
-Note that the console API's do not support format specifiers (e.g. %d, %f etc.).
-
-API Documentation
------------------
+ZJS provides console APIs which match Node.js' Console module. We
+describe them here as there could be minor differences.
+
+Note that the console APIs do not support format specifiers (e.g., %d, %f etc.).
+
+Web IDL
+-------
+This IDL provides an overview of the interface; see below for
+documentation of specific API functions.  We have a short document
+explaining [ZJS WebIDL conventions](Notes_on_WebIDL.md).
+
+
+Click to show WebIDL +
+// require returns a Console object
+// var console = require('console');

[ReturnFromRequire] +interface Console { + void assert(boolean value, optional string message); + void error(optional string data); + void log(optional string data); + void info(optional string data); + void time(string label); + void timeEnd(string label); +};

+
+ +Console API +----------- -### assert -`void assert(boolean value, optional string message);` +### console.assert(value, message) +* `value` *boolean* +* `message` *string* Optional message to print. Assert/throw an error if `value` is false. -### error -`void error(optional string data);` +### console.error(data) +* `data` *string* Optional message to print. Prints `data` to `stderr` with newline. (On Zephyr this will just print to stdout). -### warn -`void warn(optional string data);` +### console.warn(data) +* `data` *string* Optional message to print. Alias for `console.error()` -### log -`void log(optional string data);` +### console.log(data) +* `data` *string* Optional message to print. Prints `data` to `stdout` with newline. -### info -`void info(optional string data);` +### console.info(data) +* `data` *string* Optional message to print. Alias for `console.log()`. -### time -`void time(string label);` +### console.time(label) +* `label` *string* This string is used to reference the timer when calling `console.timeEnd()`. -Starts a timer used to compute the duration of an operation. The `label` string is used -to reference the timer when calling `console.timeEnd()`. +Starts a timer used to compute the duration of an operation. -### timeEnd -`void timeEnd(string label);` +### console.timeEnd(label) +* `label` *string* The label identifying the timer started with `console.time()`. -Stops a timer previously started with `console.time()` and prints the resulting time -difference to `stdout`. +Stops a timer previously started with `console.time()` and prints the resulting time difference to `stdout`. Sample Apps ----------- diff --git a/docs/dgram.md b/docs/dgram.md index bfe212721..59e4cf5e2 100644 --- a/docs/dgram.md +++ b/docs/dgram.md @@ -3,8 +3,13 @@ ZJS API for UDP datagram sockets * [Introduction](#introduction) * [Web IDL](#web-idl) -* [API Documentation](#api-documentation) -* [Client Requirements](#requirements) +* [Dgram API](#dgram-api) + * [dgram.createSocket(type)](#dgramcreatesockettype) +* [DgramSocket API](#dgramsocket-api) + * [DgramSocket.on(event, callback)](#dgramsocketonevent-callback) + * [DgramSocket.bind(port, ip_addr)](#dgramsocketbindport-ip_addr) + * [DgramSocket.send(buf, offset, len, port, ip_addr, cb)](#dgramsocketsendbuf-offset-len-port-ip_addr-cb) + * [DgramSocket.close](#dgramsocketclose) * [Sample Apps](#sample-apps) Introduction @@ -16,49 +21,53 @@ It allows you to send and receive UDP datagrams. Web IDL ------- This IDL provides an overview of the interface; see below for documentation of -specific API functions. - -```javascript +specific API functions. We also have a short document explaining [ZJS WebIDL conventions](Notes_on_WebIDL.md). +
+ Click to show/hide WebIDL +
 // require returns a socket factory object
 // var dgram = require('dgram');
-
-[NoInterfaceObject]
-interface dgram {
+

+[ReturnFromRequire] +interface Dgram { DgramSocket createSocket(string udp4_or_udp6); }; - -[NoInterfaceObject] +

+[ExternalInterface=(buffer,Buffer)] interface DgramSocket { void on(string event, RecvCallback cb); - void bind(int port, string ip_addr); - void send(Buffer buf, unsigned long offset, unsigned long len, int port, string ip_addr, [SendCallback cb]); + void bind(long port, string ip_addr); + void send(Buffer buf, unsigned long offset, unsigned long len, long port, + string ip_addr, optional SendCallback cb); void close(); }; - +

callback RecvCallback = void (Buffer msg, RemoteInfo rinfo); callback SendCallback = void (Error err); // or undefined if no error - - -callback EventCallback = void (various); // callback arg depends on event - +

+callback EventCallback = void (any... args); // callback args depend on event +

dictionary RemoteInfo { string ip_addr; string family; - int port; + long port; }; -``` +

+
-API Documentation ------------------ -### dgram.createSocket +Dgram API +--------- +### dgram.createSocket(type) +* `type` *string* Must be `'udp4'` or `'udp6'`. +* Returns: DgramSocket object. -`DgramSocket createSocket(string type);` +Create a datagram socket of the given type. -Create a datagram socket of given type, which must be `'udp4'` or `'udp6'`. - -### DgramSocket.on - -`void on(string event, RecvCallback callback);` +DgramSocket API +--------------- +### DgramSocket.on(event, callback) +* `event` *string* +* `callback` *RecvCallback* Registers a callback. The `event` may be one of the following: @@ -69,35 +78,37 @@ Registers a callback. The `event` may be one of the following: (In the current version, this callback is never called, but this will change in future versions.) -### DgramSocket.bind - -`void bind(int port, string ip_addr);` - -Bind socket to a local address and port. This is required operation for -server-side sockets, i.e. sockets which wait and receive data from other -network nodes. `ip_addr` must be a string representing an IP address of +### DgramSocket.bind(port, ip_addr) +* `port` *long* +* `ip_addr` *string* `ip_addr` A string representing an IP address of a *local* network interface, or a "wildcard" address of `'0.0.0.0'` (IPv4) or `'::'` (IPv6), in which case a socket will be bound to all local -interfaces. This module does not support domain name resolution, so only +interfaces. + +Bind socket to a local address and port. This is a required operation for +server-side sockets, i.e., sockets that wait and receive data from other +network nodes. This module does not support domain name resolution, so only IP addresses are allowed. At the time of writing, local interface addresses are hardcoded to be: `'192.0.2.1'` (IPv4) and `'2001:db8::1'` -(IPv6) (but these will become configurable in the future). - -### DgramSocket.send +(IPv6), but these will become configurable in the future. -`void send(Buffer buf, unsigned long offset, unsigned long len, int port, string ip_addr, [SendCallback cb]);` +### DgramSocket.send(buf, offset, len, port, ip_addr, cb) +* `buf` *Buffer* +* `offset` *unsigned long* +* `len` *unsigned long* +* `port` *long* +* `ip_addr` *string* +* `cb` *SendCallback* Optional. Send data contained in a buffer to remote network node. A subset of data in `buf` can be sent using `offset` and `len` parameters. To send -entire buffer, using values `0` and `buf.length` respectively. See -`bind()` method description for the format of `ip_addr`. An optional +the entire buffer, use values `0` and `buf.length` respectively. See +the `bind()`-method description for the format of `ip_addr`. An optional callback may be provided, which will be called with the result of the send -operation: either NetworkError object in case of error, or `undefined` +operation: either a NetworkError object in the case of error, or `undefined` on success. -### DgramSocket.close - -`void close();` +### DgramSocket.close() Closes socket. diff --git a/docs/events.md b/docs/events.md index 4b8ec6cf5..3e5f82c0b 100644 --- a/docs/events.md +++ b/docs/events.md @@ -3,121 +3,105 @@ ZJS API for Events * [Introduction](#introduction) * [Web IDL](#web-idl) -* [API Documentation](#api-documentation) +* [Class: EventEmitter](#eventemitter-api) + * [EventEmitter.on(event, listener)](#eventemitteronevent-listener) + * [EventEmitter.addListener(event, listener)](#eventemitteraddlistenerevent-listener) + * [EventEmitter.emit(event, args...)](#eventemitteremitevent-args) + * [EventEmitter.removeListener(event, listener)](#eventemitterremovelistenerevent-listener) + * [EventEmitter.removeAllListeners(event)](#eventemitterremovealllistenersevent) + * [EventEmitter.eventNames()](#eventemittereventnames) + * [EventEmitter.getMaxListeners()](#eventemittergetmaxlisteners) + * [EventEmitter.listeners(event)](#eventemitterlistenersevent) + * [EventEmitter.setMaxListeners(max)](#eventemittersetmaxlistenersmax) * [Sample Apps](#sample-apps) Introduction ------------ -ZJS provides event API's which match Node.js Event's. We describe them here as there could -potentially be minor differences. +ZJS provides event APIs that match `Node.js` `Event`s. We describe +them here as there could be minor differences. Web IDL ------- This IDL provides an overview of the interface; see below for documentation of -specific API functions. - -```javascript - -callback ListenerCallback = void (...); - -interface EventEmitter { +specific API functions. We also have a short document explaining [ZJS WebIDL conventions](Notes_on_WebIDL.md). +
+ Click to show/hide WebIDL +
+callback ListenerCallback = void (any... params);

interface EventEmitter { this on(string event, ListenerCallback listener); this addListener(string event, ListenerCallback listener); - boolean emit(string event, optional arg1, ...); + boolean emit(string event, any... args); this removeListener(string event, ListenerCallback listener); this removeAllListeners(string event); - string[] eventNames(void); - number getMaxListeners(void); - ListenerCallback[] listeners(string event); - this setMaxListeners(number max); + sequence < string > eventNames(); + long getMaxListeners(); + sequence < ListenerCallback > listeners(string event); + this setMaxListeners(long max); }; -``` +

+
-API Documentation ------------------ - -### on -`this on(string event, ListenerCallback listener);` +EventEmitter API +---------------- +### EventEmitter.on(event, listener) +* `event` *string* The name of the event that you are adding a listener to. +* `listener` *ListenerCallback* The function that you wish to be called when this event is emitted/triggered. +* Returns: `this` so calls can be chained. Add an event listener function. -The `event` argument is the name of the event which you are adding a listener too. - -The `listener` argument is the function that you wish to be called when this event -is emitted/triggered. +### EventEmitter.addListener(event, listener) +* `event` *string* The name of the event that you are adding a listener to. +* `listener` *ListenerCallback* The function that you wish to be called when this event is emitted/triggered. +* Returns: `this` so calls can be chained. -Returns `this` so calls can be chained. +Same as `EventEmitter.on()`. -### addListener -`this addListener(string event, ListenerCallback listener);` +### EventEmitter.emit(event, args...) +* `event` *string* The name of the event that you want to emit. +* `args` *optional* All other arguments will be given to any registered listener functions. +* Returns: true if there were any listener functions called. -Same as `on()`. +Triggers an event. Any listener functions that have been added to the +event emitter under the event name will be called. -### emit -`boolean emit(string event, optional arg1, ...);` -Triggers an event. Any listener functions which have been added to the event emitter -under the event name will be called. - -The `event` argument is the name of the event that you want to emit. - -All other arguments will be given to any registered listener functions. - -Returns true if there were any listener functions called. - -### removeListener -`this removeListener(string event, ListenerCallback listener);` +### EventEmitter.removeListener(event, listener) +* `event` *string* The name of the event you are removing the listener from. +* `listener` *ListenerCallback* The function you want to remove as a listener. +* Returns: `this` so calls can be chained. Removes a listener function from an event. -The `event` argument is the name of the event you are removing the listener from. - -The `listener` arugment is the actual function you want to remove as a listener. - -Returns `this` so calls can be chained. - -### removeAllListeners -`this removeAllListeners(string event);` +### EventEmitter.removeAllListeners(event) +* `event` *string* The name of the event from which to remove all listeners. +* Returns: `this` so calls can be chained. Removes all listeners from an event -The `event` argument is the name of the event to remove all listeners from - -Returns `this` so calls can be chained -### eventNames -`string[] eventNames(void);` +### EventEmitter.eventNames() +* Returns: an array of strings that correspond to any events. Will return undefined if there are no event's or event listeners for this event emitter. Get a list of event names from an event emitter object. -Returns an array of strings that correspond to any events. Will return undefined -if there are no event's or event listeners for this event emitter. - -### getMaxListeners -`number getMaxListeners(void);` +### EventEmitter.getMaxListeners() +* Returns: the maximum number of listeners allowed. Get the maximum number of listeners allowed for this event emitter object. -Returns the max number of listeners allowed. - -### listeners -`ListenerCallback[] listeners(string event);` +### EventEmitter.listeners(event) +* `event` *string* The name of the event from which to retrieve the listerners. +* Returns: an array of functions that correspond to the `ListenerCallbacks` for the event specified. Get a list of listeners for an event. -The `event` parameter is the name of the event you are retrieving the listerners from. - -Returns an array of functions which correspond to the listeners for the event specified. - -### setMaxListeners -`this setMaxListeners(number max);` +### EventEmitter.setMaxListeners(max) +* `max` *long* The number of listeners the event emitter can have. +* Returns: `this`, so calls can be chained. Set the max number of listeners for an event emitter object -The `max` argument is the number of listeners the event emitter can have - -Returns `this` so calls can be chained. - Sample Apps ----------- * [Events sample](../samples/tests/Events.js) diff --git a/docs/fs.md b/docs/fs.md index 232768f66..1381a60f3 100644 --- a/docs/fs.md +++ b/docs/fs.md @@ -84,7 +84,8 @@ interface FS { void writeFileSync(string file, (string or Buffer) data); };

// file descriptors are inherently platform specific, so we leave this // as a placeholder -definition FileDescriptor { +dictionary FileDescriptor { + //string name; };

interface Stat { boolean isFile(); boolean isDirectory(); diff --git a/docs/gfx.md b/docs/gfx.md index b5812ef53..cac2dc9bc 100644 --- a/docs/gfx.md +++ b/docs/gfx.md @@ -3,118 +3,154 @@ ZJS API for GFX * [Introduction](#introduction) * [Web IDL](#web-idl) -* [API Documentation](#api-documentation) +* [Class: GFX](#gfx-api) + * [gfx.init(screen_width, screen_height, init_screen, draw, this)](#gfxinitscreen_width-screen_height-init_screen-draw-this) +* [Class: GFXContext](#gfxcontext-api) + * [gfxcontext.fillRect(x_coord, y_coord, width, height, color)](#gfxcontextfillrectx_coord-y_coord-width-height-color) + * [gfxcontext.drawPixel(x_coord, y_coord, color)](#gfxcontextdrawpixelx_coord-y_coord-color) + * [gfxcontext.drawLine(x0_coord, y0_coord, x1_coord, y1_coord, color, size)](#gfxcontextdrawlinex0_coord-y0_coord-x1_coord-y1_coord-color-size) + * [gfxcontext.drawVLine(x_coord, y_coord, height, color, size)](#gfxcontextdrawvlinex_coord-y_coord-height-color-size) + * [gfxcontext.drawHLine(x_coord, y_coord, width, color, size)](#gfxcontextdrawhlinex_coord-y_coord-width-color-size) + * [gfxcontext.drawRect(x_coord, y_coord, width, height, color, size)](#gfxcontextdrawrectx_coord-y_coord-width-height-color-size) + * [gfxcontext.drawChar(x_coord, y_coord, char, color, size)](#gfxcontextdrawcharx_coord-y_coord-char-color-size) + * [gfxcontext.drawString(x_coord, y_coord, str, color, size)](#gfxcontextdrawstringx_coord-y_coord-str-color-size) * [Sample Apps](#sample-apps) Introduction ------------ -The GFX module provides a generic way to create pixel buffers, which can then +The GFX module provides a generic way to create pixel buffers that can be displayed on a display of some kind. A JavaScript method for initializing -the screen, and drawing a data buffer are required to use it. +the screen and drawing a data buffer are required to use it. See module/ST7735.js and samples/SPI_Screen.js for an example. Web IDL ------- This IDL provides an overview of the interface; see below for documentation of -specific API functions. - -```javascript +specific API functions. We also have a short document explaining [ZJS WebIDL conventions](Notes_on_WebIDL.md). +

+ Click to show/hide WebIDL +
 // require returns a GFX object
-// var gfx = require('gfx');
-
-[NoInterfaceObject]
+// var gfx = require('gfx');

[ReturnFromRequire] interface GFX { - GFXContext init(screen width, screen height, init screen function, - draw function, optional this); -}; - -[NoInterfaceObject] -interface GFXContext { - fillRect(number x coord, number y coord, number width, number height, - char array color); - drawPixel(number x coord, number y coord, char array color); - drawLine(number x0 coord, number y0 coord, number x1 coord, - number y1 coord, char array color, optional number size); - drawVLine(number x coord, number y coord, number height, char array color, - optional number size); - drawHLine(number x coord, number y coord, number width, char array color, - optional number size); - drawRect(number x coord, number y coord, number width, number height, - char array color, optional number size); - drawChar(number x coord, number y coord, character char, char array color, - optional number size); - drawString(number x coord, number y coord, string str, char array color, - optional number size); + GFXContext init(long screen_width, long screen_height, InitCallback init_screen, + DrawingCallback draw, optional this this_object); +};

interface GFXContext { + void fillRect(long x_coord, long y_coord, long width, long height, + sequence < byte > color); + void drawPixel(long x_coord, long y_coord, sequence < byte > color); + void drawLine(long x0_coord, long y0_coord, long x1_coord, + long y1_coord, sequence < byte > color, optional long size); + void drawVLine(long x_coord, long y_coord, long height, sequence < byte > color, + optional long size); + void drawHLine(long x_coord, long y_coord, long width, sequence < byte > color, + optional long size); + void drawRect(long x_coord, long y_coord, long width, long height, + sequence < byte > color, optional long size); + void drawChar(long x_coord, long y_coord, byte char, sequence < byte > color, + optional long size); + void drawString(long x_coord, long y_coord, string str, sequence < byte > color, + optional long size); }; -``` +callback InitCallback = void (any... params); +callback DrawingCallback = void (any... params); +

+
-API Documentation ------------------ -### GFX.init - -`GFXContext init(screen width, screen height, init screen function, draw function, - optional this);` +GFX API +------- +### gfx.init(screen_width, screen_height, init_screen, draw, this) +* `screen_width` *long* Width of the screen. +* `screen_height` *long* Height of the screen. +* `init_screen` *InitCallback* +* `draw` *DrawingCallback* +* `this` *object* Initializes the GFX module with the screen size, an init function, and a draw callback. A 'this' object can also be provided if needed. -### GFXContext.fillRect - -`void fillRect(number x coord, number y coord, number width, number height, - char array color);` +GFXContext API +-------------- +### gfxcontext.fillRect(x_coord, y_coord, width, height, color) +* `x_coord` *long* +* `y_coord` *long* +* `width` *long* +* `height` *long* +* `color` *byte array* Draws a solid rectangle of the given color at the coordinates provided. -### GFXContext.drawPixel - -`void drawPixel(number x coord, number y coord, char array color);` +### gfxcontext.drawPixel(x_coord, y_coord, color) +* `x_coord` *long* +* `y_coord` *long* +* `color` *byte array* Draws a pixel of the given color at the coordinates provided. -### GFXContext.drawLine +### gfxcontext.drawLine(x0_coord, y0_coord, x1_coord, y1_coord, color, size) +* `x0_coord` *long* +* `y0_coord` *long* +* `x1_coord` *long* +* `y1_coord` *long* +* `color` *byte array* +* `size` *long* Optional. -`void drawLine(number x0 coord, number y0 coord, number x1 coord, - number y1 coord, char array color, optional number size);` Draws a line of the given color at the coordinates provided. The optional size number controls how thick the line is. -### GFXContext.drawVLine +### gfxcontext.drawVLine(x_coord, y_coord, height, color, size) +* `x_coord` *long* +* `y_coord` *long* +* `height` *long* +* `color` *byte array* +* `size` *long* Optional. -`void drawVLine(number x coord, number y coord, number height, char array color, - optional number size);` Draws a vertical line of the given color at the coordinates provided. The optional size number controls how thick the line is. -### GFXContext.drawHLine +### gfxcontext.drawHLine(x_coord, y_coord, width, color, size) +* `x_coord` *long* +* `y_coord` *long* +* `width` *long* +* `color` *byte array* +* `size` *long* Optional. -`void drawHLine(number x coord, number y coord, number width, char array color, - optional number size);` Draws a horizontal line of the given color at the coordinates provided. The optional size number controls how thick the line is. -### GFXContext.drawRect +### gfxcontext.drawRect(x_coord, y_coord, width, height, color, size) +* `x_coord` *long* +* `y_coord` *long* +* `width` *long* +* `height` *long* +* `color` *byte array* +* `size` *long* Optional. -`void drawRect(number x coord, number y coord, number width, number height, - char array color, optional number size);` Draws a hollow rectangle of the given color at the coordinates provided. The optional size number controls how thick the line is. -### GFXContext.drawChar +### gfxcontext.drawChar(x_coord, y_coord, char, color, size) +* `x_coord` *long* +* `y_coord` *long* +* `char` *byte* +* `color` *byte array* +* `size` *long* Optional. -`void drawChar(number x coord, number y coord, character char, char array color, - optional number size);` Draw a character at the coordinates given. The optional size number sets how large the character is. -### GFXContext.drawString +### gfxcontext.drawString(x_coord, y_coord, str, color, size) +* `x_coord` *long* +* `y_coord` *long* +* `str` *string* +* `color` *byte array* +* `size` *long* Optional. -`void drawString(number x coord, number y coord, string str, char array color, - optional number size);` Draw a string at the coordinates given. The optional size number sets how large the character is. diff --git a/docs/grove_lcd.md b/docs/grove_lcd.md index 49be72a3c..f8140a325 100644 --- a/docs/grove_lcd.md +++ b/docs/grove_lcd.md @@ -65,9 +65,9 @@ interface GroveLCD { void selectColor(unsigned long index); void setColor(unsigned long r, unsigned long g, unsigned long b); void setFunction(unsigned long config); - attribute unsigned long getFunction(); + unsigned long getFunction(); void setDisplayState(unsigned long config); - attribute unsigned long getDisplayState(); + unsigned long getDisplayState(); };
diff --git a/docs/i2c.md b/docs/i2c.md index c5c2c4122..6c4a0b209 100644 --- a/docs/i2c.md +++ b/docs/i2c.md @@ -38,7 +38,9 @@ interface I2CBus { void write(octet device, Buffer data); void read(octet device, unsigned long size, octet registerAddress); void burstRead(octet device, unsigned long size, octet registerAddress); -}; +}; +

+typedef I2CBusSpeed long; I2C API diff --git a/docs/mathstubs.md b/docs/mathstubs.md index 515f7e36a..3574c70be 100644 --- a/docs/mathstubs.md +++ b/docs/mathstubs.md @@ -27,7 +27,7 @@ specific API functions. We have a short document explaining [ZJS WebIDL convent

// require returns a MathStubs object
 // var mathStubs = require('mathstubs');

[ReturnFromRequire] interface MathStubs { - double MathStubs.random(); + double random(); };

diff --git a/docs/net-config.md b/docs/net-config.md index da585d0de..98e52c12b 100644 --- a/docs/net-config.md +++ b/docs/net-config.md @@ -29,7 +29,7 @@ specific API functions. We have a short document explaining [ZJS WebIDL convent Click to show/hide WebIDL
 // require returns a Net object
-// var net_cfg = require('netconfig');

[ExternalInterface=(eventemitter, EventEmitter)] +// var net_cfg = require('netconfig');

[ReturnFromRequire,ExternalInterface=(eventemitter, EventEmitter)] interface NetConfig: EventEmitter { boolean setStaticIP(string ip); void dhcp(DHCPCallback callback); diff --git a/docs/net.md b/docs/net.md index 6b046545f..a8673f1ac 100644 --- a/docs/net.md +++ b/docs/net.md @@ -3,120 +3,146 @@ ZJS API for Net * [Introduction](#introduction) * [Web IDL](#web-idl) -* [API Documentation](#api-documentation) + + + + + +* [Class: Net](#net-api) + * [net.createServer(callback onconnection)](#netcreateservercallback-onconnection) + * [net.Socket()](#netsocket) + * [net.isIP(string input)](#netisipstring-input) + * [Net.isIPv4(string input)](#netisipv4string-input) + * [Net.isIPv6(string input)](#netisipv6string-input) +* [Class: Socket](#socket-api) + * [Event: 'close'](#event-close) + * [Event: 'connect'](#event-connect) + * [Event: 'data'](#event-data) + * [Event: 'error'](#event-error) + * [Event: 'timeout'](#event-timeout) + * [Socket.connect(options, onconnect)](#socketconnectoptions-onconnect) + * [Socket.pause()](#socketpause) + * [Socket.resume()](#socketresume) + * [Socket.setTimeout(time, ontimeout)](#socketsettimeouttime-ontimeout) + * [Socket.write(buf, writeDone)](#socketwritebuf-writedone) +* [Class: Server](#server-api) + * [Event: 'close'](#event-close) + * [Event: 'connection'](#event-connection) + * [Event: 'error'](#event-error) + * [Event: 'listening'](#event-listening) + * [Server.address](#serveraddress) + * [Server.close()](#serverclose) + * [Server.getConnections(ListenerCallback onconnection)](#servergetconnectionslistenercallback-onconnection) + * [Server.listen(options, onlistening)](#serverlistenoptions-onlistening) + + + + + * [Sample Apps](#sample-apps) Introduction ------------ -ZJS provides net (TCP) APIs which closely mimic the Node.js 'net' module. This -module allows you to create a TCP/IP server or client. +ZJS provides net (TCP) APIs that closely mimic the Node.js 'net' +module, which allows you to create a TCP/IP server or client. Web IDL ------- This IDL provides an overview of the interface; see below for documentation of -specific API functions. - -```javascript +specific API functions. We also have a short document explaining [ZJS WebIDL conventions](Notes_on_WebIDL.md). +

+ Click to show/hide WebIDL +
 // require returns a Net object
-// var net = require('net');
-
+// var net = require('net');

[ReturnFromRequire] interface Net { - // create a server object - Server createServer(callback onconnection); - // Socket constructor, create a new Socket + Server createServer(optional callback onconnection); Socket Socket(); - Number isIP(input); - Boolean isIPv4(input); - Boolean isIPv6(input); + long isIP(string input); + Boolean isIPv4(string input); + Boolean isIPv6(string input); }; - +

[ExternalInterface=(eventemitter,EventEmitter),ExternalInterface=(buffer,Buffer),ExternalCallback=(eventemitter,ListenerCallback)] interface Socket: EventEmitter { // Socket methods - void connect(Object options, callback onconnect); + void connect(object options, optional ListenerCallback onconnect); void pause(); void resume(); - void setTimeout(Number timeout, callback ontimeout); - void write(Buffer buf, callback writeDone); + void setTimeout(long timeout, ListenerCallback ontimeout); + void write(Buffer buf, optional ListenerCallback writeDone); // Socket properties - Number bufferSize; // Size of read buffer - Number bytesRead; // Total bytes read for the socket - Number bytesWritten; // Total bytes written for the socket - String localAddress; // Sockets local IP - Number localPort; // Sockets local port - String remoteAddress; // Remote IP address - String remoteFamily; // Remote IP family - Number remotePort; // Remote port -}; - + attribute long bufferSize; // Size of read buffer + attribute long bytesRead; // Total bytes read for the socket + attribute long bytesWritten; // Total bytes written for the socket + attribute string localAddress; // Sockets local IP + attribute long localPort; // Sockets local port + attribute string remoteAddress; // Remote IP address + attribute string remoteFamily; // Remote IP family + attribute long remotePort; // Remote port +};

+[ExternalInterface=(eventemitter, EventEmitter),ExternalCallback=(eventemitter,ListenerCallback)] interface Server: EventEmitter { // Server methods AddressInfo address(); void close(); - void getConnections(callback); - void listen(Object options, callback onlistening); + void getConnections(ListenerCallback onconnection); + void listen(object options, optional ListenerCallback onlistening); // Server properties - Boolean listening; // true if the server is listening - Number maxConnections; // maximum number of connections + attribute boolean listening; // true if the server is listening + attribute long maxConnections; // maximum number of connections }; - +

dictionary AddressOptions { - Number port; // Port the client should connect to (required) - String host; // Host the client should connect to - String localAddress; // Local address to bind to - Number localPort; // local port to bind to - Number family; // Version of IP stack, deafults to 4 -} - + long port; // Port the client should connect to (required) + string host; // Host the client should connect to + string localAddress; // Local address to bind to + long localPort; // local port to bind to + long family; // Version of IP stack, deafults to 4 +}; +

dictionary AddressInfo { - Number port; // Server port - String family; // IPv4 or IPv6 - String address; // IP address for the server -} -``` + long port; // Server port + string family; // IPv4 or IPv6 + string address; // IP address for the server +}; +

+
-Net API Documentation ---------------------- +Net API +------- -### Net.createServer -`Server createServer(callback onconnection)` +### net.createServer(callback onconnection) +* `onconnection` *callback* The (optional) callback function registered as the the event listener for the `connection` event. +* Returns: a `Server` object. Create a TCP server that can accept client connections. -`onconnection` is an optional callback function that, if supplied, will be -registered as the the event listener for the `connection` event. - -Returns a `Server` object. +### net.Socket() +* Returns: a new Socket object that can be used to connect to a remote TCP server. -### Net.Socket -`Socket Socket(void)` +Socket constructor. -Socket constructor. Calling `new Socket()` will return a new Socket object -that can be used to connect to a remote TCP server. - -### Net.isIP -`Number isIP(input)` +### net.isIP(string input) +* `input` *string* +* Returns: 4 if the input is an IPv4 address, 6 if the input is an IPv6 address, +or 0 if the input is not an IP address. Checks if the input is a valid IP address. -Returns 4 if the input is an IPv4 address, 6 if the input is an IPv6 address, -or 0 if the input is not an IP address. - -### Net.isIPv4 -`Boolean isIPv4(input)` +### Net.isIPv4(string input) +* `input` *string* +* Returns: true if input is IPv4, false otherwise. Checks if input is an IPv4 address. -Returns true if input is IPv4. - -### Net.isIPv6 -`Boolean isIPv6(input)` +### Net.isIPv6(string input) +* `input` *string* +* Returns: true if input is IPv6, false otherwise. Checks if input is an IPv6 address. -Returns true if input is IPv6. - -Socket API Documentation ------------------------- +Socket API +---------- Socket is an [EventEmitter](./events.md) with the following events: @@ -143,46 +169,37 @@ Emitted when there was an error on the socket during read, write, or connect. Emitted only when a timeout set with `setTimeout` expires. -### Socket.connect -`void connect(AddressOptions options, callback onconnect)` +### Socket.connect(options, onconnect) +* `options` *AddressOptions* Describes the remote server being connected to. +* `onconnect` *ListenerCallback* Optional callback added as the listener for the +`connect` event. Connect to a remote TCP server. -`options` should describe the remote server your connecting to. - -`onconnect` is optional and, if specified, will be added as the listener for the -`connect` event. - -### Socket.pause -`void pause(void)` +### Socket.pause() Pause a socket from receiving data. `data` event will not be emitted until -`resume` is called. +`Socket.resume` is called. -### Socket.resume -`void resume(void)` +### Socket.resume() -Allow a socket to resume receiving data after a call to `pause`. +Allow a socket to resume receiving data after a call to `Socket.pause`. -### Socket.setTimeout -`void setTimeout(Number time, callback ontimeout)` +### Socket.setTimeout(time, ontimeout) +* `time` *long* +* `ontimeout` *ListenerCallback* Optional callback registered as a listener for the `timeout` event. -Set a socket timeout. This will start a timer on the socket which will expire -in `time` milliseconds if there has been no activity on the socket. The -`ontimeout` parameter, if specified, will register a listener for the -`timeout` event. +Set a socket timeout. This will start a timer on the socket that will expire +in `time` milliseconds if there has been no activity on the socket. -### Socket.write -`void write(Buffer buf, callback writeDone)` +### Socket.write(buf, writeDone) +* `buf` *Buffer* `buf` Contains the data to be written. +* `writeDone` *ListenerCallback* Optional function called once the data is written. Send data on the socket. -`buf` should contain the data you wish to send. - -`writeDone` is optional and will be called once the data is written. - -Server API Documentation ------------------------- +Server API +---------- Server is an [EventEmitter](./events.md) with the following events: @@ -212,21 +229,20 @@ Emitted when the server has been bound, after calling `server.listen()`. Returns an AddressInfo object for the server: -### Server.close -`void close(void)` +### Server.close() Signals the server to close. This will stop the server from accepting any new connections but will keep any existing connections alive. Once all existing connections have been closed the server will emit the `close` event. -### Server.getConnections(callback) -`void getConnections(callback)` +### Server.getConnections(ListenerCallback onconnection) +* `onconnection` *ListenerCallback* Should be a function with `err` and `count` parameters. -Get the number of connections to the server. The `callback` parameter should be -a function with `err` and `count` parameters. +Get the number of connections to the server. -### Server.listen -`void listen(Object options, callback onlistening)` +### Server.listen(options, onlistening) +* `options` *object* +* `onlistening` *ListenerCallback* Optional function added to the `listening` event. Start listening for connections. The `options` object supports the following properties: @@ -238,9 +254,6 @@ properties: } ``` -`onlistening` is optional and, if specified, will add a listener to the -`listening` event. - Sample Apps ----------- * [IPv6 Server sample](../samples/TCPEchoServ6.js) diff --git a/docs/ocf.md b/docs/ocf.md index 70c012aad..7ab327f39 100644 --- a/docs/ocf.md +++ b/docs/ocf.md @@ -3,42 +3,53 @@ ZJS API for OCF * [Introduction](#introduction) * [Web IDL](#web-idl) -* [OCF Object](#the-ocf-object) -* [OCF API Documentation](#ocf-api-documentation) -* [OCF Server](#ocf-server) -* [Server API Documentation](#server-api-documentation) -* [Server Samples](#server-samples) -* [OCF Client](#ocf-client) -* [Client API Documentation](#client-api-documentation) -* [Client Samples](#client-samples) +* [Class: OCF](#ocf-api) + * [ocf.start()](#ocfstart) +* [OCFServer-supported Events](#ocfserver-supported-events) +* [Class: OCFServer](#ocfserver-api) + * [server.register(init)](#serverregisterinit) +* [Class: Request](#request-api) + * [request.respond(data)](#requestresponddata) +* [OCFClient-supported Events](#ocfclient-supported-events) +* [Class: OCFClient](#ocfclient-api) + * [client.findResources(options, listener)](#clientfindresourcesoptions-listener) + * [client.retrieve(deviceId, options)](#clientretrievedeviceid-options) + * [client.update(resource)](#clientupdateresource) + * [client.getPlatformInfo(deviceId)](#clientgetplatforminfodeviceid) + * [client.getDeviceInfo(deviceId)](#clientgetdeviceinfodeviceid) +* [OCFServer Samples](#ocfserver-samples) +* [OCFClient Samples](#ocfclient-samples) Introduction ------------ ZJS provides OCF Server API's which allow communication using the OCF networking protocol. -Web IDL -------- -This IDL provides an overview of the interfaces for OCF common, OCF Server and -OCF Client; see below for documentation of specific API functions. - -The OCF Object --------------- The OCF object is the top level object containing either OCF Server, OCF Client, or both, as well as device and platform information. -```javascript +The OCF device and platform objects can be set up after requiring 'ocf'. An +example of this can be found in [OCF Server sample](../samples/OcfServer.js). + +Web IDL +------- +This IDL provides an overview of the interface; see below for +documentation of specific API functions. We have a short document +explaining [ZJS WebIDL conventions](Notes_on_WebIDL.md). + +
+Click to show WebIDL +
 // require returns an OCFObject
 // var ocf = require('ocf');
-
+

[ReturnFromRequire] interface OCFObject { - Server server; // OCF server object - Client client; // OCF client object - Platform platform; // OCF platform info - Device device // OCF device info -}; - -dictionary Platform { + attribute OCFServer server; // OCF server object + attribute OCFClient client; // OCF client object + attribute Platform platform; // OCF platform info + attribute Device device; // OCF device info + void start(); +};

dictionary Platform { string id; string osVersion; string model; @@ -48,40 +59,18 @@ dictionary Platform { string platformVersion; string firmwareVersion; string supportURL; -} - -dictionary Device { +};

dictionary Device { string uuid; string name; string dataModels; string coreSpecVersion; -} - -``` -The OCF device and platform objects can be set up after requiring 'ocf'. An -example of this can be found in [OCF Server sample](../samples/OcfServer.js). -The properties are registered to the system (and available during discovery) -once either `OCFServer.registerResource()` or `OCFClient.findResources()` -is called. - -OCF API Documentation ---------------------- - -### OCFObject.start -`void start(void)` - -Start the OCF stack (iotivity-constrained). This should be called after all -resources have been registered. Any calls to `registerResource` after `start` -will have no effect. - -OCF Server ----------- -```javascript -interface Server: EventEmitter { +};

/////////////////////////////////////////// +// OCF Server +///////////////////////////////////////////

[ExternalInterface=(eventemitter, +EventEmitter)] +interface OCFServer: EventEmitter { Promise register(ResourceInit init); -}; - -dictionary ResourceInit { +};

dictionary ResourceInit { string resourcePath; // OCF resource path string[] resourceTypes; // List of resource types string[] interfaces; // List of interfaces for resource types @@ -90,24 +79,52 @@ dictionary ResourceInit { boolean secure; // Is resource security enabled boolean slow; // Is resource a slow reader object properties; // Dictionary of resource properties -}; - -interface Resource { +};

dictionary Resource { string resourcePath; // Path for this resource object properties; // Application specific resource properties -}; - -interface Request { - OCFResource target; // Target/destination resource - OCFResource source; // Source/origin resource - object data; // resource representation +};

interface Request { + attribute OCFResource target; // Target/destination resource + attribute OCFResource source; // Source/origin resource + attribute object data; // resource representation Promise respond(object data); +};

/////////////////////////////////////////// +// OCF Client +///////////////////////////////////////////

[ExternalInterface=(eventemitter, +EventEmitter)] +interface OCFClient: EventEmitter { + Promise findResources(ClientOptions options, optional FoundListener listener); + Promise retrieve(string deviceId, object options); + Promise update(Resource resource); + Promise getPlatformInfo(string deviceId); + Promise getDeviceInfo(string deviceId); +};

dictionary ClientOptions { + string deviceId; + string resourceType; + string resourcePath; +};

callback FoundListener = void (ClientResource resource); +dictionary ClientResource { + string deviceId; + string resourceType; + string resourcePath; }; -``` +

+
-Server API Documentation ------------------------- -Server is an [EventEmitter](./events.md) with the following events: +OCF API +------- +The properties are registered to the system (and available during discovery) +once either `OCFServer.registerResource()` or `OCFClient.findResources()` +is called. + +### ocf.start() + +Start the OCF stack (iotivity-constrained). This should be called after all +resources have been registered. Any calls to `registerResource` after `start` +will have no effect. + +OCFServer-supported Events +-------------------------- +An OCFServer is an [EventEmitter](./events.md) with the following events: ### Event: 'retrieve' @@ -122,60 +139,28 @@ Emitted when a remote client retrieves this server's resource(s). Emitted when a remote client updates this server's resource(s). -### Server.register -`Promise register(ResourceInit init);` +OCFServer API +-------------- +### server.register(init) +* `init` *ResourceInit* Contains the resource initialization information. +* Returns: a promise which resolves to an `OCFResource`. Register a new resource with the server. -The `init` contains the resource initalization information. - -Returns a promise which resolves to an `OCFResource`. - -### Request.respond -`Promise respond(object data);` - -Respond to an OCF `retrieve` or `update` event. - -The `data` parameter should contain object property data for the resource. In +Request API +----------- +### request.respond(data) +* `data` *object* Should contain object property data for the resource. In the case of an `onretrieve` event, `data` will be sent back to the client as the retrieved property data. +* Returns: a promise which resolves successfully if there was no network error +from sending out the data. -Returns a promise which resolves successfully if there was no network error -sending out the data. - -Server Samples --------------- -* [OCF Server sample](../samples/OcfServer.js) -* [OCF Sensor Server](../samples/OcfSensorServer.js) - -OCF Client ----------- -```javascript -interface Client: EventEmitter { - Promise findResources(ClientOptions options, optional FoundListener listener); - Promise retrieve(string deviceId, object options); - Promise update(Resource resource); - Promise getPlatformInfo(string deviceId); - Promise getDeviceInfo(string deviceId); -}; - -dictionary ClientOptions { - string deviceId; - string resourceType; - string resourcePath; -} - -interface Resource { - string resourcePath; // Path for this resource - object properties; // Application specific resource properties -}; - -callback FoundListener = void (ClientResource); -``` +Respond to an OCF `retrieve` or `update` event. -Client API Documentation ------------------------- -Client is an [EventEmitter](./events.md) with the following events: +OCFClient-supported Events +-------------------------- +An OCFClient is an [EventEmitter](./events.md) with the following events: ### Event: 'devicefound' @@ -201,68 +186,52 @@ Emitted when a resource is found during `findResources()`. Emitted when a resource is updated. -### Client.findResources -`Promise findResources(ClientOptions options, optional FoundListener listener);` - -Find remote resources matching `options` filter. - -The `options` parameter should contain a filter of resource options. Only +OCFClient API +------------- +### client.findResources(options, listener) +* `options` *ClientOptions* Should contain a filter of resource options. Only resources matching these options will be found. - -The `listener` parameter is an optional event listener callback. This +* `listener` *FoundListener* An optional event-listener callback. This callback will be called if a resource is found (`onfound` event). +* Returns: a promise which resolves to a `ClientResource` containing the resource properties if a resource is found. -Returns a promise which resolves with a `ClientResource` object if a resource -was found. - -### Client.retrieve -`Promise retrieve(string deviceId, object options);` - -Retrieve (GET) a remote resource. +Find remote resources matching `options` filter. -The `deviceId` parameter is the device ID of the resource you are retrieving. +### client.retrieve(deviceId, options) +* `deviceId` *string* The device ID of the resource you are retrieving. This ID must match a resource which has been found with `findResources()`. +* `options` *object * Contains flag information for this GET request (e.g., `observable=true`). -The `options` object properties contain flag information for this GET request -e.g. `observable=true`. - -Returns a promise which resolves to a `ClientResource` containing the resource -properties. - -### Client.update -`Promise update(Resource resource);` - -Update remote resource properties. +Retrieve (GET) a remote resource. -The `resource` parameter should contain a `deviceId` for the resource to +### client.update(resource) +* `resource` *Resource* Should contain a `deviceId` for the resource to update. The `properties` parameter will be sent to the resource and updated. - -Returns a promise which resolves to a resource `Resource` containing the +* Returns: a promise which resolves to a resource `Resource` containing the updated properties. -### Client.getPlatformInfo -`Promise getPlatformInfo(string deviceId);` +Update remote resource properties. -Get `Platform` information for a resource. +### client.getPlatformInfo(deviceId) +* `deviceId` *string* The `deviceId` parameter should be the ID for a resource found with `findResources()`. +* Returns: a promise which resolves to a `Platform` containing the platform +information for the resource. -The `deviceId` parameter should be the ID for a resource found with -`findResources()`. +Get `Platform` information for a resource. -Returns a promise which resolves to a `Platform` containing the platform +### client.getDeviceInfo(deviceId) +* `deviceId` *string* The ID for a resource found with `findResources()`. +* Returns: a promise which resolves to a `Device` containing the device information for the resource. -### Client.getDeviceInfo -`Promise getDeviceInfo(string deviceId);` - Get `Device` information for a resource. -The `deviceId` parameter should be the ID for a resource found with -`findResources()`. - -Returns a promise which resolves to a `Device` containing the device -information for the resource. +OCFServer Samples +-------------- +* [OCF Server sample](../samples/OcfServer.js) +* [OCF Sensor Server](../samples/OcfSensorServer.js) -Client Samples +OCFClient Samples -------------- * [OCF Client sample](../samples/OcfClient.js) * [OCF Sensor Client](../samples/OcfSensorClient.js) diff --git a/docs/performance.md b/docs/performance.md index 0981518ae..ac3f5ebbe 100644 --- a/docs/performance.md +++ b/docs/performance.md @@ -3,46 +3,54 @@ ZJS API for Benchmarking * [Introduction](#introduction) * [Web IDL](#web-idl) -* [API Documentation](#api-documentation) +* [Performance API](#performance-api) + * [performance.now()](#performancenow) * [Sample Apps](#sample-apps) Introduction ------------ -"Performance" module implements a subset of "High Resolution Time" specification -from W3C, intended primarily for benchmarking purposes. The key point of this -module is that it is very light-weight by implementing just one function -(unlike for example Date object). + +The "Performance" module implements a subset of the "High Resolution Time" +specification from W3C, intended primarily for benchmarking +purposes. The key point of this module is that it is very light-weight +by implementing just one function (unlike, for example, the Date object). Web IDL ------- -This IDL provides an overview of the interface; see below for documentation of -specific API functions. -```javascript -double now(); -``` +This IDL provides an overview of the interface; see below for documentation of +specific API functions. We also have a short document explaining [ZJS WebIDL conventions](Notes_on_WebIDL.md). +
+ Click to show/hide WebIDL +
+// require returns a Performance object
+// var ble = require('performance');
+

+[ReturnFromRequire] +interface Performance { + double now(); +};

+
-API Documentation ------------------ -### now -`now(); -` +Performance API +--------------- +### performance.now() +* Returns: the current time in milliseconds, as a floating-point number. -The module exposes just one function, `now()`. It returns current time in -milliseconds, as a floating-point number, since an arbitrary point in -time. It is thus not useful as an absolute value, but subtracting values -from two calls will give a time duration between these two calls. +The "time" returned from this function is the offset since an +arbitrary point in time. It is thus not useful as an absolute value, +but subtracting values from two calls will give a time duration +between these two calls. -As the value returned is floating point, it may have higher resolution +As the value returned is a floating point value, it may have higher resolution than a millisecond. However, the actual resolution depends on a platform -and its configuration. For example, default Zephyr configuration for +and its configuration. For example, the default Zephyr configuration for many boards provides resolution of only ones or tens of milliseconds. -The intended usage of this function is for benchmarking and other testing +The intended use of this function is for benchmarking and other testing and development needs. - Examples -------- diff --git a/docs/pme.md b/docs/pme.md index 04bd08a73..c7a3fcf68 100644 --- a/docs/pme.md +++ b/docs/pme.md @@ -3,18 +3,33 @@ ZJS API for Pattern Matching Engine (PME) * [Introduction](#introduction) * [Web IDL](#web-idl) -* [API Documentation](#api-documentation) +* [Class: PME](#pme-api) + * [pme.begin()](#pmebegin) + * [pme.forget()](#pmeforget) + * [pme.configure(context, classificationMode, distanceMode, minInfluence, maxInfluence)](#pmeconfigurecontext-classificationmode-distancemode-mininfluence-maxinfluence) + * [pme.learn(pattern, category)](#pmelearnpattern-category) + * [pme.classify(pattern)](#pmeclassifypattern) + * [pme.readNeuron(id)](#pmereadneuronid) + * [pme.writeVector(pattern)](#pmewritevectorpattern) + * [pme.getCommittedCount()](#pmegetcommittedcount) + * [pme.getGlobalContext()](#pmegetglobalcontext) + * [pme.getClassifierMode()](#pmegetclassifiermode) + * [pme.setClassifierMode(mode)](#pmesetclassifiermodemode) + * [pme.getDistanceMode()](#pmegetdistancemode) + * [pme.setDistanceMode(mode)](#pmesetdistancemodemode) + * [pme.saveNeurons()](#pmesaveneurons) + * [pme.restoreNeurons(objects)](#pmerestoreneuronsobjects) * [Sample Apps](#sample-apps) Introduction ------------ -The Pattern Matching Engine API is the JavaScript version of the parallel data recognition engine with the following features: +The Pattern Matching Engine API is the JavaScript version of the parallel data-recognition engine with the following features: - 128 parallel Processing Elements (PE) each with - 128 byte input vector - 128 byte model memory - 8-Bit Arithmetic Units - - Two distance evaluation norms with 16-bit resolution: + - Two distance-evaluation norms with 16-bit resolution: - L1 norm (Manhattan Distance) - Lsup (Supremum) norm (Chebyshev Distance) - Support for up to 32,768 Categories @@ -30,194 +45,128 @@ The Pattern Matching Engine API is the JavaScript version of the parallel data r Web IDL ------- This IDL provides an overview of the interface; see below for documentation of -specific API functions. - -```javascript +specific API functions. We also have a short document explaining [ZJS WebIDL conventions](Notes_on_WebIDL.md). +
+ Click to show/hide WebIDL +
 // require returns a PME object
-// var pme = require('pme');
-
-[NoInterfaceObject]
+// var pme = require('pme');

[ReturnFromRequire] interface PME { - begin(); - forget(); - configure(unsigned short context, - unsigned short classificationMode, - unsigned short distanceMode, - unsigned short minInfluence, - unsigned short maxInfluence); - learn(number[] pattern, unsigned long category); - unsigned long classify(number[] pattern); + void begin(); + void forget(); + void configure(unsigned short context, + unsigned short classificationMode, + unsigned short distanceMode, + unsigned short minInfluence, + unsigned short maxInfluence); + void learn(sequence < number > pattern, unsigned long category); + unsigned long classify(sequence < number > pattern); Neuron readNeuron(unsigned long id); - writeVector(number[] pattern); + void writeVector(sequence < number > pattern); unsigned short getCommittedCount(); unsigned short getGlobalContext(); unsigned short getClassifierMode(); - setClassifierMode(unsigned short mode); + void setClassifierMode(unsigned short mode); unsigned short getDistanceMode(); - setDistanceMode(unsigned short mode); - Json[] saveNeurons(); - restoreNeurons(Json[] objects); - - unsigned short RBF_MODE; // RBF classification mode - unsigned short KNN_MODE; // KNN classification mode - unsigned short L1_DISTANCE; // L1 distance mode - unsigned short LSUP_DISTANCE; // LSUP distance mode - unsigned long NO_MATCH; // indicate a pattern could not be classified - unsigned short MIN_CONTEXT; // minimum context value - unsigned short MAX_CONTEXT; // maximum context value - unsigned long MAX_VECTOR_SIZE; // Maximum pattern size (in bytes) - unsigned long FIRST_NEURON_ID; // ID of first neuron in network - unsigned long LAST_NEURON_ID; // ID of last neuron in network - unsigned long MAX_NEURONS; // Number of neurons in the network -}; - -[NoInterfaceObject] -interface Neuron { + void setDistanceMode(unsigned short mode); + sequence < Json > saveNeurons(); + restoreNeurons(sequence < Json > objects); +

+ attribute unsigned short RBF_MODE; // RBF classification mode + attribute unsigned short KNN_MODE; // KNN classification mode + attribute unsigned short L1_DISTANCE; // L1 distance mode + attribute unsigned short LSUP_DISTANCE; // LSUP distance mode + attribute unsigned long NO_MATCH; // indicate a pattern could not + // be classified + attribute unsigned short MIN_CONTEXT; // minimum context value + attribute unsigned short MAX_CONTEXT; // maximum context value + attribute unsigned long MAX_VECTOR_SIZE; // Maximum pattern size (in bytes) + attribute unsigned long FIRST_NEURON_ID; // ID of first neuron in network + attribute unsigned long LAST_NEURON_ID; // ID of last neuron in network + attribute unsigned long MAX_NEURONS; // Number of neurons in the network +};

dictionary Neuron { unsigned short category; unsigned short context; unsigned short AIF; unsigned short minIF; }; -``` - -API Documentation ------------------ -### PME.begin +

+
-`void begin();` +PME API +------- +### pme.begin() Initialize the PME so it is ready for operation. -### PME.forget - -`void forget();` +### pme.forget() Clear any data committed to the network, making the network ready to learn again. -### PME.configure - -`configure(unsigned short context, - unsigned short classificationMode, - unsigned short distanceMode, - unsigned short minInfluence, - unsigned short maxInfluence);` +### pme.configure(context, classificationMode, distanceMode, minInfluence, maxInfluence) +* `context` *unsigned short* This value has a range between 1-127. A context value of 0 enables all neurons, with no regard to their context. +* `classificationMode` *unsigned short* The classifying function to use. Valid values are: PME.RBF_MODE (default) or PME.KNN_MODE. +* `distanceMode` *unsigned short* The distance function to use. Valid values are: PME.LSUP_DISTANCE or PME.L1_DISTANCE. +* `minInfluence` *unsigned short* The minimum influence value used on the neuron. +* `maxInfluence` *unsigned short* The maximum influence value used on the neuron. Configure the engine with parameters used for training data. -The `context` is valid context value range between 1-127. A context value of 0 enables all neurons, with no regard to their context. -The `classificationMode` is the classifying function to use. Valid values are: - - - PME.RBF_MODE (default) - - PME.KNN_MODE - -The `distanceMode` is the distance function to use. Valid values are: - - - PME.LSUP_DISTANCE - - PME.L1_DISTANCE - -The `minIF` is the minimum influence value used on the neuron. -The `maxIF` is the maximum influence value used on the neuron. - -### PME.learn - -`void learn(number[] pattern, unsigned long category);` +### pme.learn(pattern, category) +* `pattern` *array of bytes* An array of bytes up to 128 bytes in length. +* `category` *unsigned long* Indicates to the PME to which category this training vector belongs; that is, if a future input has a sufficiently similar pattern, it will be classified as the same category as the passed-in pattern. Takes a pattern and commits it to the network as training data for a given category. -The `pattern` is an array of bytes, up to 128 bytes in length. -The `category` indicates to the PME which category this training vector belongs to, that is, if a future input has a sufficiently similar pattern, it will be classified as the same category passed with this pattern. - -### PME.classify - -`unsigned long classify(number[] pattern);` +### pme.classify(pattern) +* `pattern` *array of bytes* An array of bytes up to 128 bytes in length. +* Returns: `PME.NO_MATCH` if the input data did not match any of the trained categories. Otherwise, the trained category assigned by the network will be returned. Takes a pattern and uses the committed neurons in the network to classify the pattern. -The `pattern` is an array of bytes, up to 128 bytes in length. - -Returns `PME.NO_MATCH` if the input data did not match any of the trained categories. Otherwise, the trained category assigned by the network will be returned. - -### PME.readNeuron - -`Neuron readNeuron(unsigned long id);` +### pme.readNeuron(id) +* `id` *unsigned long* A value between 1-128 representing a specific neuron. +* Returns: the `Neuron` object in which to write the neuron data. Read a specific neuron by its ID. -The `id` is value between 1-128 representing a specific neuron. - -Returns the `Neuron` object in which to write the neuron data. - -### PME.writeVector (KNN_MODE only) - -`void writeVector(number[] pattern);` +### pme.writeVector(pattern) +* `pattern` *array of bytes* An array of bytes up to 128 bytes in length. (Should only be used in KNN_MODE.) Takes a pattern and uses the committed neurons in the network to classify the pattern. -The `pattern` is an array of bytes, up to 128 bytes in length. - -### PME.getCommittedCount - -`unsigned short getCommittedCount();` +### pme.getCommittedCount() +*Returns: the number of comitted neurons in the network (a value between 0-128). Gets the number of committed neurons in the network. -Returns the number of comitted neurons in the network (a value between 0-128). - -### PME.getGlobalContext - -`unsigned short getGlobalContext();` +### pme.getGlobalContext() +* Returns: the contents of the Global Context Register (a value between 0-127). Reads the Global Context Register. -Returns the contents of the Global Context Register (a value between 0-127). - -### PME.getClassifierMode - -`unsigned short getClassifierMode();` +### pme.getClassifierMode() +* Returns: the classifying function being used. Possible values are: PME.RBF_MODE or PME.KNN_MODE. Gets the classifying function being used by the network. -Returns the the classifying function being used. Possible values are: - - - PME.RBF_MODE - - PME.KNN_MODE - -### PME.setClassifierMode - -`void setClassifierMode(unsigned short mode);` +### pme.setClassifierMode(mode) +* `mode` *unsigned short* The classifying function to use. Valid values are: PME.RBF_MODE (default) or PME.KNN_MODE. Sets the classifying function to be used by the network. -The `mode` is the classifying function to use. Valid values are: - - - PME.RBF_MODE (default) - - PME.KNN_MODE - -### PME.getDistanceMode - -`unsigned short getDistanceMode();` +### pme.getDistanceMode() +* Returns: the distance function being used. Possible values are: PME.LSUP_DISTANCE or PME.L1_DISTANCE. Gets the distance function being used by the network. -Returns the the distance function being used. Possible values are: - - - PME.LSUP_DISTANCE - - PME.L1_DISTANCE - -### PME.setDistanceMode - -`void setDistanceMode(unsigned short mode);` +### pme.setDistanceMode(mode) +* `mode` *unsigned short* The distance function to use. Valid values are: PME.LSUP_DISTANCE or PME.L1_DISTANCE. Sets the distance function to be used by the network. -The `mode` is the distance function to use. Valid values are: - - - PME.LSUP_DISTANCE - - PME.L1_DISTANCE - -### PME.saveNeurons - -`Json[] saveNeurons();` +### pme.saveNeurons() +* Returns: an array of JSON objects. Export committed neuron data into an array of JSON objects in the following format, maximum number of objects to save is 128: @@ -229,9 +178,8 @@ Export committed neuron data into an array of JSON objects in the following form "vector": [10,10,10,10] // up to 128 bytes }` -### PME.restoreNeurons - -`void restoreNeurons(Json[] objects);` +### pme.restoreNeurons(objects) +* `objects` *array of JSON objects* Restore neurons in an array of JSON objects in the following format, maximum number of objects to restore is 128: diff --git a/docs/pwm.md b/docs/pwm.md index 50ad5f197..0ce0fd183 100644 --- a/docs/pwm.md +++ b/docs/pwm.md @@ -3,7 +3,11 @@ ZJS API for Pulse Width Modulation (PWM) * [Introduction](#introduction) * [Web IDL](#web-idl) -* [API Documentation](#api-documentation) +* [Class: PWM](#pwm-api) + * [pwm.open(init)](#pwmopeninit) +* [Class: PWMPin](#pwmpin-api) + * [pin.setCycles(period, pulseWidth)](#pinsetcyclesperiod-pulsewidth) + * [pin.setMilliseconds(periodMS, pulseWidthMS)](#pinsetmillisecondsperiodms-pulsewidthms) * [Sample Apps](#sample-apps) Introduction @@ -35,68 +39,69 @@ The PWM API intends to follow the [iot-js-api specification](https://github.com/ Web IDL ------- -This IDL provides an overview of the interface; see below for documentation of -specific API functions. -```javascript +This IDL provides an overview of the interface; see below for documentation of +specific API functions. We also have a short document explaining [ZJS WebIDL conventions](Notes_on_WebIDL.md). +
+ Click to show/hide WebIDL +
 // require returns a PWM object
 // var pwm = require('pwm');
-
-[NoInterfaceObject]
+

+[ReturnFromRequire] interface PWM { - PWMPin open(PWMInit init); -}; - + PWMPin open((long or string or PWMInit) init); +};

dictionary PWMInit { - number or string pin; + (long or string) pin; boolean reversePolarity = false; -}; - -[NoInterfaceObject] +};

interface PWMPin { void setCycles(unsigned long period, unsigned long pulseWidth); void setMilliseconds(double period, double pulseWidth); -}; -``` - -API Documentation ------------------ -### PWM.open +};

+
-`PWMPin open(number or string or PWMInit init);` +PWM API +------- +### pwm.open(init) -If the argument is a number, it is a pin channel number. If it is a string, it -is a pin name. Otherwise, it must be a `PWMInit` object. +* `init` *long of string or PWMInit* A numerical argument indicates +a pin channel number. If the argument is a string, it is a pin +name. Otherwise, it must be a `PWMInit` object. +* Returns: a PWMPin object that can be used to set the period and +pulse width. -The `init` object lets you set the pin channel number with the `pin` property. -You can use a pin name like "PWM_0.2" where "PWM_0" is the name of a Zephyr -pwm controller device for your board and 210 is the pin/channel number. This -will work on any board as long as you find the right values in Zephyr -documentation. But for boards with specific ZJS support, you can use friendly -names. Currently this means Arduino 101 and FRDM-K64F. +The `init` object lets you set the pin channel number with the `pin` +property. You can use a pin name like "PWM_0.2", where "PWM_0" is the +name of a Zephyr pwm controller device for your board and 210 is the +pin/channel number. This will work on any board as long as you find +the right values in the Zephyr documentation. For boards with specific +ZJS support (currently: Arduino 101 and FRDM-K64F), you can use +friendly names. *Arduino 101* -For the A101, you can use numbers 0-3 or strings "PWM0" through "PWM3", or the +For the A101, you can use numbers 0-3, strings "PWM0" through "PWM3", or the corresponding digital pin names "IO3", "IO5", "IO6", and "IO9". *FRDM-K64F* -For the K64F, you can use numbers 0-11 or strings "D3", "D5" through "D13", -"A4" and "A5". +For the K64F, you can use numbers 0-11, strings "D3", "D5" through "D13", +and "A4" and "A5". -The term 'channel' is used to refer to the fact that PWM controller hardware has -multiple channels, but these are connected to output pins so as the user of the -hardware you will think of them as pins. +The term 'channel' refers to multiple channels on the PWM controller +hardware, but these are connected to output pins, so the hardware user +should think of them as pins. The `reversePolarity` value should flip the signal if set to 'reverse', meaning -the signal will be off (low) for the pulseWidth, and back on (high) for the +the signal will be off (low) for the pulseWidth, and on (high) for the rest of the period. -The function returns a PWMPin object that can be used to set the period and -pulse width. +PWMPin API +---------- -### PWMPin.setCycles - -`void setCycles(unsigned long period, unsigned long pulseWidth);` +### pin.setCycles(period, pulseWidth) +* `period` *unsigned long* +* `pulseWidth` *unsigned long* Sets the repeat period and pulse width for the signal, in terms of hardware cycles. One hardware cycle is the minimum amount of time the hardware supports @@ -104,18 +109,19 @@ having the pulse signal on (high). Throws an error if pulseWidth is greater than period. -This version of the API is useful when the duty cycle is what matters (e.g. +This version of the API is useful when the duty cycle is what matters (e.g., using the 'analog' model of PWM control described in the [Introduction](#introduction)). For example, a period of 20 with a pulse width of 10 will make an LED at 50% brightness, with no flicker because the changes occur far faster than visible to the human eye. -### PWMPin.setMilliseconds - -`void setMilliseconds(double periodMS, double pulseWidthMS);` +### pin.setMilliseconds(periodMS, pulseWidthMS) +* `periodMS` *double* Signal repeat period. +* ` pulseWidthMS` *double* Signal pulse width. -Sets the repeat period and pulse width for the signal. It is given in -milliseconds, so these can be fractional to provide microsecond timings, etc. +Sets the repeat period and pulse width for the signal. The values are given in +milliseconds, so these can be fractional to provide microsecond +timings, for example. The actual resolution available will depend on the hardware, so the value you provide may get rounded. *TODO: We could probably have the period attribute show the actual setting for @@ -123,7 +129,7 @@ the device when it is read back.* Throws an error if pulseWidth is greater than period. -This version of the API is useful when the timing of the pulse matters (e.g. +This version of the API is useful when the timing of the pulse matters (e.g., the 'servo' model of PWM control described in the [Introduction](#introduction)). diff --git a/docs/sensors.md b/docs/sensors.md index 2fcb6920f..a77488de2 100644 --- a/docs/sensors.md +++ b/docs/sensors.md @@ -3,30 +3,39 @@ ZJS API for W3C Generic Sensors * [Introduction](#introduction) * [Web IDL](#web-idl) -* [API Documentation](#api-documentation) +* [Class: Sensor](#sensor-api) + * [onreading](#onreading) + * [onactivate](#onactivate) + * [onerror](#onerror) + * [sensor.start()](#sensorstart) + * [sensor.stop()](#sensorstop) * [Sample Apps](#sample-apps) Introduction ------------ ZJS Generic Sensor API implements the W3C Sensor API, and it's intended to provide a consistent API that allows apps to communicate with sensors like -accelerometer and gyroscope. Since the W3C Sensor API is still a draft spec, -our implementation only provide a subset of the API and the API could be -slightly different, but we try to follow the latest spec as closely as +an accelerometer or gyroscope. Since the W3C Sensor API is still a draft spec, +our implementation only provides a subset of the API -- and this API could be +slightly different even though we try to follow the latest spec as closely as possible. -Note: The currently supported hardware is Arduino 101 with its built-in -BMI160 chip with accelerometer, gyroscope, and temperature. The supported -ambient light sensor is the Grove light sensor that comes with the -Grove starter kit, that can be connected using an analog pin. +Note: The currently supported hardware is Arduino 101 that has a +built-in BMI160 chip with accelerometer, gyroscope, and temperature +sensors. The supported ambient light sensor is the Grove light sensor +that comes with the Grove starter kit. The light sensor can be +connected using an analog pin. Web IDL ------- -This IDL provides an overview of the interface; see below for documentation of -specific API functions. -####Sensor Interface -```javascript +This IDL provides an overview of the interface; see below for +documentation of specific API functions. We have a short document +explaining [ZJS WebIDL conventions](Notes_on_WebIDL.md). + +
+Click to show WebIDL +
 interface Sensor {
     readonly attribute boolean activated;   // whether the sensor is activated or not
     readonly attribute boolean hasReading;  // whether the sensor has readings available
@@ -37,73 +46,44 @@ interface Sensor {
     attribute ChangeCallback onreading;     // callback handler for change events
     attribute ActivateCallback onactivate;  // callback handler for activate events
     attribute ErrorCallback onerror;        // callback handler for error events
-};
-
-dictionary SensorOptions {
-    double frequency;  // desire frequency, default is 20 if unset
-};
-
-interface SensorErrorEvent {
+};

dictionary SensorOptions { + double frequency; // desired frequency, default is 20 if unset +};

interface SensorErrorEvent { attribute Error error; -}; - -callback ChangeCallback = void(); +};

callback ChangeCallback = void(); callback ActivateCallback = void(); -callback ErrorCallback = void(SensorErrorEvent error); -``` -####Accelerometer Interface -```javascript -[Constructor(optional AccelerometerOptions accelerometerOptions)] +callback ErrorCallback = void(SensorErrorEvent error);

[Constructor(optional AccelerometerOptions accelerometerOptions)] interface Accelerometer : Sensor { readonly attribute double x; readonly attribute double y; readonly attribute double z; -}; - -dictionary AccelerometerOptions : SensorOptions { +};

dictionary AccelerometerOptions : SensorOptions { string controller; // controller name, default to "bmi160" -}; -``` -####GyroscopeSensor Interface -```javascript -[Constructor(optional SensorOptions sensorOptions)] +};

[Constructor(optional SensorOptions sensorOptions)] interface GyroscopeSensor : Sensor { readonly attribute double x; readonly attribute double y; readonly attribute double z; -}; - +};

dictionary GyroscopeOptions : SensorOptions { string controller; // controller name, default to "bmi160" -}; -``` -####AmbientLightSensor Interface -```javascript +};

[Constructor(optional SensorOptions sensorOptions)] interface AmbientLightSensor : Sensor { readonly attribute unsigned long pin; readonly attribute double illuminance; -}; - -dictionary AmbientLightSensorOptions : SensorOptions { +};

dictionary AmbientLightSensorOptions : SensorOptions { string controller; // controller name, default to "ADC_0" unsigned long pin; // analog pin where the light is connected -}; -``` -####TemperatureSensor Interface -```javascript -[Constructor(optional SensorOptions sensorOptions)] +};

[Constructor(optional SensorOptions sensorOptions)] interface TemperatureSensor : Sensor { readonly attribute double celsius; -}; - -dictionary TemperatureSensorOptions : SensorOptions { +};

dictionary TemperatureSensorOptions : SensorOptions { string controller; // controller name, default to "bmi160" -}; -``` +};

-API Documentation ------------------ +Sensor API +---------- ### onreading `Sensor.onreading` @@ -120,13 +100,11 @@ The onactivate attribute is an EventHandler which is called when the sensor is a The onactivate attribute is an EventHandler which is called whenever an exception cannot be handled synchronously. -### start -`void Sensor.start()` +### sensor.start() Starts the sensor instance, the sensor will get callback on onreading whenever there's a new reading available. -### stop -`void Sensor.stop()` +### sensor.stop() Stop the sensor instance, the sensor will stop reporting new readings. diff --git a/docs/timers.md b/docs/timers.md index 250458153..0bdf32b16 100644 --- a/docs/timers.md +++ b/docs/timers.md @@ -3,7 +3,11 @@ ZJS API for Timers * [Introduction](#introduction) * [Web IDL](#web-idl) -* [API Documentation](#api-documentation) +* [Class: Timers](#timers-api) + * [timers.setInterval(func, delay, args_for_func)](#timerssetintervalfunc-delay-args_for_func) + * [timers.setTimeout(func, delay, args_for_func)](#timerssettimeoutfunc-delay-args_for_func) + * [timers.clearInterval(intervalID)](#timersclearintervalintervalid) + * [timers.clearTimeout(timeoutID)](#timerscleartimeouttimeoutid) * [Sample Apps](#sample-apps) Introduction @@ -13,70 +17,56 @@ available. Web IDL ------- -This IDL provides an overview of the interface; see below for documentation of -specific API functions. - -```javascript -intervalID setInterval(TimerCallback func, unsigned long delay, optional arg1, ...); -timeoutID setTimeout(TimerCallback func, unsigned long delay, optional arg1, ...); -void clearInterval(intervalID); -void clearTimeout(timeoutID); - -callback TimerCallback = void (optional arg1, ...); -``` - -API Documentation ------------------ -### setInterval - -`intervalID setInterval(TimerCallback func, unsigned long delay, optional arg1, ...); -` - -The `func` argument is a callback function that should expect whatever arguments -you pass as arg1, arg2, and so on. - -The `delay` argument is in milliseconds. Currently, the delay resolution is -about 10 milliseconds and if you choose a value less than that it will probably -fail. - -Any additional arguments such as `arg1` will be passed to the callback you -provide. They can be whatever type you wish. - -Every `delay` milliseconds, your callback function will be called. An -`intervalID` will be returned that you can save and pass to clearInterval later -to stop the timer. - -### setTimeout - -`timeoutID setTimeout(TimerCallback func, unsigned long delay, optional arg1, ...);` - -The `func` argument is a callback function that should expect whatever arguments -you pass as arg1, arg2, and so on. - -The `delay` argument is in milliseconds. Currently, the delay resolution is -about 10 milliseconds. - -Any additional arguments such as `arg1` will be passed to the callback you -provide. They can be whatever type you wish. - -After `delay` milliseconds, your callback function will be called *one time*. A -`timeoutID` will be returned that you can save and pass to clearTimeout later -to stop the timer. - -### clearInterval - -`void clearInterval(intervalID);` - -The `intervalID` should be what was returned from a previous call to -`setInterval`. That interval timer will be cleared and its callback function +This IDL provides an overview of the interface; see below for +documentation of specific API functions. We have a short document +explaining [ZJS WebIDL conventions](Notes_on_WebIDL.md). + +
+Click to show WebIDL +
+// require returns a Timers object
+// var timers = require('timers');
+

+[ReturnFromRequire] +interface Timers { + intervalID setInterval(TimerCallback func, unsigned long delay, any... args_for_func); + timeoutID setTimeout(TimerCallback func, unsigned long delay, any... args_for_func); + void clearInterval(long intervalID); + void clearTimeout(long timeoutID); +};

+callback TimerCallback = void (any... callback_args);

+

+typedef timeoutID long; +

+ +Timers API +---------- +### timers.setInterval(func, delay, args_for_func) +* `func` *TimerCallback* A callback function that will take the arguments passed in the variadic `args_for_func` parameter. +* `delay` *unsigned long* The `delay` argument is in milliseconds. Currently, the delay resolution is about 10 milliseconds, and if you choose a value less than that it will probably fail. +* `args_for_func` *any* The user can pass an arbitrary number of additional arguments that will then be passed to `func`. +* Returns: an `intervalID` object that can be passed to `clearInterval` to stop the timer. + +Every `delay` milliseconds, your callback function will be called. + +### timers.setTimeout(func, delay, args_for_func) +* `func` *TimerCallback* A callback function that will take the arguments passed in the variadic `args_for_func` parameter. +* `delay` *unsigned long* The `delay` argument is in milliseconds. Currently, the delay resolution is about 10 milliseconds. +* `args_for_func` *any* The user can pass an arbitrary number of additional arguments that will then be passed to `func`. +* Returns: a `timeoutID` that can be passed to `clearTimeout` to stop the timer. + +After `delay` milliseconds, your callback function will be called *one time*. + +### timers.clearInterval(intervalID) +* `intervalID` *long* This value was returned from a call to `setInterval`. + +That interval timer will be cleared and its callback function no longer called. -### clearTimeout - -`void clearTimeout(timeoutID);` +### timers.clearTimeout(timeoutID) +* `timeoutID` *long* This value was returned from a call to `setTimeout`. -The `timeoutID` should be what was returned from a previous call to -`setTimeout`. That timer will be cleared and its callback function will not be +The `timeoutID` timer will be cleared and its callback function will not be called. Sample Apps diff --git a/docs/uart.md b/docs/uart.md index 5d7708f35..95a24f713 100644 --- a/docs/uart.md +++ b/docs/uart.md @@ -38,12 +38,12 @@ explaining [ZJS WebIDL conventions](Notes_on_WebIDL.md). // long stopBits = 1; // UARTParity parity = "none"; // boolean flowControl = false; -};

[ExternalInterface=(buffer,Buffer)] +};

[ExternalInterface=(buffer,Buffer),ExternalInterface=(eventemitter, EventEmitter)] interface UARTConnection: EventEmitter { // void close(); void write(Buffer data); void setReadRange(long min, long max); -};

enum UARTParity { "none", "event", "odd" } +};

enum UARTParity { "none", "event", "odd" };

diff --git a/docs/web-socket.md b/docs/web-socket.md index 18fb04cd1..849715def 100644 --- a/docs/web-socket.md +++ b/docs/web-socket.md @@ -35,8 +35,8 @@ explaining [ZJS WebIDL conventions](Notes_on_WebIDL.md).
// require returns a WebSocket object
 // var ws = require('ws');

[ReturnFromRequire] interface WebSocket { - WebSocketServer Server(Object options); -};

interface WebSocketServer: EventEmitter;

[ExternalInterface=(buffer,Buffer)] + WebSocketServer Server(object options); +};

[ExternalInterface=(eventemitter, EventEmitter)]interface WebSocketServer: EventEmitter{};

[ExternalInterface=(buffer,Buffer),] interface WebSocketConnection: EventEmitter { void send(Buffer data, boolean mask); void ping(Buffer data, boolean mask); From 48ff0a859ea7c2c5751c09d60decd35be0883fa3 Mon Sep 17 00:00:00 2001 From: Timothy Harvey Date: Fri, 29 Jun 2018 17:18:45 -0500 Subject: [PATCH 06/18] Fixed a problem with too many newlines --- docs/net.md | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/docs/net.md b/docs/net.md index a8673f1ac..05b136345 100644 --- a/docs/net.md +++ b/docs/net.md @@ -3,11 +3,6 @@ ZJS API for Net * [Introduction](#introduction) * [Web IDL](#web-idl) - - - - - * [Class: Net](#net-api) * [net.createServer(callback onconnection)](#netcreateservercallback-onconnection) * [net.Socket()](#netsocket) @@ -34,11 +29,6 @@ ZJS API for Net * [Server.close()](#serverclose) * [Server.getConnections(ListenerCallback onconnection)](#servergetconnectionslistenercallback-onconnection) * [Server.listen(options, onlistening)](#serverlistenoptions-onlistening) - - - - - * [Sample Apps](#sample-apps) Introduction From f601baf5f3645761105c47fb2f79f4cb40d9c561 Mon Sep 17 00:00:00 2001 From: Timothy Harvey Date: Tue, 5 Jun 2018 21:38:18 -0500 Subject: [PATCH 07/18] Modified format and fixed WebIDL Modified format and fixed WebIDL --- docs/aio.md | 26 ++-- docs/ble.md | 49 ++++---- docs/board.md | 35 +++--- docs/buffer.md | 21 ++-- docs/console.md | 80 +++++++++---- docs/dgram.md | 103 +++++++++------- docs/events.md | 132 +++++++++------------ docs/fs.md | 217 +++++++++++++++++---------------- docs/gfx.md | 160 +++++++++++++++---------- docs/gpio.md | 127 ++++++++++---------- docs/grove_lcd.md | 171 +++++++++++++------------- docs/i2c.md | 77 ++++++------ docs/mathstubs.md | 27 +++-- docs/net-config.md | 60 +++++----- docs/net.md | 235 +++++++++++++++++++----------------- docs/ocf.md | 283 ++++++++++++++++++++------------------------ docs/performance.md | 54 +++++---- docs/pme.md | 232 ++++++++++++++---------------------- docs/pwm.md | 100 ++++++++-------- docs/sensors.md | 98 ++++++--------- docs/spi.md | 116 +++++++++--------- docs/timers.md | 114 ++++++++---------- docs/uart.md | 88 +++++++------- docs/web-socket.md | 99 +++++++++------- 24 files changed, 1346 insertions(+), 1358 deletions(-) diff --git a/docs/aio.md b/docs/aio.md index dfd9e919d..3d3cc3ec4 100644 --- a/docs/aio.md +++ b/docs/aio.md @@ -31,30 +31,26 @@ Web IDL ------- This IDL provides an overview of the interface; see below for -documentation of specific API functions. We have a short document explaining [ZJS WebIDL conventions](Notes_on_WebIDL.md). +documentation of specific API functions. We have a short document +explaining [ZJS WebIDL conventions](Notes_on_WebIDL.md). -```javascript +

+Click to show WebIDL +
 // require returns an AIO object
-// var aio = require('aio');
-
-[ReturnFromRequire]
+// var aio = require('aio');

[ReturnFromRequire] interface AIO { AIOPin open(AIOInit init); -}; - -dictionary AIOInit { +};

dictionary AIOInit { (unsigned long or string) pin; -}; - -interface AIOPin { +};

interface AIOPin { unsigned long read(); void readAsync(ReadCallback callback); // TODO: change to return a promise void on(string eventType, ReadCallback callback); void close(); -}; - -callback ReadCallback = void (unsigned long value); -``` +};

callback ReadCallback = void (unsigned long value); +

+
AIO API ------- diff --git a/docs/ble.md b/docs/ble.md index 0092ac732..3e3e2a132 100644 --- a/docs/ble.md +++ b/docs/ble.md @@ -37,41 +37,46 @@ treat them like decimals.* Web IDL ------- + This IDL provides an overview of the interface; see below for documentation of specific API functions. We also have a short document explaining [ZJS WebIDL conventions](Notes_on_WebIDL.md). - - -```javascript +
+ Click to show/hide WebIDL +
 // require returns a BLE object
 // var ble = require('ble');
-
-[ReturnFromRequire]
+

+[ReturnFromRequire,ExternalInterface=(eventemitter, EventEmitter)] interface BLE: EventEmitter { void disconnect(string address); - void startAdvertising(string name, string[] uuids, string url); + void startAdvertising(string name, sequence < string > uuids, string url); void stopAdvertising(); - void setServices(PrimaryService[] services); + void setServices(sequence < PrimaryService > services); PrimaryService newPrimaryService(PrimaryServiceInit init); Characteristic newCharacteristic(CharacteristicInit init); - Descriptor newDescriptor(DescriptorInit init); + DescriptorInit newDescriptor(DescriptorInit init); }; - +

dictionary PrimaryServiceInit { string uuid; - Characteristic[] characteristics; + sequence < Characteristic > characteristics; +};

+dictionary PrimaryService { + string uuid; + sequence < Characteristic > characteristics; }; - +

dictionary CharacteristicInit { string uuid; - string[] properties; // 'read', 'write', 'notify' - Descriptor[] descriptors; + sequence < string > properties; // 'read', 'write', 'notify' + sequence < DescriptorInit > descriptors; ReadCallback onReadRequest; // optional WriteCallback onWriteRequest; // optional SubscribeCallback onSubscribe; // optional UnsubscribeCallback onUnsubscribe; // optional NotifyCallback onNotify; // optional }; - +

interface Characteristic { attribute ReadCallback onReadRequest; attribute WriteCallback onWriteRequest; @@ -80,9 +85,10 @@ interface Characteristic { attribute NotifyCallback onNotify; attribute CharacteristicResult response; }; - +

callback ReadCallback = void (unsigned long offset, FulfillReadCallback fulfillReadCallback); +[ExternalInterface=(buffer,Buffer)] callback WriteCallback = void (Buffer data, unsigned long offset, boolean withoutResponse, FulfillWriteCallback fulfillWriteCallback); @@ -91,14 +97,17 @@ callback SubscribeCallback = void (unsigned long maxValueSize, callback FulfillReadCallback = void (CharacteristicResult result, Buffer data); callback FulfillWriteCallback = void (CharacteristicResult result); callback FulfillSubscribeCallback = void (Buffer data); - -enum CharacteristicResult { "RESULT_SUCCESS", "RESULT_INVALID_OFFSET", "RESULT_INVALID_ATTRIBUTE_LENGTH", "RESULT_UNLIKELY_ERROR" } ; - +callback NotifyCallback = void (any... params); +callback UnsubscribeCallback = void (any... params); +

+enum CharacteristicResult { "RESULT_SUCCESS", "RESULT_INVALID_OFFSET", + "RESULT_INVALID_ATTRIBUTE_LENGTH", "RESULT_UNLIKELY_ERROR" } ; +

dictionary DescriptorInit { string uuid; string value; -}; -``` +};

+
BLE-supported Events -------------------- diff --git a/docs/board.md b/docs/board.md index e4edf85de..33d88f2db 100644 --- a/docs/board.md +++ b/docs/board.md @@ -3,7 +3,9 @@ ZJS Board API * [Introduction](#introduction) * [Web IDL](#web-idl) -* [API Documentation](#api-documentation) +* [Class: Board](#board-api) + * [board.name](#boardname) + * [board.version](#boardversion) * [Sample Apps](#sample-apps) Introduction @@ -15,23 +17,24 @@ but both that and ZJS are under a lot of change at the moment. Web IDL ------- -This IDL provides an overview of the interface; see below for documentation of -specific API functions. -```javascript -// require returns the Board API object +This IDL provides an overview of the interface; see below for +documentation of specific API functions. We have a short document explaining [ZJS WebIDL conventions](Notes_on_WebIDL.md). +
+ Click to show/hide WebIDL +
// require returns the Board API object
 // var board = require('board');
-
-[NoInterfaceObject]
+

+[ReturnFromRequire] interface Board { - string name; - string version; -}; -``` + attribute string name5; + attribute string version; +};

+
-API Documentation +Board API ----------------- -### Board.name +### board.name `string name;` @@ -42,14 +45,14 @@ When code is run under Linux with the jslinux utility, it currently reports a board name of "linux (partially simulating arduino_101)". Any other board will show up with "unknown". Even if the board is unknown, you -can still use the [GPIO API](gpio.md) at least by consulting Zephyr +can still use the [GPIO API](gpio.md) by consulting Zephyr documentation for the board's GPIO port names and pin numbers. -### Board.version +### board.version `string version;` -For now, just returns "0.1". Stay tuned! +Currently, this value is always set to "0.1". Stay tuned! Sample Apps ----------- diff --git a/docs/buffer.md b/docs/buffer.md index 0449e39b3..56b8b25e3 100644 --- a/docs/buffer.md +++ b/docs/buffer.md @@ -4,9 +4,9 @@ ZJS API for Buffer * [Introduction](#introduction) * [Web IDL](#web-idl) * [Class: Buffer](#buffer-api) - * [new Buffer(array)](#new-bufferarray) + * [new Buffer(initialValues)](#new-bufferinitialvalues) * [new Buffer(size)](#new-buffersize) - * [new Buffer(string)](#new-bufferstring) + * [new Buffer(initialString)](#new-bufferinitialstring) * [buf.copy(target[, targetStart, [sourceStart[, sourceEnd]]])](#bufcopytarget-targetstart-sourcestart-sourceend) * [buf.fill(value[, offset[, end[, encoding]]])](#buffillvalue-offset-end-encoding) * [buf.readUInt*(offset)](#bufreaduint-family) @@ -26,12 +26,15 @@ Web IDL This IDL provides an overview of the interface; see below for documentation of specific API functions. We have a short document explaining [ZJS WebIDL conventions](Notes_on_WebIDL.md). -```javascript -[ Constructor(Uint8Array initialValues), +
+ Click to show/hide WebIDL +
+[ Constructor(sequence < Uint8 > initialValues),
   Constructor(unsigned long size),
-  Constructor(ByteString initialString) ]
+  Constructor(ByteString initialString), ]
 interface Buffer {
     readonly attribute unsigned long length;
+    attribute ArrayBuffer buffer;
     unsigned long copy(Buffer target, optional unsigned long targetStart = 0,
                                       optional unsigned long sourceStart = 0,
                                       optional unsigned long sourceEnd);
@@ -45,20 +48,20 @@ interface Buffer {
     long readUInt32LE(optional unsigned long offset = 0);
     string toString(string encoding);
     long write(string value, optional long offset = 0,
-                             optional long length = this.length-offset,
+                             optional long length = 0,
                              optional string encoding = "utf8");
     long writeUInt8(octet value, unsigned long offset);
     long writeUInt16BE(unsigned short value, unsigned long offset);
     long writeUInt16LE(unsigned short value, unsigned long offset);
     long writeUInt32BE(unsigned long value, unsigned long offset);
     long writeUInt32LE(unsigned long value, unsigned long offset);
-};
-```
+};
+
Buffer API ---------- ### new Buffer(initialValues) -* `initialValues` *integer[]* Array of octets to use as initial data. +* `initialValues` *integer-array* of octets to use as initial data. A new Buffer object will be returned with the same size as the array and initialized with the array's contents. If there is not enough diff --git a/docs/console.md b/docs/console.md index a03aebed8..149b08ce9 100644 --- a/docs/console.md +++ b/docs/console.md @@ -2,55 +2,83 @@ ZJS API for Console ================== * [Introduction](#introduction) -* [API Documentation](#api-documentation) +* [Web IDL](#web-idl) +* [Class: Console](#console-api) + * [console.assert(value, message)](#consoleassertvalue-message) + * [console.error(data)](#consoleerrordata) + * [console.warn(data)](#consolewarndata) + * [console.log(data)](#consolelogdata) + * [console.info(data)](#consoleinfodata) + * [console.time(label)](#consoletimelabel) + * [console.timeEnd(label)](#consoletimeendlabel) * [Sample Apps](#sample-apps) Introduction ------------ -ZJS provides console API's which match Node.js' Console module. We describe them here as there could -potentially be minor differences. - -Note that the console API's do not support format specifiers (e.g. %d, %f etc.). - -API Documentation ------------------ +ZJS provides console APIs which match Node.js' Console module. We +describe them here as there could be minor differences. + +Note that the console APIs do not support format specifiers (e.g., %d, %f etc.). + +Web IDL +------- +This IDL provides an overview of the interface; see below for +documentation of specific API functions. We have a short document +explaining [ZJS WebIDL conventions](Notes_on_WebIDL.md). + +
+Click to show WebIDL +
+// require returns a Console object
+// var console = require('console');

[ReturnFromRequire] +interface Console { + void assert(boolean value, optional string message); + void error(optional string data); + void log(optional string data); + void info(optional string data); + void time(string label); + void timeEnd(string label); +};

+
+ +Console API +----------- -### assert -`void assert(boolean value, optional string message);` +### console.assert(value, message) +* `value` *boolean* +* `message` *string* Optional message to print. Assert/throw an error if `value` is false. -### error -`void error(optional string data);` +### console.error(data) +* `data` *string* Optional message to print. Prints `data` to `stderr` with newline. (On Zephyr this will just print to stdout). -### warn -`void warn(optional string data);` +### console.warn(data) +* `data` *string* Optional message to print. Alias for `console.error()` -### log -`void log(optional string data);` +### console.log(data) +* `data` *string* Optional message to print. Prints `data` to `stdout` with newline. -### info -`void info(optional string data);` +### console.info(data) +* `data` *string* Optional message to print. Alias for `console.log()`. -### time -`void time(string label);` +### console.time(label) +* `label` *string* This string is used to reference the timer when calling `console.timeEnd()`. -Starts a timer used to compute the duration of an operation. The `label` string is used -to reference the timer when calling `console.timeEnd()`. +Starts a timer used to compute the duration of an operation. -### timeEnd -`void timeEnd(string label);` +### console.timeEnd(label) +* `label` *string* The label identifying the timer started with `console.time()`. -Stops a timer previously started with `console.time()` and prints the resulting time -difference to `stdout`. +Stops a timer previously started with `console.time()` and prints the resulting time difference to `stdout`. Sample Apps ----------- diff --git a/docs/dgram.md b/docs/dgram.md index bfe212721..59e4cf5e2 100644 --- a/docs/dgram.md +++ b/docs/dgram.md @@ -3,8 +3,13 @@ ZJS API for UDP datagram sockets * [Introduction](#introduction) * [Web IDL](#web-idl) -* [API Documentation](#api-documentation) -* [Client Requirements](#requirements) +* [Dgram API](#dgram-api) + * [dgram.createSocket(type)](#dgramcreatesockettype) +* [DgramSocket API](#dgramsocket-api) + * [DgramSocket.on(event, callback)](#dgramsocketonevent-callback) + * [DgramSocket.bind(port, ip_addr)](#dgramsocketbindport-ip_addr) + * [DgramSocket.send(buf, offset, len, port, ip_addr, cb)](#dgramsocketsendbuf-offset-len-port-ip_addr-cb) + * [DgramSocket.close](#dgramsocketclose) * [Sample Apps](#sample-apps) Introduction @@ -16,49 +21,53 @@ It allows you to send and receive UDP datagrams. Web IDL ------- This IDL provides an overview of the interface; see below for documentation of -specific API functions. - -```javascript +specific API functions. We also have a short document explaining [ZJS WebIDL conventions](Notes_on_WebIDL.md). +
+ Click to show/hide WebIDL +
 // require returns a socket factory object
 // var dgram = require('dgram');
-
-[NoInterfaceObject]
-interface dgram {
+

+[ReturnFromRequire] +interface Dgram { DgramSocket createSocket(string udp4_or_udp6); }; - -[NoInterfaceObject] +

+[ExternalInterface=(buffer,Buffer)] interface DgramSocket { void on(string event, RecvCallback cb); - void bind(int port, string ip_addr); - void send(Buffer buf, unsigned long offset, unsigned long len, int port, string ip_addr, [SendCallback cb]); + void bind(long port, string ip_addr); + void send(Buffer buf, unsigned long offset, unsigned long len, long port, + string ip_addr, optional SendCallback cb); void close(); }; - +

callback RecvCallback = void (Buffer msg, RemoteInfo rinfo); callback SendCallback = void (Error err); // or undefined if no error - - -callback EventCallback = void (various); // callback arg depends on event - +

+callback EventCallback = void (any... args); // callback args depend on event +

dictionary RemoteInfo { string ip_addr; string family; - int port; + long port; }; -``` +

+
-API Documentation ------------------ -### dgram.createSocket +Dgram API +--------- +### dgram.createSocket(type) +* `type` *string* Must be `'udp4'` or `'udp6'`. +* Returns: DgramSocket object. -`DgramSocket createSocket(string type);` +Create a datagram socket of the given type. -Create a datagram socket of given type, which must be `'udp4'` or `'udp6'`. - -### DgramSocket.on - -`void on(string event, RecvCallback callback);` +DgramSocket API +--------------- +### DgramSocket.on(event, callback) +* `event` *string* +* `callback` *RecvCallback* Registers a callback. The `event` may be one of the following: @@ -69,35 +78,37 @@ Registers a callback. The `event` may be one of the following: (In the current version, this callback is never called, but this will change in future versions.) -### DgramSocket.bind - -`void bind(int port, string ip_addr);` - -Bind socket to a local address and port. This is required operation for -server-side sockets, i.e. sockets which wait and receive data from other -network nodes. `ip_addr` must be a string representing an IP address of +### DgramSocket.bind(port, ip_addr) +* `port` *long* +* `ip_addr` *string* `ip_addr` A string representing an IP address of a *local* network interface, or a "wildcard" address of `'0.0.0.0'` (IPv4) or `'::'` (IPv6), in which case a socket will be bound to all local -interfaces. This module does not support domain name resolution, so only +interfaces. + +Bind socket to a local address and port. This is a required operation for +server-side sockets, i.e., sockets that wait and receive data from other +network nodes. This module does not support domain name resolution, so only IP addresses are allowed. At the time of writing, local interface addresses are hardcoded to be: `'192.0.2.1'` (IPv4) and `'2001:db8::1'` -(IPv6) (but these will become configurable in the future). - -### DgramSocket.send +(IPv6), but these will become configurable in the future. -`void send(Buffer buf, unsigned long offset, unsigned long len, int port, string ip_addr, [SendCallback cb]);` +### DgramSocket.send(buf, offset, len, port, ip_addr, cb) +* `buf` *Buffer* +* `offset` *unsigned long* +* `len` *unsigned long* +* `port` *long* +* `ip_addr` *string* +* `cb` *SendCallback* Optional. Send data contained in a buffer to remote network node. A subset of data in `buf` can be sent using `offset` and `len` parameters. To send -entire buffer, using values `0` and `buf.length` respectively. See -`bind()` method description for the format of `ip_addr`. An optional +the entire buffer, use values `0` and `buf.length` respectively. See +the `bind()`-method description for the format of `ip_addr`. An optional callback may be provided, which will be called with the result of the send -operation: either NetworkError object in case of error, or `undefined` +operation: either a NetworkError object in the case of error, or `undefined` on success. -### DgramSocket.close - -`void close();` +### DgramSocket.close() Closes socket. diff --git a/docs/events.md b/docs/events.md index 4b8ec6cf5..3e5f82c0b 100644 --- a/docs/events.md +++ b/docs/events.md @@ -3,121 +3,105 @@ ZJS API for Events * [Introduction](#introduction) * [Web IDL](#web-idl) -* [API Documentation](#api-documentation) +* [Class: EventEmitter](#eventemitter-api) + * [EventEmitter.on(event, listener)](#eventemitteronevent-listener) + * [EventEmitter.addListener(event, listener)](#eventemitteraddlistenerevent-listener) + * [EventEmitter.emit(event, args...)](#eventemitteremitevent-args) + * [EventEmitter.removeListener(event, listener)](#eventemitterremovelistenerevent-listener) + * [EventEmitter.removeAllListeners(event)](#eventemitterremovealllistenersevent) + * [EventEmitter.eventNames()](#eventemittereventnames) + * [EventEmitter.getMaxListeners()](#eventemittergetmaxlisteners) + * [EventEmitter.listeners(event)](#eventemitterlistenersevent) + * [EventEmitter.setMaxListeners(max)](#eventemittersetmaxlistenersmax) * [Sample Apps](#sample-apps) Introduction ------------ -ZJS provides event API's which match Node.js Event's. We describe them here as there could -potentially be minor differences. +ZJS provides event APIs that match `Node.js` `Event`s. We describe +them here as there could be minor differences. Web IDL ------- This IDL provides an overview of the interface; see below for documentation of -specific API functions. - -```javascript - -callback ListenerCallback = void (...); - -interface EventEmitter { +specific API functions. We also have a short document explaining [ZJS WebIDL conventions](Notes_on_WebIDL.md). +
+ Click to show/hide WebIDL +
+callback ListenerCallback = void (any... params);

interface EventEmitter { this on(string event, ListenerCallback listener); this addListener(string event, ListenerCallback listener); - boolean emit(string event, optional arg1, ...); + boolean emit(string event, any... args); this removeListener(string event, ListenerCallback listener); this removeAllListeners(string event); - string[] eventNames(void); - number getMaxListeners(void); - ListenerCallback[] listeners(string event); - this setMaxListeners(number max); + sequence < string > eventNames(); + long getMaxListeners(); + sequence < ListenerCallback > listeners(string event); + this setMaxListeners(long max); }; -``` +

+
-API Documentation ------------------ - -### on -`this on(string event, ListenerCallback listener);` +EventEmitter API +---------------- +### EventEmitter.on(event, listener) +* `event` *string* The name of the event that you are adding a listener to. +* `listener` *ListenerCallback* The function that you wish to be called when this event is emitted/triggered. +* Returns: `this` so calls can be chained. Add an event listener function. -The `event` argument is the name of the event which you are adding a listener too. - -The `listener` argument is the function that you wish to be called when this event -is emitted/triggered. +### EventEmitter.addListener(event, listener) +* `event` *string* The name of the event that you are adding a listener to. +* `listener` *ListenerCallback* The function that you wish to be called when this event is emitted/triggered. +* Returns: `this` so calls can be chained. -Returns `this` so calls can be chained. +Same as `EventEmitter.on()`. -### addListener -`this addListener(string event, ListenerCallback listener);` +### EventEmitter.emit(event, args...) +* `event` *string* The name of the event that you want to emit. +* `args` *optional* All other arguments will be given to any registered listener functions. +* Returns: true if there were any listener functions called. -Same as `on()`. +Triggers an event. Any listener functions that have been added to the +event emitter under the event name will be called. -### emit -`boolean emit(string event, optional arg1, ...);` -Triggers an event. Any listener functions which have been added to the event emitter -under the event name will be called. - -The `event` argument is the name of the event that you want to emit. - -All other arguments will be given to any registered listener functions. - -Returns true if there were any listener functions called. - -### removeListener -`this removeListener(string event, ListenerCallback listener);` +### EventEmitter.removeListener(event, listener) +* `event` *string* The name of the event you are removing the listener from. +* `listener` *ListenerCallback* The function you want to remove as a listener. +* Returns: `this` so calls can be chained. Removes a listener function from an event. -The `event` argument is the name of the event you are removing the listener from. - -The `listener` arugment is the actual function you want to remove as a listener. - -Returns `this` so calls can be chained. - -### removeAllListeners -`this removeAllListeners(string event);` +### EventEmitter.removeAllListeners(event) +* `event` *string* The name of the event from which to remove all listeners. +* Returns: `this` so calls can be chained. Removes all listeners from an event -The `event` argument is the name of the event to remove all listeners from - -Returns `this` so calls can be chained -### eventNames -`string[] eventNames(void);` +### EventEmitter.eventNames() +* Returns: an array of strings that correspond to any events. Will return undefined if there are no event's or event listeners for this event emitter. Get a list of event names from an event emitter object. -Returns an array of strings that correspond to any events. Will return undefined -if there are no event's or event listeners for this event emitter. - -### getMaxListeners -`number getMaxListeners(void);` +### EventEmitter.getMaxListeners() +* Returns: the maximum number of listeners allowed. Get the maximum number of listeners allowed for this event emitter object. -Returns the max number of listeners allowed. - -### listeners -`ListenerCallback[] listeners(string event);` +### EventEmitter.listeners(event) +* `event` *string* The name of the event from which to retrieve the listerners. +* Returns: an array of functions that correspond to the `ListenerCallbacks` for the event specified. Get a list of listeners for an event. -The `event` parameter is the name of the event you are retrieving the listerners from. - -Returns an array of functions which correspond to the listeners for the event specified. - -### setMaxListeners -`this setMaxListeners(number max);` +### EventEmitter.setMaxListeners(max) +* `max` *long* The number of listeners the event emitter can have. +* Returns: `this`, so calls can be chained. Set the max number of listeners for an event emitter object -The `max` argument is the number of listeners the event emitter can have - -Returns `this` so calls can be chained. - Sample Apps ----------- * [Events sample](../samples/tests/Events.js) diff --git a/docs/fs.md b/docs/fs.md index c6a6afb34..1381a60f3 100644 --- a/docs/fs.md +++ b/docs/fs.md @@ -2,21 +2,36 @@ ZJS API for File System ================== * [Introduction](#introduction) -* [API Documentation](#api-documentation) -* [Sample Apps](#sample-apps) +* [Web IDL](#web-idl) +* [Class FS](#fs-api) + * [fs.openSync(path, mode)](#fsopensyncpath-mode) + * [fs.closeSync(fd)](#fsclosesyncfd) + * [fs.unlinkSync(path)](#fsunlinksyncpath) + * [fs.rmdirSync(path)](#fsrmdirsyncpath) + * [fs.writeSync(fd, data, offset, length, position)](#fswritesyncfd-data-offset-length-position) + * [fs.readSync(fd, data, offset, length, position)](#fsreadsyncfd-data-offset-length-position) + * [fs.truncateSync(path, length)](#fstruncatesyncpath-length) + * [fs.mkdirSync(path)](#fsmkdirsyncpath) + * [fs.readdirSync(path)](#fsreaddirsyncpath) + * [fs.statSync(path)](#fsstatsyncpath) + * [writeFileSync(file, data)](#writefilesyncfile-data) +* [Class Stat](#stat-api) + * [stat.isFile()](#statisfile) + * [stat.isDirectory()](#statisdirectory) Introduction ------------ -ZJS provides File System API's which match Node.js' FS module. We describe them -here as there could potentially be minor differences. It should be noted that by -default the FS module only contains the synchronous Node.js API's. The -asynchronous API's can be compiled in by enabling the pre-processor define -`ZJS_FS_ASYNC_APIS`. They are compiled out because all of Zephyr's File -System API's are synchronous, so making the JavaScript API's asynchronous was -only adding ROM space. - -On the Arduino 101 the flash file system uses SPI and the pins are shared with -IO10-13. For this reason you will not be able to use these GPIO pins at the + +ZJS provides File System APIs that match Node.js' FS module. We +describe them here to document any minor differences. It should be +noted that by default, the FS module only contains the synchronous +Node.js APIs. The asynchronous APIs can be compiled in by enabling the +pre-processor value `ZJS_FS_ASYNC_APIS`. The default is to leave them +out, because all of Zephyr's File System APIs are synchronous, so +making the JavaScript APIs asynchronous was only adding ROM space. + +On the Arduino 101, the flash file system uses SPI, and the pins are shared with +IO10-13. For this reason, you will not be able to use these GPIO pins at the same time as the file system. Available file modes: @@ -27,148 +42,142 @@ not exist. `'r+'` - Open a file for reading and writing. An error will be thrown if the file does not exist. -`'w'` - Opens a file for writing. The file will be overwritten if it already +`'w'` - Open a file for writing. The file will be overwritten if it already exists. -`'w+'` - Opens a file for writing and reading. The file will be overwritten if +`'w+'` - Open a file for writing and reading. The file will be overwritten if it already exists. `'a'` - Opens a file for appending. The write pointer will always seek to the end of the file during a write. -`'a+'` - Opens a file for appending and reading. As with `'a'` the write -pointer will seek to the end for writes, but reads can be done from the -start of the file (read pointer saved across different read calls). +`'a+'` - Opens a file for appending and reading. The write +pointer will seek to the end for writes, but reads will be done from the +start of the file (the read pointer is saved across different read calls). Web IDL ------- -This IDL provides an overview of the interface; see below for documentation of -specific API functions. +This IDL provides an overview of the interface; see below for +documentation of specific API functions. We have a short document +explaining [ZJS WebIDL conventions](Notes_on_WebIDL.md). -```javascript +
+Click to show WebIDL +
 // require returns a FS object
 // var fs = require('fs');
-
-interface Stat {
+

+[ReturnFromRequire, ExternalInterface=(buffer,Buffer)] +interface FS { + FileDescriptor openSync(string path, FileMode mode); + void closeSync(FileDescriptor fd); + void unlinkSync(string path); + void rmdirSync(string path); + long writeSync(FileDescriptor fd, (string or Buffer) data, long offset, + long length, optional long position); + long readSync(FileDescriptor fd, Buffer data, long offset, + long length, long position); + void truncateSync(string path, long length); + void mkdirSync(string path); + sequence < string > readdirSync(string path); + Stat statSync(string path); + void writeFileSync(string file, (string or Buffer) data); +};

// file descriptors are inherently platform specific, so we leave this +// as a placeholder +dictionary FileDescriptor { + //string name; +};

interface Stat { boolean isFile(); boolean isDirectory(); -}; -``` +};

enum FileMode { "r", "w", "a", "r+", "w+", "a+" };

+
-API Documentation ------------------ +FS API +------ -### FS.openSync -`object openSync(string path, string mode);` +### fs.openSync(path, mode) +* `path` *string* The name and path of the file to open. +* `mode` *FileMode* The mode in which to open the file. +* Returns: an object representing the file descriptor. Opens a file. -`path` is the name/path of the file to open. - -`mode` is the mode to open the file in (r/w/a/r+/w+/a+). - -Returns an object representing the file descriptor. - -### FS.closeSync -`void closeSync(object fd);` +### fs.closeSync(fd) +* `fd` *FileDescriptor* The file descriptor for the file that will be closed. Closes a file. -`fd` is the descriptor returned from `openSync()`. - -### FS.unlinkSync -`void unlinkSync(string path);` +### fs.unlinkSync(path) +* `path` *string* The name and path of the file to remove. Unlink (remove) a file from the file system. -`path` is the file to remove. - -### FS.rmdirSync -`void rmdirSync(string path);` +### fs.rmdirSync(path) +* `path` *string* The name and path of the directory to be removed. Remove a directory from the file system. -`path` is the name of the directory. - -### FS.writeSync -`number writeSync(object fd, Buffer data, number offset, number length, optional number position);` +### fs.writeSync(fd, data, offset, length, position) +* `fd` *FileDescriptor* The file descriptor returned from `openSync()`. +* `data` *string or Buffer* The data to write to 'fd'. +* `offset` *long* The position in 'data' from which to start writing. +* `length` *long* The number of bytes to write to 'fd' from 'data'. +* `position` *long* The offset from the beginning of the file where + 'data' should be written. The parameter is optional; the default value is 0. +* Returns: the number of bytes actually written (this may be different from 'length'). Write bytes to an opened file. -`fd` is the file descriptor returned from `openSync()`. - -`data` is either a string or buffer to write. - -`offset` is the position in `data` to start writing from. - -`length` is the number of bytes to write from `data`. - -`position` is the offset from the beginning of the file where `data` should be -written. Default is 0. - -Returns the number of bytes actually written (this may be different from `length`). - -### FS.readSync -`number readSync(object fd, buffer data, number offset, number length, number position);` +### fs.readSync(fd, data, offset, length, position) +* `fd` *FileDescriptor* The file descriptor returned from 'openSync()'. +* `data` *Buffer* The buffer into which the data will be read. +* `offset` *long* The offset in 'data' at which to start writing. +* `length` *long* The number of bytes to read. +* `position` *long* The position in the file from which to start reading. +* Returns: the number of bytes actually read. This may be different from +'length' if there was a read error or if the file had no more data left to read. Read bytes from a file. -`fd` is the file descriptor returned from `openSync()`. - -`data` is a buffer where the data will be read into. - -`offset` is the offset in `data` to start writing at. - -`length` is the number of bytes to read. - -`position` is the position in the file to start reading from. - -Returns the number of bytes actually read. This may be different from `length` -if there was a read error or if the file had no more data left to read. - -### FS.truncateSync -`void truncateSync(string path, number length);` +### fs.truncateSync(path, length) +* `path` *string* The name and path of the file. +* `length` *long* The new length of the file. Truncate a file. If the length passed in is shorter than the existing file -length then the trailing file data will be lost. - -`path` is the name of the file. +length, then the trailing file data will be lost. -`length` is the new length of the file. +### fs.mkdirSync(path) +* `path` *string* The name and path of the directory. -### FS.mkdirSync -`void mkdirSync(string path)` +Create a directory. There is no effect if the directory already exists. -Create a directory. If the directory already exists there is no effect. - -`path` is the name of the directory. - -### FS.readdirSync -`string[] readdirSync(string path);` +### fs.readdirSync(path) +* `path` *string* The name and path of the directory to read. +* Returns: an array of filenames and directories found in 'path'. Read the contents of a directory. -`path` directory path to read. - -Returns an array of filenames and directories found in `path`. - -### FS.statSync -`Stat statSync(string path);` +### fs.statSync(path) +* `path` *string* The name and path of the file or directory. +* Returns: a 'Stat' object for the file or directory or undefined if the +file or directory does not exist. Get stats about a file or directory. -`path` name of file or directory. - -Returns a `Stat` object for that file or directory or undefined if file or directory does not exist. - -### FS.writeFileSync -`void writeFileSync(string file, [string|buffer] data);` +### writeFileSync(file, data) +* `file` *string* The name of the file to which to write. +* `data` *string or Buffer* The data to write into the file. Open and write data to a file. This will replace the file if it already exists. -`file` is the name of the file to write to. +Stat API +-------- + +### stat.isFile() +* Returns: true if the file descriptor is a file. -`data` is the bytes to write into the file. +### stat.isDirectory() +* Returns: true if the file descriptor is a directory. Sample Apps ----------- diff --git a/docs/gfx.md b/docs/gfx.md index b5812ef53..cac2dc9bc 100644 --- a/docs/gfx.md +++ b/docs/gfx.md @@ -3,118 +3,154 @@ ZJS API for GFX * [Introduction](#introduction) * [Web IDL](#web-idl) -* [API Documentation](#api-documentation) +* [Class: GFX](#gfx-api) + * [gfx.init(screen_width, screen_height, init_screen, draw, this)](#gfxinitscreen_width-screen_height-init_screen-draw-this) +* [Class: GFXContext](#gfxcontext-api) + * [gfxcontext.fillRect(x_coord, y_coord, width, height, color)](#gfxcontextfillrectx_coord-y_coord-width-height-color) + * [gfxcontext.drawPixel(x_coord, y_coord, color)](#gfxcontextdrawpixelx_coord-y_coord-color) + * [gfxcontext.drawLine(x0_coord, y0_coord, x1_coord, y1_coord, color, size)](#gfxcontextdrawlinex0_coord-y0_coord-x1_coord-y1_coord-color-size) + * [gfxcontext.drawVLine(x_coord, y_coord, height, color, size)](#gfxcontextdrawvlinex_coord-y_coord-height-color-size) + * [gfxcontext.drawHLine(x_coord, y_coord, width, color, size)](#gfxcontextdrawhlinex_coord-y_coord-width-color-size) + * [gfxcontext.drawRect(x_coord, y_coord, width, height, color, size)](#gfxcontextdrawrectx_coord-y_coord-width-height-color-size) + * [gfxcontext.drawChar(x_coord, y_coord, char, color, size)](#gfxcontextdrawcharx_coord-y_coord-char-color-size) + * [gfxcontext.drawString(x_coord, y_coord, str, color, size)](#gfxcontextdrawstringx_coord-y_coord-str-color-size) * [Sample Apps](#sample-apps) Introduction ------------ -The GFX module provides a generic way to create pixel buffers, which can then +The GFX module provides a generic way to create pixel buffers that can be displayed on a display of some kind. A JavaScript method for initializing -the screen, and drawing a data buffer are required to use it. +the screen and drawing a data buffer are required to use it. See module/ST7735.js and samples/SPI_Screen.js for an example. Web IDL ------- This IDL provides an overview of the interface; see below for documentation of -specific API functions. - -```javascript +specific API functions. We also have a short document explaining [ZJS WebIDL conventions](Notes_on_WebIDL.md). +
+ Click to show/hide WebIDL +
 // require returns a GFX object
-// var gfx = require('gfx');
-
-[NoInterfaceObject]
+// var gfx = require('gfx');

[ReturnFromRequire] interface GFX { - GFXContext init(screen width, screen height, init screen function, - draw function, optional this); -}; - -[NoInterfaceObject] -interface GFXContext { - fillRect(number x coord, number y coord, number width, number height, - char array color); - drawPixel(number x coord, number y coord, char array color); - drawLine(number x0 coord, number y0 coord, number x1 coord, - number y1 coord, char array color, optional number size); - drawVLine(number x coord, number y coord, number height, char array color, - optional number size); - drawHLine(number x coord, number y coord, number width, char array color, - optional number size); - drawRect(number x coord, number y coord, number width, number height, - char array color, optional number size); - drawChar(number x coord, number y coord, character char, char array color, - optional number size); - drawString(number x coord, number y coord, string str, char array color, - optional number size); + GFXContext init(long screen_width, long screen_height, InitCallback init_screen, + DrawingCallback draw, optional this this_object); +};

interface GFXContext { + void fillRect(long x_coord, long y_coord, long width, long height, + sequence < byte > color); + void drawPixel(long x_coord, long y_coord, sequence < byte > color); + void drawLine(long x0_coord, long y0_coord, long x1_coord, + long y1_coord, sequence < byte > color, optional long size); + void drawVLine(long x_coord, long y_coord, long height, sequence < byte > color, + optional long size); + void drawHLine(long x_coord, long y_coord, long width, sequence < byte > color, + optional long size); + void drawRect(long x_coord, long y_coord, long width, long height, + sequence < byte > color, optional long size); + void drawChar(long x_coord, long y_coord, byte char, sequence < byte > color, + optional long size); + void drawString(long x_coord, long y_coord, string str, sequence < byte > color, + optional long size); }; -``` +callback InitCallback = void (any... params); +callback DrawingCallback = void (any... params); +

+
-API Documentation ------------------ -### GFX.init - -`GFXContext init(screen width, screen height, init screen function, draw function, - optional this);` +GFX API +------- +### gfx.init(screen_width, screen_height, init_screen, draw, this) +* `screen_width` *long* Width of the screen. +* `screen_height` *long* Height of the screen. +* `init_screen` *InitCallback* +* `draw` *DrawingCallback* +* `this` *object* Initializes the GFX module with the screen size, an init function, and a draw callback. A 'this' object can also be provided if needed. -### GFXContext.fillRect - -`void fillRect(number x coord, number y coord, number width, number height, - char array color);` +GFXContext API +-------------- +### gfxcontext.fillRect(x_coord, y_coord, width, height, color) +* `x_coord` *long* +* `y_coord` *long* +* `width` *long* +* `height` *long* +* `color` *byte array* Draws a solid rectangle of the given color at the coordinates provided. -### GFXContext.drawPixel - -`void drawPixel(number x coord, number y coord, char array color);` +### gfxcontext.drawPixel(x_coord, y_coord, color) +* `x_coord` *long* +* `y_coord` *long* +* `color` *byte array* Draws a pixel of the given color at the coordinates provided. -### GFXContext.drawLine +### gfxcontext.drawLine(x0_coord, y0_coord, x1_coord, y1_coord, color, size) +* `x0_coord` *long* +* `y0_coord` *long* +* `x1_coord` *long* +* `y1_coord` *long* +* `color` *byte array* +* `size` *long* Optional. -`void drawLine(number x0 coord, number y0 coord, number x1 coord, - number y1 coord, char array color, optional number size);` Draws a line of the given color at the coordinates provided. The optional size number controls how thick the line is. -### GFXContext.drawVLine +### gfxcontext.drawVLine(x_coord, y_coord, height, color, size) +* `x_coord` *long* +* `y_coord` *long* +* `height` *long* +* `color` *byte array* +* `size` *long* Optional. -`void drawVLine(number x coord, number y coord, number height, char array color, - optional number size);` Draws a vertical line of the given color at the coordinates provided. The optional size number controls how thick the line is. -### GFXContext.drawHLine +### gfxcontext.drawHLine(x_coord, y_coord, width, color, size) +* `x_coord` *long* +* `y_coord` *long* +* `width` *long* +* `color` *byte array* +* `size` *long* Optional. -`void drawHLine(number x coord, number y coord, number width, char array color, - optional number size);` Draws a horizontal line of the given color at the coordinates provided. The optional size number controls how thick the line is. -### GFXContext.drawRect +### gfxcontext.drawRect(x_coord, y_coord, width, height, color, size) +* `x_coord` *long* +* `y_coord` *long* +* `width` *long* +* `height` *long* +* `color` *byte array* +* `size` *long* Optional. -`void drawRect(number x coord, number y coord, number width, number height, - char array color, optional number size);` Draws a hollow rectangle of the given color at the coordinates provided. The optional size number controls how thick the line is. -### GFXContext.drawChar +### gfxcontext.drawChar(x_coord, y_coord, char, color, size) +* `x_coord` *long* +* `y_coord` *long* +* `char` *byte* +* `color` *byte array* +* `size` *long* Optional. -`void drawChar(number x coord, number y coord, character char, char array color, - optional number size);` Draw a character at the coordinates given. The optional size number sets how large the character is. -### GFXContext.drawString +### gfxcontext.drawString(x_coord, y_coord, str, color, size) +* `x_coord` *long* +* `y_coord` *long* +* `str` *string* +* `color` *byte array* +* `size` *long* Optional. -`void drawString(number x coord, number y coord, string str, char array color, - optional number size);` Draw a string at the coordinates given. The optional size number sets how large the character is. diff --git a/docs/gpio.md b/docs/gpio.md index 19277a89a..e9f12b94d 100644 --- a/docs/gpio.md +++ b/docs/gpio.md @@ -3,7 +3,13 @@ ZJS API for General Purpose I/O (GPIO) * [Introduction](#introduction) * [Web IDL](#web-idl) -* [API Documentation](#api-documentation) +* [Class GPIO](#gpio-api) + * [GPIO.open(init)](#gpioopeninit) +* [Class GPIOPin](#gpiopin-api) + * [pin.read()](#pinread) + * [pin.write()](#pinwritevalue) + * [pin.close()](#pinclose) + * [pin.onchange](#pinonchange) * [Sample Apps](#sample-apps) Introduction @@ -17,108 +23,95 @@ but both that and ZJS are under a lot of change at the moment. Web IDL ------- This IDL provides an overview of the interface; see below for documentation of -specific API functions. +specific API functions. We have a short document explaining [ZJS WebIDL conventions](Notes_on_WebIDL.md). -```javascript +
+ Click to show/hide WebIDL +
 // require returns a GPIO object
-// var gpio = require('gpio');
-
-[NoInterfaceObject]
+// var gpio = require('gpio');

+[ReturnFromRequire] interface GPIO { - GPIOPin open(number or string or GPIOInit init); -}; - -dictionary GPIOInit { - number or string pin; + GPIOPin open( (long or string or GPIOInit) init); +};

dictionary GPIOInit { + (long or string) pin; boolean activeLow = false; - string mode = "out"; // in, out - string edge = "none"; // none, rising, falling, any - string state = "none"; // none, up, down -}; - -[NoInterfaceObject] -interface GPIOPin { - number read(); - void write(number value); + GPIOMode mode = "out"; + GPIOEdge edge = "none"; + GPIOState state = "none"; +};

interface GPIOPin { + long read(); + void write(long value); void close(); attribute ChangeCallback onchange; -}; - -callback ChangeCallback = void (GPIOEvent); - -dictionary GPIOEvent { - number value; -} -``` - -API Documentation ------------------ -### GPIO.open - -`GPIOPin open(number or string or GPIOInit init);` - -If the argument is a number, it is a pin number. If it is a string, it is a -pin name. Otherwise, it must be a GPIOInit object. - -The `init` object lets you set the pin number or name with the `pin` property. +};

callback ChangeCallback = void (GPIOEvent event);

dictionary GPIOEvent { + long value; +};

enum GPIOMode { "out", "in" }; +enum GPIOEdge { "none", "rising", "falling", "any" }; +enum GPIOState { "none", "up", "down" };

+
+ +GPIO API +-------- +### gpio.open(init) +* `init` *long or string or GPIOInit* If the argument is a number, it is a pin number. If it is a +string, it is a pin name. Otherwise, it must be a GPIOInit object. +* Returns: a GPIOPin object that can be used to read or write the pin. If the pin number or name is valid for the given board, the call will succeed. You can use a pin name like "GPIO_0.10" where "GPIO_0" is the name of a Zephyr gpio port device for your board and 10 is the pin number. This will work on any board as long as you find the right values in Zephyr documentation. But for -boards with specific ZJS support, you can use friendly names. Currently this +boards with specific ZJS support, you can use friendly names. Currently, this means Arduino 101 and FRDM-K64F. For the A101, you can use numbers 0-13 or strings "IO0" through "IO13", as well as "LED0" through "LED2". For K64F, you can use numbers 0-15 or strings "D0" through "D15", as well as "LEDR", "LEDG", and "LEDB" for the RGB LED, and "SW2" and "SW3" for onboard switches. -The other values are optional. The `activeLow` setting determines whether -high (default) or low means active. When you read or write a boolean value, -true means 'active' and false means 'inactive'. +The GPIOInit object can take a string or number as the pin argument, +and all of the rest of the fields are optional. The `activeLow` +setting determines whether high (default) or low means active. When +you read or write a boolean value, true means 'active' and false means +'inactive'. The `mode` value determines whether the pin is an input ('in') or output -('out', default). +('out'). The `edge` value is for input pins and tells whether the `onchange` callback will be called on the rising edge of the signal, falling edge, or both. -The `state` value is to enable an internal pullup or pulldown resistor. This -would be used for inputs to provide a default (high or low) when the input is -floating (not being intentionally driven to a particular value). +The `state` value is useful when the architecture has an internal +pullup or pulldown resistor. This would be used for inputs to provide +a default (high or low) when the input is floating (not being +intentionally driven to a particular value). *NOTE: When we last checked, Zephyr did not use this state setting, at least for -Arduino 101. Perhaps there is no hardware support, but in any case it didn't +Arduino 101. Perhaps there is no hardware support, but in any case, it didn't work. You can always provide an external resistor for this purpose instead.* -The function returns a GPIOPin object that can be used to read or write the pin. - -### GPIOPin.read - -`number read();` +GPIOPin API +----------- +### pin.read() +* Returns: the current reading from the pin. -Returns the current reading from the pin. This is a synchronous function because -it should be nearly instantaneous on the devices we've tested with so far. The -value will be 1 if the pin is active (high by default, low for a pin configured +This is a synchronous function, because it is nearly +instantaneous on the devices we've tested with so far. The value will +be 1 if the pin is active (high by default, low for a pin configured active low), 0 if inactive. -### GPIOPin.write - -`void write(number value);` - -Pass 1 for `value` to make an output pin active (high by default, low for a pin -configured active low), 0 to make it inactive. - -### GPIOPin.close +### pin.write(value) +* `value` *long* Pass 1 for `value` to make an output pin active +(high by default, low for a pin configured active low), 0 to make it inactive. -`void close();` +### pin.close() Free up resources associated with the pin. The onchange function for this pin will no longer be called, and the object should not be used for reading and writing anymore. -### GPIOPin.onchange +### pin.onchange -`attribute ChangeCallback onchange;` +* `onchange` *ChangeCallback* Set this attribute to a function that will receive events whenever the pin changes according to the edge condition specified at pin initialization. The diff --git a/docs/grove_lcd.md b/docs/grove_lcd.md index 24e489d32..f8140a325 100644 --- a/docs/grove_lcd.md +++ b/docs/grove_lcd.md @@ -3,53 +3,62 @@ ZJS API for Grove LCD * [Introduction](#introduction) * [Web IDL](#web-idl) -* [API Documentation](#api-documentation) +* [GroveLCD API](#grovelcd-api) + * [grove_lcd.init()](#grove_lcdinit) +* [GroveLCDDevice API](#grovelcddevice-api) + * [groveLCDDevice.print(string text)](#grovelcddeviceprinttext) + * [groveLCDDevice.clear()](#grovelcddeviceclear) + * [groveLCDDevice.setCursorPos(col, row)](#grovelcddevicesetcursorposcol-row) + * [groveLCDDevice.selectColor(index)](#grovelcddeviceselectcolorindex) + * [groveLCDDevice.setColor(r, g, b)](#grovelcddevicesetcolorr-g-b) + * [groveLCDDevice.setFunction(config)](#grovelcddevicesetfunctionconfig) + * [groveLCDDevice.getFunction()](#grovelcddevicegetfunction) + * [groveLCDDevice.setDisplayState(config)](#grovelcddevicesetdisplaystateconfig) + * [GroveLCDDevice.getDisplayState()](#grovelcddevicegetdisplaystate) + * [Sample Apps](#sample-apps) Introduction ------------ The Grove LCD API is the JavaScript version of the Zephyr API that supports the Grove LCD. It works over I2C to allow user to send text to the LCD screen -and also configure LCD to different RGB backlight colors. +and also configure the LCD to different RGB backlight colors. Web IDL ------- -This IDL provides an overview of the interface; see below for documentation of -specific API functions. - -```javascript -// require returns a GroveLCD object -// var grove_lcd = require('grove_lcd'); - -[NoInterfaceObject] +This IDL provides an overview of the interface; see below for +documentation of specific API functions. We have a short document +explaining [ZJS WebIDL conventions](Notes_on_WebIDL.md). + +
+Click to show WebIDL +
// require returns a GroveLCD object
+// var grove_lcd = require('grove_lcd');

[ReturnFromRequire] interface GroveLCD { GroveLCDDevice init(); - unsigned long GLCD_FS_8BIT_MODE; - unsigned long GLCD_FS_ROWS_2; - unsigned long GLCD_FS_ROWS_1; - unsigned long GLCD_FS_DOT_SIZE_BIG; - unsigned long GLCD_FS_DOT_SIZE_LITTLE; - - unsigned long GLCD_DS_DISPLAY_ON; - unsigned long GLCD_DS_DISPLAY_OFF; - unsigned long GLCD_DS_CURSOR_ON; - unsigned long GLCD_DS_CURSOR_OFF; - unsigned long GLCD_DS_BLINK_ON; - unsigned long GLCD_DS_BLINK_OFF; - - unsigned long GLCD_IS_SHIFT_INCREMENT; - unsigned long GLCD_IS_SHIFT_DECREMENT; - unsigned long GLCD_IS_ENTRY_LEFT; - unsigned long GLCD_IS_ENTRY_RIGHT; - - unsigned long GROVE_RGB_WHITE; - unsigned long GROVE_RGB_RED; - unsigned long GROVE_RGB_GREEN; - unsigned long GROVE_RGB_BLUE; -}; - -[NoInterfaceObject] -interface GroveLCDDevice { + attribute unsigned long GLCD_FS_8BIT_MODE; + attribute unsigned long GLCD_FS_ROWS_2; + attribute unsigned long GLCD_FS_ROWS_1; + attribute unsigned long GLCD_FS_DOT_SIZE_BIG; + attribute unsigned long GLCD_FS_DOT_SIZE_LITTLE; +

+ attribute unsigned long GLCD_DS_DISPLAY_ON; + attribute unsigned long GLCD_DS_DISPLAY_OFF; + attribute unsigned long GLCD_DS_CURSOR_ON; + attribute unsigned long GLCD_DS_CURSOR_OFF; + attribute unsigned long GLCD_DS_BLINK_ON; + attribute unsigned long GLCD_DS_BLINK_OFF; +

+ attribute unsigned long GLCD_IS_SHIFT_INCREMENT; + attribute unsigned long GLCD_IS_SHIFT_DECREMENT; + attribute unsigned long GLCD_IS_ENTRY_LEFT; + attribute unsigned long GLCD_IS_ENTRY_RIGHT; +

+ attribute unsigned long GROVE_RGB_WHITE; + attribute unsigned long GROVE_RGB_RED; + attribute unsigned long GROVE_RGB_GREEN; + attribute unsigned long GROVE_RGB_BLUE; +};

interface GroveLCDDevice { void print(string text); void clear(); void setCursorPos(unsigned long col, unsigned long row); @@ -59,50 +68,43 @@ interface GroveLCDDevice { unsigned long getFunction(); void setDisplayState(unsigned long config); unsigned long getDisplayState(); -}; -``` - -API Documentation ------------------ -### GroveLCD.init - -`GroveLCDDevice init();` - -Initialize the Grove LCD panel +};

+
-*NOTE: Zephyr's Grove LCD API is on top of the I2C which is only accessible -from the ARC side on the Arduino 101, so all the API in here will use the -IPM to send commands over to the API, and all the API will be synchronous* - -The function returns a GroveLCDDevice object instance that can be used to +GroveLCD API +------------ +### grove_lcd.init() +* Returns: a GroveLCDDevice object that can be used to talk to the Grove LCD panel. -### GroveLCDDevice.print +Initializes the Grove LCD panel. + +*NOTE: Zephyr's Grove LCD API is on top of the I2C, which is only accessible +from the ARC side on the Arduino 101, so all the APIs in here will use the +IPM to send commands over to the API, and all this API will be synchronous.* -`void print(string text);` +GroveLCDDevice API +------------------ +### groveLCDDevice.print(text) +* `text` *string* The text to be printed. Send text to the screen on the current line cursor is set to, if the text is longer than number of characters it can fit on that line, any additional characters will not wrap around and be dropped, so a 16x2 LCD will have a maximum of 16 characters. -### GroveLCDDevice.clear - -`void clear();` +### groveLCDDevice.clear() Clear the current display. -### GroveLCDDevice.setCursorPos - -`void setCursorPos(unsigned long col, unsigned long row);` +### groveLCDDevice.setCursorPos(col, row) +* `col` *unsigned long* The column for the cursor to be moved to (0-15). +* `row` *unsigned long* The row the column should be moved to (0 or 1). -Set text cursor position for next additions. -The `col` is the column for the cursor to be moved to (0-15). -The `row` is the row it should be moved to (0 or 1). +Set text cursor position for the next print. -### GroveLCDDevice.selectColor - -`void selectColor(unsigned long index);` +### groveLCDDevice.selectColor(index) +* `index` *unsigned long* The color selection, as defined, below. Set LCD background to a predfined color. @@ -116,25 +118,21 @@ GroveLCD.GROVE_RGB_GREEN GroveLCD.GROVE_RGB_BLUE -### GroveLCDDevice.setColor - -`void setColor(unsigned long r, unsigned long g, unsigned long b);` - -Set LCD background to custom RGB color value +### groveLCDDevice.setColor(r, g, b) +* `r` *unsigned long* The numeric value for the red color (max is 255). +* `g` *unsigned long* The numeric value for the green color (max is 255). +* `b` *unsigned long* The numeric value for the blue color (max is 255). -The `r` is a numeric value for the red color (max is 255). -The `g` is a numeric value for the green color (max is 255). -The `b` is a numeric value for the blue color (max is 255). +Set LCD background to custom RGB color value. -### GroveLCDDevice.setFunction - -`void setFunction(unsigned long config);` +### groveLCDDevice.setFunction(config) +* `config` *unsigned long* The bit mask to change the display state, as described, below. This function provides the user the ability to change the state of the display, controlling things like the number of rows, dot size, and text display quality. -The `config` is bit mask of the following configurations: +The `config` bit mask can take the following configurations: GroveLCD.GLCD_FS_8BIT_MODE @@ -146,15 +144,11 @@ GroveLCD.GLCD_FS_DOT_SIZE_BIG GroveLCD.GLCD_FS_DOT_SIZE_LITTLE -### GroveLCDDevice.getFunction +### groveLCDDevice.getFunction() +*Returns: the function-features set associated with the device. -`unsigned long getFunction();` - -Return the function features set associated with the device. - -### GroveLCDDevice.setDisplayState - -`void setDisplayState(unsigned long config);` +### groveLCDDevice.setDisplayState(config) +* `config` *unsigned long* The bit mask to change the display state, as described, below. This function provides the user the ability to change the state of the display, controlling things like powering on or off @@ -175,11 +169,8 @@ GroveLCD.GLCD_DS_BLINK_ON GroveLCD.GLCD_DS_BLINK_OFF -### GroveLCDDevice.getDisplayState - -`unsigned long getDisplayState();` - -Return the display feature set associated with the device. +### GroveLCDDevice.getDisplayState() +* Returns: the display-feature set associated with the device. Sample Apps ----------- diff --git a/docs/i2c.md b/docs/i2c.md index 7849e318f..6c4a0b209 100644 --- a/docs/i2c.md +++ b/docs/i2c.md @@ -3,7 +3,12 @@ ZJS API for I2C * [Introduction](#introduction) * [Web IDL](#web-idl) -* [API Documentation](#api-documentation) +* [I2C API](#i2c-api) + * [i2c.open(init)](#i2copeninit) +* [I2CBus API](#i2cbus-api) + * [i2cBus.write(device, data)](#i2cbuswritedevice-data) + * [i2cBus.read(device, size, registerAddress)](#i2cbusreaddevice-size-registeraddress) + * [I2CBus.burstRead(device, size, registerAddress)](#i2cbusburstreaddevice-size-registeraddress) * [Sample Apps](#sample-apps) Introduction @@ -14,60 +19,60 @@ and SCL. SDA is the data signal and SCL is the clock signal. Web IDL ------- -This IDL provides an overview of the interface; see below for documentation of -specific API functions. - -```javascript -// require returns a I2C object -// var i2c = require('i2c'); - -[NoInterfaceObject] +This IDL provides an overview of the interface; see below for +documentation of specific API functions. We have a short document +explaining [ZJS WebIDL conventions](Notes_on_WebIDL.md). + +
+Click to show WebIDL +
// require returns a I2C object
+// var i2c = require('i2c');

[ReturnFromRequire] interface I2C { I2CBus open(I2CInit init); -}; - -dictionary I2CInit { +};

dictionary I2CInit { octet bus; I2CBusSpeed speed; -}; - -[NoInterfaceObject] +};

[ExternalInterface=(buffer,Buffer)] interface I2CBus { // has all the properties of I2CInit as read-only attributes - write(octet device, Buffer data); - read(octet device, unsigned int size, octet registerAddress); - burstRead(octet device, unsigned int size, octet registerAddress); + void write(octet device, Buffer data); + void read(octet device, unsigned long size, octet registerAddress); + void burstRead(octet device, unsigned long size, octet registerAddress); }; -``` +

+typedef I2CBusSpeed long;

+
-API Documentation ------------------ -### I2C.open - -`I2CBus open(I2CInit init);` - -The `init` object lets you set the I2C bus you wish to use and the speed you -want to operate at. Speed options are 10, 100, 400, 1000, and 34000. Speed is +I2C API +------- +### i2c.open(init) +* `init` *I2CInit* Lets you set the I2C bus you wish to use and the speed you +want to operate at. Speed options are 10, 100, 400, 1000, and 34000. Speed is measured in kbs. +* Returns: an I2CBus object. -### I2CBus.write - -`void write(octet device, Buffer data);` +I2CBus API +---------- +### i2cBus.write(device, data) +* `device` *octet* The device address. +* `data` *Buffer* The data to be written. Writes the data to the given device address. The first byte of data typically contains the register you want to write the data to. This will vary from device to device. -### I2CBus.read - -`Buffer read(octet device, unsigned int size, octet registerAddress);` +### i2cBus.read(device, size, registerAddress) +* `device` *octet* The device address. +* `size` *unsigned long* The number of bytes of data to read. +* `registerAddress` *octet* The register on the device from which to read. Reads 'size' bytes of data from the device at the registerAddress. The default value of registerAdress is 0x00; -### I2CBus.burstRead - -`Buffer burstRead(octet device, unsigned int size, octet registerAddress);` +### I2CBus.burstRead(device, size, registerAddress) +* `device` *octet* The device address. +* `size` *long* The number of bytes of data to read. +* `registerAddress` *octet* The number of the starting address from which to read. Reads 'size' bytes of data from the device across multiple addresses starting at the registerAddress. The default value of registerAdress is 0x00; diff --git a/docs/mathstubs.md b/docs/mathstubs.md index 6d27a3a17..3574c70be 100644 --- a/docs/mathstubs.md +++ b/docs/mathstubs.md @@ -3,12 +3,13 @@ ZJS API for MathStubs * [Introduction](#introduction) * [Web IDL](#web-idl) -* [API Documentation](#api-documentation) +* [Mathstubs API](#mathstubs-api) + * [random()](#mathstubsrandom) * [Sample Apps](#sample-apps) Introduction ------------ -"MathStubs" module implements a subset of the Math libary's functions such +The "MathStubs" module implements a subset of the Math library's functions such as random(). This module is served as a replacement for the JerryScript's Math libary when you only need certain math functions without the need to import Math so your application can be smaller, since enabling the whole Math @@ -19,18 +20,22 @@ round(), floor(), etc. Web IDL ------- This IDL provides an overview of the interface; see below for documentation of -specific API functions. +specific API functions. We have a short document explaining [ZJS WebIDL conventions](Notes_on_WebIDL.md). -```javascript -double MathStubs.random(); -``` +
+ Click to show/hide WebIDL +
// require returns a MathStubs object
+// var mathStubs = require('mathstubs');

[ReturnFromRequire] +interface MathStubs { + double random(); +}; +

+
-API Documentation +Mathstubs API ----------------- -### random -`double random();` - -Returns a floating-point, pseudo-random number between 0 (inclusive)and 1 (exclusive). +### mathStubs.random() +* Returns: a floating-point, pseudo-random number between 0 (inclusive) and 1 (exclusive). Sample Apps ----------- diff --git a/docs/net-config.md b/docs/net-config.md index 752438acb..98e52c12b 100644 --- a/docs/net-config.md +++ b/docs/net-config.md @@ -3,8 +3,12 @@ ZJS API for Network Configuration * [Introduction](#introduction) * [Web IDL](#web-idl) -* [API Documentation](#api-documentation) -* [Sample Apps](#sample-apps) +* [NetConfig API](#netconfig-api) + * [Event: 'netup'](#event-netup) + * [Event: 'netdown'](#event-netdown) + * [net_cfg.setStaticIP(ip)](#net_cfgsetstaticipip) + * [net_cfg.dhcp(callback)](#net_cfgdhcpcallback) + * [net_cfg.setBleAddress(address)](#net_cfgsetbleaddressaddress) Introduction ------------ @@ -19,26 +23,23 @@ static IP addresses of 192.0.2.1 and 2001:db8::1. Web IDL ------- This IDL provides an overview of the interface; see below for documentation of -specific API functions. +specific API functions. We have a short document explaining [ZJS WebIDL conventions](Notes_on_WebIDL.md). -```javascript +
+ Click to show/hide WebIDL +
 // require returns a Net object
-// var net_cfg = require('netconfig');
-
+// var net_cfg = require('netconfig');

[ReturnFromRequire,ExternalInterface=(eventemitter, EventEmitter)] interface NetConfig: EventEmitter { - // set a static IP - Boolean setStaticIP(String ip); - // start DHCP + boolean setStaticIP(string ip); void dhcp(DHCPCallback callback); - // set the BLE MAC address - void setBleAddress(String address); -}; - -callback DHCPCallback = void (String address, String subnet, String gateway); -``` + void setBleAddress(string address); +};

callback DHCPCallback = void (string address, string subnet, string gateway); +

+
-API Documentation ------------------ +NetConfig API +------------- NetConfig is an [EventEmitter](./events.md) with the following events: ### Event: 'netup' @@ -51,35 +52,30 @@ wait for a BLE connection before issuing any socket connections. Emitted when the networking interface goes offline. -### NetConfig.setStaticIP -`Boolean setStaticIP(String ip)` +### net_cfg.setStaticIP(ip) +* `ip` *string* This should be either an IPv4 or IPv6 string. +* Returns: true if the IP was successfully set and false if there was a problem setting the IP. Set the device to use a static IP address. -`ip` should be either an IPv4 or IPv6 string. - -This returns a true if the IP was successfully set. It will return false if -there was a problem setting that IP. An error will be returned if there was +An error will be returned if there was a misconfiguration, e.g. setting an IPv6 address when IPv6 was not built. -### NetConfig.dhcp -`void dhcp(DHCPCallback callback)` +### net_cfg.dhcp(callback) +* `callback` *DHCPCallback* Start DHCP to obtain an IP address. -`callback` should be a `DHCPCallback` type. This event listener will be called -when DHCP has finished. The callback will contain 3 arguments: `address`, +This `callback` event listener will be called when DHCP has +finished. The callback will contain 3 arguments: `address`, `subnet`, and `gateway`. -### NetConfig.setBleAddress -`void setBleAddress(string address);` +### net_cfg.setBleAddress(address) +* `address` *string* The MAC address string in the format `XX:XX:XX:XX:XX:XX`, where each character is in HEX format (0-9, A-F). Sets the device's BLE MAC address. This function is only defined on Zephyr boards with BLE capabilities (e.g. Arduino 101). -The `address` parameter should be a MAC address string in the format -`XX:XX:XX:XX:XX:XX` where each character is in HEX format (0-9, A-F). - Note: This function has be called when the JS is initially run when loaded. This means no calling from within any callback functions like setTimeout(), setInterval() and promises. Also, If the image was built diff --git a/docs/net.md b/docs/net.md index 6b046545f..a8673f1ac 100644 --- a/docs/net.md +++ b/docs/net.md @@ -3,120 +3,146 @@ ZJS API for Net * [Introduction](#introduction) * [Web IDL](#web-idl) -* [API Documentation](#api-documentation) + + + + + +* [Class: Net](#net-api) + * [net.createServer(callback onconnection)](#netcreateservercallback-onconnection) + * [net.Socket()](#netsocket) + * [net.isIP(string input)](#netisipstring-input) + * [Net.isIPv4(string input)](#netisipv4string-input) + * [Net.isIPv6(string input)](#netisipv6string-input) +* [Class: Socket](#socket-api) + * [Event: 'close'](#event-close) + * [Event: 'connect'](#event-connect) + * [Event: 'data'](#event-data) + * [Event: 'error'](#event-error) + * [Event: 'timeout'](#event-timeout) + * [Socket.connect(options, onconnect)](#socketconnectoptions-onconnect) + * [Socket.pause()](#socketpause) + * [Socket.resume()](#socketresume) + * [Socket.setTimeout(time, ontimeout)](#socketsettimeouttime-ontimeout) + * [Socket.write(buf, writeDone)](#socketwritebuf-writedone) +* [Class: Server](#server-api) + * [Event: 'close'](#event-close) + * [Event: 'connection'](#event-connection) + * [Event: 'error'](#event-error) + * [Event: 'listening'](#event-listening) + * [Server.address](#serveraddress) + * [Server.close()](#serverclose) + * [Server.getConnections(ListenerCallback onconnection)](#servergetconnectionslistenercallback-onconnection) + * [Server.listen(options, onlistening)](#serverlistenoptions-onlistening) + + + + + * [Sample Apps](#sample-apps) Introduction ------------ -ZJS provides net (TCP) APIs which closely mimic the Node.js 'net' module. This -module allows you to create a TCP/IP server or client. +ZJS provides net (TCP) APIs that closely mimic the Node.js 'net' +module, which allows you to create a TCP/IP server or client. Web IDL ------- This IDL provides an overview of the interface; see below for documentation of -specific API functions. - -```javascript +specific API functions. We also have a short document explaining [ZJS WebIDL conventions](Notes_on_WebIDL.md). +
+ Click to show/hide WebIDL +
 // require returns a Net object
-// var net = require('net');
-
+// var net = require('net');

[ReturnFromRequire] interface Net { - // create a server object - Server createServer(callback onconnection); - // Socket constructor, create a new Socket + Server createServer(optional callback onconnection); Socket Socket(); - Number isIP(input); - Boolean isIPv4(input); - Boolean isIPv6(input); + long isIP(string input); + Boolean isIPv4(string input); + Boolean isIPv6(string input); }; - +

[ExternalInterface=(eventemitter,EventEmitter),ExternalInterface=(buffer,Buffer),ExternalCallback=(eventemitter,ListenerCallback)] interface Socket: EventEmitter { // Socket methods - void connect(Object options, callback onconnect); + void connect(object options, optional ListenerCallback onconnect); void pause(); void resume(); - void setTimeout(Number timeout, callback ontimeout); - void write(Buffer buf, callback writeDone); + void setTimeout(long timeout, ListenerCallback ontimeout); + void write(Buffer buf, optional ListenerCallback writeDone); // Socket properties - Number bufferSize; // Size of read buffer - Number bytesRead; // Total bytes read for the socket - Number bytesWritten; // Total bytes written for the socket - String localAddress; // Sockets local IP - Number localPort; // Sockets local port - String remoteAddress; // Remote IP address - String remoteFamily; // Remote IP family - Number remotePort; // Remote port -}; - + attribute long bufferSize; // Size of read buffer + attribute long bytesRead; // Total bytes read for the socket + attribute long bytesWritten; // Total bytes written for the socket + attribute string localAddress; // Sockets local IP + attribute long localPort; // Sockets local port + attribute string remoteAddress; // Remote IP address + attribute string remoteFamily; // Remote IP family + attribute long remotePort; // Remote port +};

+[ExternalInterface=(eventemitter, EventEmitter),ExternalCallback=(eventemitter,ListenerCallback)] interface Server: EventEmitter { // Server methods AddressInfo address(); void close(); - void getConnections(callback); - void listen(Object options, callback onlistening); + void getConnections(ListenerCallback onconnection); + void listen(object options, optional ListenerCallback onlistening); // Server properties - Boolean listening; // true if the server is listening - Number maxConnections; // maximum number of connections + attribute boolean listening; // true if the server is listening + attribute long maxConnections; // maximum number of connections }; - +

dictionary AddressOptions { - Number port; // Port the client should connect to (required) - String host; // Host the client should connect to - String localAddress; // Local address to bind to - Number localPort; // local port to bind to - Number family; // Version of IP stack, deafults to 4 -} - + long port; // Port the client should connect to (required) + string host; // Host the client should connect to + string localAddress; // Local address to bind to + long localPort; // local port to bind to + long family; // Version of IP stack, deafults to 4 +}; +

dictionary AddressInfo { - Number port; // Server port - String family; // IPv4 or IPv6 - String address; // IP address for the server -} -``` + long port; // Server port + string family; // IPv4 or IPv6 + string address; // IP address for the server +}; +

+
-Net API Documentation ---------------------- +Net API +------- -### Net.createServer -`Server createServer(callback onconnection)` +### net.createServer(callback onconnection) +* `onconnection` *callback* The (optional) callback function registered as the the event listener for the `connection` event. +* Returns: a `Server` object. Create a TCP server that can accept client connections. -`onconnection` is an optional callback function that, if supplied, will be -registered as the the event listener for the `connection` event. - -Returns a `Server` object. +### net.Socket() +* Returns: a new Socket object that can be used to connect to a remote TCP server. -### Net.Socket -`Socket Socket(void)` +Socket constructor. -Socket constructor. Calling `new Socket()` will return a new Socket object -that can be used to connect to a remote TCP server. - -### Net.isIP -`Number isIP(input)` +### net.isIP(string input) +* `input` *string* +* Returns: 4 if the input is an IPv4 address, 6 if the input is an IPv6 address, +or 0 if the input is not an IP address. Checks if the input is a valid IP address. -Returns 4 if the input is an IPv4 address, 6 if the input is an IPv6 address, -or 0 if the input is not an IP address. - -### Net.isIPv4 -`Boolean isIPv4(input)` +### Net.isIPv4(string input) +* `input` *string* +* Returns: true if input is IPv4, false otherwise. Checks if input is an IPv4 address. -Returns true if input is IPv4. - -### Net.isIPv6 -`Boolean isIPv6(input)` +### Net.isIPv6(string input) +* `input` *string* +* Returns: true if input is IPv6, false otherwise. Checks if input is an IPv6 address. -Returns true if input is IPv6. - -Socket API Documentation ------------------------- +Socket API +---------- Socket is an [EventEmitter](./events.md) with the following events: @@ -143,46 +169,37 @@ Emitted when there was an error on the socket during read, write, or connect. Emitted only when a timeout set with `setTimeout` expires. -### Socket.connect -`void connect(AddressOptions options, callback onconnect)` +### Socket.connect(options, onconnect) +* `options` *AddressOptions* Describes the remote server being connected to. +* `onconnect` *ListenerCallback* Optional callback added as the listener for the +`connect` event. Connect to a remote TCP server. -`options` should describe the remote server your connecting to. - -`onconnect` is optional and, if specified, will be added as the listener for the -`connect` event. - -### Socket.pause -`void pause(void)` +### Socket.pause() Pause a socket from receiving data. `data` event will not be emitted until -`resume` is called. +`Socket.resume` is called. -### Socket.resume -`void resume(void)` +### Socket.resume() -Allow a socket to resume receiving data after a call to `pause`. +Allow a socket to resume receiving data after a call to `Socket.pause`. -### Socket.setTimeout -`void setTimeout(Number time, callback ontimeout)` +### Socket.setTimeout(time, ontimeout) +* `time` *long* +* `ontimeout` *ListenerCallback* Optional callback registered as a listener for the `timeout` event. -Set a socket timeout. This will start a timer on the socket which will expire -in `time` milliseconds if there has been no activity on the socket. The -`ontimeout` parameter, if specified, will register a listener for the -`timeout` event. +Set a socket timeout. This will start a timer on the socket that will expire +in `time` milliseconds if there has been no activity on the socket. -### Socket.write -`void write(Buffer buf, callback writeDone)` +### Socket.write(buf, writeDone) +* `buf` *Buffer* `buf` Contains the data to be written. +* `writeDone` *ListenerCallback* Optional function called once the data is written. Send data on the socket. -`buf` should contain the data you wish to send. - -`writeDone` is optional and will be called once the data is written. - -Server API Documentation ------------------------- +Server API +---------- Server is an [EventEmitter](./events.md) with the following events: @@ -212,21 +229,20 @@ Emitted when the server has been bound, after calling `server.listen()`. Returns an AddressInfo object for the server: -### Server.close -`void close(void)` +### Server.close() Signals the server to close. This will stop the server from accepting any new connections but will keep any existing connections alive. Once all existing connections have been closed the server will emit the `close` event. -### Server.getConnections(callback) -`void getConnections(callback)` +### Server.getConnections(ListenerCallback onconnection) +* `onconnection` *ListenerCallback* Should be a function with `err` and `count` parameters. -Get the number of connections to the server. The `callback` parameter should be -a function with `err` and `count` parameters. +Get the number of connections to the server. -### Server.listen -`void listen(Object options, callback onlistening)` +### Server.listen(options, onlistening) +* `options` *object* +* `onlistening` *ListenerCallback* Optional function added to the `listening` event. Start listening for connections. The `options` object supports the following properties: @@ -238,9 +254,6 @@ properties: } ``` -`onlistening` is optional and, if specified, will add a listener to the -`listening` event. - Sample Apps ----------- * [IPv6 Server sample](../samples/TCPEchoServ6.js) diff --git a/docs/ocf.md b/docs/ocf.md index 70c012aad..7ab327f39 100644 --- a/docs/ocf.md +++ b/docs/ocf.md @@ -3,42 +3,53 @@ ZJS API for OCF * [Introduction](#introduction) * [Web IDL](#web-idl) -* [OCF Object](#the-ocf-object) -* [OCF API Documentation](#ocf-api-documentation) -* [OCF Server](#ocf-server) -* [Server API Documentation](#server-api-documentation) -* [Server Samples](#server-samples) -* [OCF Client](#ocf-client) -* [Client API Documentation](#client-api-documentation) -* [Client Samples](#client-samples) +* [Class: OCF](#ocf-api) + * [ocf.start()](#ocfstart) +* [OCFServer-supported Events](#ocfserver-supported-events) +* [Class: OCFServer](#ocfserver-api) + * [server.register(init)](#serverregisterinit) +* [Class: Request](#request-api) + * [request.respond(data)](#requestresponddata) +* [OCFClient-supported Events](#ocfclient-supported-events) +* [Class: OCFClient](#ocfclient-api) + * [client.findResources(options, listener)](#clientfindresourcesoptions-listener) + * [client.retrieve(deviceId, options)](#clientretrievedeviceid-options) + * [client.update(resource)](#clientupdateresource) + * [client.getPlatformInfo(deviceId)](#clientgetplatforminfodeviceid) + * [client.getDeviceInfo(deviceId)](#clientgetdeviceinfodeviceid) +* [OCFServer Samples](#ocfserver-samples) +* [OCFClient Samples](#ocfclient-samples) Introduction ------------ ZJS provides OCF Server API's which allow communication using the OCF networking protocol. -Web IDL -------- -This IDL provides an overview of the interfaces for OCF common, OCF Server and -OCF Client; see below for documentation of specific API functions. - -The OCF Object --------------- The OCF object is the top level object containing either OCF Server, OCF Client, or both, as well as device and platform information. -```javascript +The OCF device and platform objects can be set up after requiring 'ocf'. An +example of this can be found in [OCF Server sample](../samples/OcfServer.js). + +Web IDL +------- +This IDL provides an overview of the interface; see below for +documentation of specific API functions. We have a short document +explaining [ZJS WebIDL conventions](Notes_on_WebIDL.md). + +
+Click to show WebIDL +
 // require returns an OCFObject
 // var ocf = require('ocf');
-
+

[ReturnFromRequire] interface OCFObject { - Server server; // OCF server object - Client client; // OCF client object - Platform platform; // OCF platform info - Device device // OCF device info -}; - -dictionary Platform { + attribute OCFServer server; // OCF server object + attribute OCFClient client; // OCF client object + attribute Platform platform; // OCF platform info + attribute Device device; // OCF device info + void start(); +};

dictionary Platform { string id; string osVersion; string model; @@ -48,40 +59,18 @@ dictionary Platform { string platformVersion; string firmwareVersion; string supportURL; -} - -dictionary Device { +};

dictionary Device { string uuid; string name; string dataModels; string coreSpecVersion; -} - -``` -The OCF device and platform objects can be set up after requiring 'ocf'. An -example of this can be found in [OCF Server sample](../samples/OcfServer.js). -The properties are registered to the system (and available during discovery) -once either `OCFServer.registerResource()` or `OCFClient.findResources()` -is called. - -OCF API Documentation ---------------------- - -### OCFObject.start -`void start(void)` - -Start the OCF stack (iotivity-constrained). This should be called after all -resources have been registered. Any calls to `registerResource` after `start` -will have no effect. - -OCF Server ----------- -```javascript -interface Server: EventEmitter { +};

/////////////////////////////////////////// +// OCF Server +///////////////////////////////////////////

[ExternalInterface=(eventemitter, +EventEmitter)] +interface OCFServer: EventEmitter { Promise register(ResourceInit init); -}; - -dictionary ResourceInit { +};

dictionary ResourceInit { string resourcePath; // OCF resource path string[] resourceTypes; // List of resource types string[] interfaces; // List of interfaces for resource types @@ -90,24 +79,52 @@ dictionary ResourceInit { boolean secure; // Is resource security enabled boolean slow; // Is resource a slow reader object properties; // Dictionary of resource properties -}; - -interface Resource { +};

dictionary Resource { string resourcePath; // Path for this resource object properties; // Application specific resource properties -}; - -interface Request { - OCFResource target; // Target/destination resource - OCFResource source; // Source/origin resource - object data; // resource representation +};

interface Request { + attribute OCFResource target; // Target/destination resource + attribute OCFResource source; // Source/origin resource + attribute object data; // resource representation Promise respond(object data); +};

/////////////////////////////////////////// +// OCF Client +///////////////////////////////////////////

[ExternalInterface=(eventemitter, +EventEmitter)] +interface OCFClient: EventEmitter { + Promise findResources(ClientOptions options, optional FoundListener listener); + Promise retrieve(string deviceId, object options); + Promise update(Resource resource); + Promise getPlatformInfo(string deviceId); + Promise getDeviceInfo(string deviceId); +};

dictionary ClientOptions { + string deviceId; + string resourceType; + string resourcePath; +};

callback FoundListener = void (ClientResource resource); +dictionary ClientResource { + string deviceId; + string resourceType; + string resourcePath; }; -``` +

+
-Server API Documentation ------------------------- -Server is an [EventEmitter](./events.md) with the following events: +OCF API +------- +The properties are registered to the system (and available during discovery) +once either `OCFServer.registerResource()` or `OCFClient.findResources()` +is called. + +### ocf.start() + +Start the OCF stack (iotivity-constrained). This should be called after all +resources have been registered. Any calls to `registerResource` after `start` +will have no effect. + +OCFServer-supported Events +-------------------------- +An OCFServer is an [EventEmitter](./events.md) with the following events: ### Event: 'retrieve' @@ -122,60 +139,28 @@ Emitted when a remote client retrieves this server's resource(s). Emitted when a remote client updates this server's resource(s). -### Server.register -`Promise register(ResourceInit init);` +OCFServer API +-------------- +### server.register(init) +* `init` *ResourceInit* Contains the resource initialization information. +* Returns: a promise which resolves to an `OCFResource`. Register a new resource with the server. -The `init` contains the resource initalization information. - -Returns a promise which resolves to an `OCFResource`. - -### Request.respond -`Promise respond(object data);` - -Respond to an OCF `retrieve` or `update` event. - -The `data` parameter should contain object property data for the resource. In +Request API +----------- +### request.respond(data) +* `data` *object* Should contain object property data for the resource. In the case of an `onretrieve` event, `data` will be sent back to the client as the retrieved property data. +* Returns: a promise which resolves successfully if there was no network error +from sending out the data. -Returns a promise which resolves successfully if there was no network error -sending out the data. - -Server Samples --------------- -* [OCF Server sample](../samples/OcfServer.js) -* [OCF Sensor Server](../samples/OcfSensorServer.js) - -OCF Client ----------- -```javascript -interface Client: EventEmitter { - Promise findResources(ClientOptions options, optional FoundListener listener); - Promise retrieve(string deviceId, object options); - Promise update(Resource resource); - Promise getPlatformInfo(string deviceId); - Promise getDeviceInfo(string deviceId); -}; - -dictionary ClientOptions { - string deviceId; - string resourceType; - string resourcePath; -} - -interface Resource { - string resourcePath; // Path for this resource - object properties; // Application specific resource properties -}; - -callback FoundListener = void (ClientResource); -``` +Respond to an OCF `retrieve` or `update` event. -Client API Documentation ------------------------- -Client is an [EventEmitter](./events.md) with the following events: +OCFClient-supported Events +-------------------------- +An OCFClient is an [EventEmitter](./events.md) with the following events: ### Event: 'devicefound' @@ -201,68 +186,52 @@ Emitted when a resource is found during `findResources()`. Emitted when a resource is updated. -### Client.findResources -`Promise findResources(ClientOptions options, optional FoundListener listener);` - -Find remote resources matching `options` filter. - -The `options` parameter should contain a filter of resource options. Only +OCFClient API +------------- +### client.findResources(options, listener) +* `options` *ClientOptions* Should contain a filter of resource options. Only resources matching these options will be found. - -The `listener` parameter is an optional event listener callback. This +* `listener` *FoundListener* An optional event-listener callback. This callback will be called if a resource is found (`onfound` event). +* Returns: a promise which resolves to a `ClientResource` containing the resource properties if a resource is found. -Returns a promise which resolves with a `ClientResource` object if a resource -was found. - -### Client.retrieve -`Promise retrieve(string deviceId, object options);` - -Retrieve (GET) a remote resource. +Find remote resources matching `options` filter. -The `deviceId` parameter is the device ID of the resource you are retrieving. +### client.retrieve(deviceId, options) +* `deviceId` *string* The device ID of the resource you are retrieving. This ID must match a resource which has been found with `findResources()`. +* `options` *object * Contains flag information for this GET request (e.g., `observable=true`). -The `options` object properties contain flag information for this GET request -e.g. `observable=true`. - -Returns a promise which resolves to a `ClientResource` containing the resource -properties. - -### Client.update -`Promise update(Resource resource);` - -Update remote resource properties. +Retrieve (GET) a remote resource. -The `resource` parameter should contain a `deviceId` for the resource to +### client.update(resource) +* `resource` *Resource* Should contain a `deviceId` for the resource to update. The `properties` parameter will be sent to the resource and updated. - -Returns a promise which resolves to a resource `Resource` containing the +* Returns: a promise which resolves to a resource `Resource` containing the updated properties. -### Client.getPlatformInfo -`Promise getPlatformInfo(string deviceId);` +Update remote resource properties. -Get `Platform` information for a resource. +### client.getPlatformInfo(deviceId) +* `deviceId` *string* The `deviceId` parameter should be the ID for a resource found with `findResources()`. +* Returns: a promise which resolves to a `Platform` containing the platform +information for the resource. -The `deviceId` parameter should be the ID for a resource found with -`findResources()`. +Get `Platform` information for a resource. -Returns a promise which resolves to a `Platform` containing the platform +### client.getDeviceInfo(deviceId) +* `deviceId` *string* The ID for a resource found with `findResources()`. +* Returns: a promise which resolves to a `Device` containing the device information for the resource. -### Client.getDeviceInfo -`Promise getDeviceInfo(string deviceId);` - Get `Device` information for a resource. -The `deviceId` parameter should be the ID for a resource found with -`findResources()`. - -Returns a promise which resolves to a `Device` containing the device -information for the resource. +OCFServer Samples +-------------- +* [OCF Server sample](../samples/OcfServer.js) +* [OCF Sensor Server](../samples/OcfSensorServer.js) -Client Samples +OCFClient Samples -------------- * [OCF Client sample](../samples/OcfClient.js) * [OCF Sensor Client](../samples/OcfSensorClient.js) diff --git a/docs/performance.md b/docs/performance.md index 0981518ae..ac3f5ebbe 100644 --- a/docs/performance.md +++ b/docs/performance.md @@ -3,46 +3,54 @@ ZJS API for Benchmarking * [Introduction](#introduction) * [Web IDL](#web-idl) -* [API Documentation](#api-documentation) +* [Performance API](#performance-api) + * [performance.now()](#performancenow) * [Sample Apps](#sample-apps) Introduction ------------ -"Performance" module implements a subset of "High Resolution Time" specification -from W3C, intended primarily for benchmarking purposes. The key point of this -module is that it is very light-weight by implementing just one function -(unlike for example Date object). + +The "Performance" module implements a subset of the "High Resolution Time" +specification from W3C, intended primarily for benchmarking +purposes. The key point of this module is that it is very light-weight +by implementing just one function (unlike, for example, the Date object). Web IDL ------- -This IDL provides an overview of the interface; see below for documentation of -specific API functions. -```javascript -double now(); -``` +This IDL provides an overview of the interface; see below for documentation of +specific API functions. We also have a short document explaining [ZJS WebIDL conventions](Notes_on_WebIDL.md). +
+ Click to show/hide WebIDL +
+// require returns a Performance object
+// var ble = require('performance');
+

+[ReturnFromRequire] +interface Performance { + double now(); +};

+
-API Documentation ------------------ -### now -`now(); -` +Performance API +--------------- +### performance.now() +* Returns: the current time in milliseconds, as a floating-point number. -The module exposes just one function, `now()`. It returns current time in -milliseconds, as a floating-point number, since an arbitrary point in -time. It is thus not useful as an absolute value, but subtracting values -from two calls will give a time duration between these two calls. +The "time" returned from this function is the offset since an +arbitrary point in time. It is thus not useful as an absolute value, +but subtracting values from two calls will give a time duration +between these two calls. -As the value returned is floating point, it may have higher resolution +As the value returned is a floating point value, it may have higher resolution than a millisecond. However, the actual resolution depends on a platform -and its configuration. For example, default Zephyr configuration for +and its configuration. For example, the default Zephyr configuration for many boards provides resolution of only ones or tens of milliseconds. -The intended usage of this function is for benchmarking and other testing +The intended use of this function is for benchmarking and other testing and development needs. - Examples -------- diff --git a/docs/pme.md b/docs/pme.md index 04bd08a73..c7a3fcf68 100644 --- a/docs/pme.md +++ b/docs/pme.md @@ -3,18 +3,33 @@ ZJS API for Pattern Matching Engine (PME) * [Introduction](#introduction) * [Web IDL](#web-idl) -* [API Documentation](#api-documentation) +* [Class: PME](#pme-api) + * [pme.begin()](#pmebegin) + * [pme.forget()](#pmeforget) + * [pme.configure(context, classificationMode, distanceMode, minInfluence, maxInfluence)](#pmeconfigurecontext-classificationmode-distancemode-mininfluence-maxinfluence) + * [pme.learn(pattern, category)](#pmelearnpattern-category) + * [pme.classify(pattern)](#pmeclassifypattern) + * [pme.readNeuron(id)](#pmereadneuronid) + * [pme.writeVector(pattern)](#pmewritevectorpattern) + * [pme.getCommittedCount()](#pmegetcommittedcount) + * [pme.getGlobalContext()](#pmegetglobalcontext) + * [pme.getClassifierMode()](#pmegetclassifiermode) + * [pme.setClassifierMode(mode)](#pmesetclassifiermodemode) + * [pme.getDistanceMode()](#pmegetdistancemode) + * [pme.setDistanceMode(mode)](#pmesetdistancemodemode) + * [pme.saveNeurons()](#pmesaveneurons) + * [pme.restoreNeurons(objects)](#pmerestoreneuronsobjects) * [Sample Apps](#sample-apps) Introduction ------------ -The Pattern Matching Engine API is the JavaScript version of the parallel data recognition engine with the following features: +The Pattern Matching Engine API is the JavaScript version of the parallel data-recognition engine with the following features: - 128 parallel Processing Elements (PE) each with - 128 byte input vector - 128 byte model memory - 8-Bit Arithmetic Units - - Two distance evaluation norms with 16-bit resolution: + - Two distance-evaluation norms with 16-bit resolution: - L1 norm (Manhattan Distance) - Lsup (Supremum) norm (Chebyshev Distance) - Support for up to 32,768 Categories @@ -30,194 +45,128 @@ The Pattern Matching Engine API is the JavaScript version of the parallel data r Web IDL ------- This IDL provides an overview of the interface; see below for documentation of -specific API functions. - -```javascript +specific API functions. We also have a short document explaining [ZJS WebIDL conventions](Notes_on_WebIDL.md). +
+ Click to show/hide WebIDL +
 // require returns a PME object
-// var pme = require('pme');
-
-[NoInterfaceObject]
+// var pme = require('pme');

[ReturnFromRequire] interface PME { - begin(); - forget(); - configure(unsigned short context, - unsigned short classificationMode, - unsigned short distanceMode, - unsigned short minInfluence, - unsigned short maxInfluence); - learn(number[] pattern, unsigned long category); - unsigned long classify(number[] pattern); + void begin(); + void forget(); + void configure(unsigned short context, + unsigned short classificationMode, + unsigned short distanceMode, + unsigned short minInfluence, + unsigned short maxInfluence); + void learn(sequence < number > pattern, unsigned long category); + unsigned long classify(sequence < number > pattern); Neuron readNeuron(unsigned long id); - writeVector(number[] pattern); + void writeVector(sequence < number > pattern); unsigned short getCommittedCount(); unsigned short getGlobalContext(); unsigned short getClassifierMode(); - setClassifierMode(unsigned short mode); + void setClassifierMode(unsigned short mode); unsigned short getDistanceMode(); - setDistanceMode(unsigned short mode); - Json[] saveNeurons(); - restoreNeurons(Json[] objects); - - unsigned short RBF_MODE; // RBF classification mode - unsigned short KNN_MODE; // KNN classification mode - unsigned short L1_DISTANCE; // L1 distance mode - unsigned short LSUP_DISTANCE; // LSUP distance mode - unsigned long NO_MATCH; // indicate a pattern could not be classified - unsigned short MIN_CONTEXT; // minimum context value - unsigned short MAX_CONTEXT; // maximum context value - unsigned long MAX_VECTOR_SIZE; // Maximum pattern size (in bytes) - unsigned long FIRST_NEURON_ID; // ID of first neuron in network - unsigned long LAST_NEURON_ID; // ID of last neuron in network - unsigned long MAX_NEURONS; // Number of neurons in the network -}; - -[NoInterfaceObject] -interface Neuron { + void setDistanceMode(unsigned short mode); + sequence < Json > saveNeurons(); + restoreNeurons(sequence < Json > objects); +

+ attribute unsigned short RBF_MODE; // RBF classification mode + attribute unsigned short KNN_MODE; // KNN classification mode + attribute unsigned short L1_DISTANCE; // L1 distance mode + attribute unsigned short LSUP_DISTANCE; // LSUP distance mode + attribute unsigned long NO_MATCH; // indicate a pattern could not + // be classified + attribute unsigned short MIN_CONTEXT; // minimum context value + attribute unsigned short MAX_CONTEXT; // maximum context value + attribute unsigned long MAX_VECTOR_SIZE; // Maximum pattern size (in bytes) + attribute unsigned long FIRST_NEURON_ID; // ID of first neuron in network + attribute unsigned long LAST_NEURON_ID; // ID of last neuron in network + attribute unsigned long MAX_NEURONS; // Number of neurons in the network +};

dictionary Neuron { unsigned short category; unsigned short context; unsigned short AIF; unsigned short minIF; }; -``` - -API Documentation ------------------ -### PME.begin +

+
-`void begin();` +PME API +------- +### pme.begin() Initialize the PME so it is ready for operation. -### PME.forget - -`void forget();` +### pme.forget() Clear any data committed to the network, making the network ready to learn again. -### PME.configure - -`configure(unsigned short context, - unsigned short classificationMode, - unsigned short distanceMode, - unsigned short minInfluence, - unsigned short maxInfluence);` +### pme.configure(context, classificationMode, distanceMode, minInfluence, maxInfluence) +* `context` *unsigned short* This value has a range between 1-127. A context value of 0 enables all neurons, with no regard to their context. +* `classificationMode` *unsigned short* The classifying function to use. Valid values are: PME.RBF_MODE (default) or PME.KNN_MODE. +* `distanceMode` *unsigned short* The distance function to use. Valid values are: PME.LSUP_DISTANCE or PME.L1_DISTANCE. +* `minInfluence` *unsigned short* The minimum influence value used on the neuron. +* `maxInfluence` *unsigned short* The maximum influence value used on the neuron. Configure the engine with parameters used for training data. -The `context` is valid context value range between 1-127. A context value of 0 enables all neurons, with no regard to their context. -The `classificationMode` is the classifying function to use. Valid values are: - - - PME.RBF_MODE (default) - - PME.KNN_MODE - -The `distanceMode` is the distance function to use. Valid values are: - - - PME.LSUP_DISTANCE - - PME.L1_DISTANCE - -The `minIF` is the minimum influence value used on the neuron. -The `maxIF` is the maximum influence value used on the neuron. - -### PME.learn - -`void learn(number[] pattern, unsigned long category);` +### pme.learn(pattern, category) +* `pattern` *array of bytes* An array of bytes up to 128 bytes in length. +* `category` *unsigned long* Indicates to the PME to which category this training vector belongs; that is, if a future input has a sufficiently similar pattern, it will be classified as the same category as the passed-in pattern. Takes a pattern and commits it to the network as training data for a given category. -The `pattern` is an array of bytes, up to 128 bytes in length. -The `category` indicates to the PME which category this training vector belongs to, that is, if a future input has a sufficiently similar pattern, it will be classified as the same category passed with this pattern. - -### PME.classify - -`unsigned long classify(number[] pattern);` +### pme.classify(pattern) +* `pattern` *array of bytes* An array of bytes up to 128 bytes in length. +* Returns: `PME.NO_MATCH` if the input data did not match any of the trained categories. Otherwise, the trained category assigned by the network will be returned. Takes a pattern and uses the committed neurons in the network to classify the pattern. -The `pattern` is an array of bytes, up to 128 bytes in length. - -Returns `PME.NO_MATCH` if the input data did not match any of the trained categories. Otherwise, the trained category assigned by the network will be returned. - -### PME.readNeuron - -`Neuron readNeuron(unsigned long id);` +### pme.readNeuron(id) +* `id` *unsigned long* A value between 1-128 representing a specific neuron. +* Returns: the `Neuron` object in which to write the neuron data. Read a specific neuron by its ID. -The `id` is value between 1-128 representing a specific neuron. - -Returns the `Neuron` object in which to write the neuron data. - -### PME.writeVector (KNN_MODE only) - -`void writeVector(number[] pattern);` +### pme.writeVector(pattern) +* `pattern` *array of bytes* An array of bytes up to 128 bytes in length. (Should only be used in KNN_MODE.) Takes a pattern and uses the committed neurons in the network to classify the pattern. -The `pattern` is an array of bytes, up to 128 bytes in length. - -### PME.getCommittedCount - -`unsigned short getCommittedCount();` +### pme.getCommittedCount() +*Returns: the number of comitted neurons in the network (a value between 0-128). Gets the number of committed neurons in the network. -Returns the number of comitted neurons in the network (a value between 0-128). - -### PME.getGlobalContext - -`unsigned short getGlobalContext();` +### pme.getGlobalContext() +* Returns: the contents of the Global Context Register (a value between 0-127). Reads the Global Context Register. -Returns the contents of the Global Context Register (a value between 0-127). - -### PME.getClassifierMode - -`unsigned short getClassifierMode();` +### pme.getClassifierMode() +* Returns: the classifying function being used. Possible values are: PME.RBF_MODE or PME.KNN_MODE. Gets the classifying function being used by the network. -Returns the the classifying function being used. Possible values are: - - - PME.RBF_MODE - - PME.KNN_MODE - -### PME.setClassifierMode - -`void setClassifierMode(unsigned short mode);` +### pme.setClassifierMode(mode) +* `mode` *unsigned short* The classifying function to use. Valid values are: PME.RBF_MODE (default) or PME.KNN_MODE. Sets the classifying function to be used by the network. -The `mode` is the classifying function to use. Valid values are: - - - PME.RBF_MODE (default) - - PME.KNN_MODE - -### PME.getDistanceMode - -`unsigned short getDistanceMode();` +### pme.getDistanceMode() +* Returns: the distance function being used. Possible values are: PME.LSUP_DISTANCE or PME.L1_DISTANCE. Gets the distance function being used by the network. -Returns the the distance function being used. Possible values are: - - - PME.LSUP_DISTANCE - - PME.L1_DISTANCE - -### PME.setDistanceMode - -`void setDistanceMode(unsigned short mode);` +### pme.setDistanceMode(mode) +* `mode` *unsigned short* The distance function to use. Valid values are: PME.LSUP_DISTANCE or PME.L1_DISTANCE. Sets the distance function to be used by the network. -The `mode` is the distance function to use. Valid values are: - - - PME.LSUP_DISTANCE - - PME.L1_DISTANCE - -### PME.saveNeurons - -`Json[] saveNeurons();` +### pme.saveNeurons() +* Returns: an array of JSON objects. Export committed neuron data into an array of JSON objects in the following format, maximum number of objects to save is 128: @@ -229,9 +178,8 @@ Export committed neuron data into an array of JSON objects in the following form "vector": [10,10,10,10] // up to 128 bytes }` -### PME.restoreNeurons - -`void restoreNeurons(Json[] objects);` +### pme.restoreNeurons(objects) +* `objects` *array of JSON objects* Restore neurons in an array of JSON objects in the following format, maximum number of objects to restore is 128: diff --git a/docs/pwm.md b/docs/pwm.md index 50ad5f197..0ce0fd183 100644 --- a/docs/pwm.md +++ b/docs/pwm.md @@ -3,7 +3,11 @@ ZJS API for Pulse Width Modulation (PWM) * [Introduction](#introduction) * [Web IDL](#web-idl) -* [API Documentation](#api-documentation) +* [Class: PWM](#pwm-api) + * [pwm.open(init)](#pwmopeninit) +* [Class: PWMPin](#pwmpin-api) + * [pin.setCycles(period, pulseWidth)](#pinsetcyclesperiod-pulsewidth) + * [pin.setMilliseconds(periodMS, pulseWidthMS)](#pinsetmillisecondsperiodms-pulsewidthms) * [Sample Apps](#sample-apps) Introduction @@ -35,68 +39,69 @@ The PWM API intends to follow the [iot-js-api specification](https://github.com/ Web IDL ------- -This IDL provides an overview of the interface; see below for documentation of -specific API functions. -```javascript +This IDL provides an overview of the interface; see below for documentation of +specific API functions. We also have a short document explaining [ZJS WebIDL conventions](Notes_on_WebIDL.md). +
+ Click to show/hide WebIDL +
 // require returns a PWM object
 // var pwm = require('pwm');
-
-[NoInterfaceObject]
+

+[ReturnFromRequire] interface PWM { - PWMPin open(PWMInit init); -}; - + PWMPin open((long or string or PWMInit) init); +};

dictionary PWMInit { - number or string pin; + (long or string) pin; boolean reversePolarity = false; -}; - -[NoInterfaceObject] +};

interface PWMPin { void setCycles(unsigned long period, unsigned long pulseWidth); void setMilliseconds(double period, double pulseWidth); -}; -``` - -API Documentation ------------------ -### PWM.open +};

+
-`PWMPin open(number or string or PWMInit init);` +PWM API +------- +### pwm.open(init) -If the argument is a number, it is a pin channel number. If it is a string, it -is a pin name. Otherwise, it must be a `PWMInit` object. +* `init` *long of string or PWMInit* A numerical argument indicates +a pin channel number. If the argument is a string, it is a pin +name. Otherwise, it must be a `PWMInit` object. +* Returns: a PWMPin object that can be used to set the period and +pulse width. -The `init` object lets you set the pin channel number with the `pin` property. -You can use a pin name like "PWM_0.2" where "PWM_0" is the name of a Zephyr -pwm controller device for your board and 210 is the pin/channel number. This -will work on any board as long as you find the right values in Zephyr -documentation. But for boards with specific ZJS support, you can use friendly -names. Currently this means Arduino 101 and FRDM-K64F. +The `init` object lets you set the pin channel number with the `pin` +property. You can use a pin name like "PWM_0.2", where "PWM_0" is the +name of a Zephyr pwm controller device for your board and 210 is the +pin/channel number. This will work on any board as long as you find +the right values in the Zephyr documentation. For boards with specific +ZJS support (currently: Arduino 101 and FRDM-K64F), you can use +friendly names. *Arduino 101* -For the A101, you can use numbers 0-3 or strings "PWM0" through "PWM3", or the +For the A101, you can use numbers 0-3, strings "PWM0" through "PWM3", or the corresponding digital pin names "IO3", "IO5", "IO6", and "IO9". *FRDM-K64F* -For the K64F, you can use numbers 0-11 or strings "D3", "D5" through "D13", -"A4" and "A5". +For the K64F, you can use numbers 0-11, strings "D3", "D5" through "D13", +and "A4" and "A5". -The term 'channel' is used to refer to the fact that PWM controller hardware has -multiple channels, but these are connected to output pins so as the user of the -hardware you will think of them as pins. +The term 'channel' refers to multiple channels on the PWM controller +hardware, but these are connected to output pins, so the hardware user +should think of them as pins. The `reversePolarity` value should flip the signal if set to 'reverse', meaning -the signal will be off (low) for the pulseWidth, and back on (high) for the +the signal will be off (low) for the pulseWidth, and on (high) for the rest of the period. -The function returns a PWMPin object that can be used to set the period and -pulse width. +PWMPin API +---------- -### PWMPin.setCycles - -`void setCycles(unsigned long period, unsigned long pulseWidth);` +### pin.setCycles(period, pulseWidth) +* `period` *unsigned long* +* `pulseWidth` *unsigned long* Sets the repeat period and pulse width for the signal, in terms of hardware cycles. One hardware cycle is the minimum amount of time the hardware supports @@ -104,18 +109,19 @@ having the pulse signal on (high). Throws an error if pulseWidth is greater than period. -This version of the API is useful when the duty cycle is what matters (e.g. +This version of the API is useful when the duty cycle is what matters (e.g., using the 'analog' model of PWM control described in the [Introduction](#introduction)). For example, a period of 20 with a pulse width of 10 will make an LED at 50% brightness, with no flicker because the changes occur far faster than visible to the human eye. -### PWMPin.setMilliseconds - -`void setMilliseconds(double periodMS, double pulseWidthMS);` +### pin.setMilliseconds(periodMS, pulseWidthMS) +* `periodMS` *double* Signal repeat period. +* ` pulseWidthMS` *double* Signal pulse width. -Sets the repeat period and pulse width for the signal. It is given in -milliseconds, so these can be fractional to provide microsecond timings, etc. +Sets the repeat period and pulse width for the signal. The values are given in +milliseconds, so these can be fractional to provide microsecond +timings, for example. The actual resolution available will depend on the hardware, so the value you provide may get rounded. *TODO: We could probably have the period attribute show the actual setting for @@ -123,7 +129,7 @@ the device when it is read back.* Throws an error if pulseWidth is greater than period. -This version of the API is useful when the timing of the pulse matters (e.g. +This version of the API is useful when the timing of the pulse matters (e.g., the 'servo' model of PWM control described in the [Introduction](#introduction)). diff --git a/docs/sensors.md b/docs/sensors.md index 2fcb6920f..a77488de2 100644 --- a/docs/sensors.md +++ b/docs/sensors.md @@ -3,30 +3,39 @@ ZJS API for W3C Generic Sensors * [Introduction](#introduction) * [Web IDL](#web-idl) -* [API Documentation](#api-documentation) +* [Class: Sensor](#sensor-api) + * [onreading](#onreading) + * [onactivate](#onactivate) + * [onerror](#onerror) + * [sensor.start()](#sensorstart) + * [sensor.stop()](#sensorstop) * [Sample Apps](#sample-apps) Introduction ------------ ZJS Generic Sensor API implements the W3C Sensor API, and it's intended to provide a consistent API that allows apps to communicate with sensors like -accelerometer and gyroscope. Since the W3C Sensor API is still a draft spec, -our implementation only provide a subset of the API and the API could be -slightly different, but we try to follow the latest spec as closely as +an accelerometer or gyroscope. Since the W3C Sensor API is still a draft spec, +our implementation only provides a subset of the API -- and this API could be +slightly different even though we try to follow the latest spec as closely as possible. -Note: The currently supported hardware is Arduino 101 with its built-in -BMI160 chip with accelerometer, gyroscope, and temperature. The supported -ambient light sensor is the Grove light sensor that comes with the -Grove starter kit, that can be connected using an analog pin. +Note: The currently supported hardware is Arduino 101 that has a +built-in BMI160 chip with accelerometer, gyroscope, and temperature +sensors. The supported ambient light sensor is the Grove light sensor +that comes with the Grove starter kit. The light sensor can be +connected using an analog pin. Web IDL ------- -This IDL provides an overview of the interface; see below for documentation of -specific API functions. -####Sensor Interface -```javascript +This IDL provides an overview of the interface; see below for +documentation of specific API functions. We have a short document +explaining [ZJS WebIDL conventions](Notes_on_WebIDL.md). + +
+Click to show WebIDL +
 interface Sensor {
     readonly attribute boolean activated;   // whether the sensor is activated or not
     readonly attribute boolean hasReading;  // whether the sensor has readings available
@@ -37,73 +46,44 @@ interface Sensor {
     attribute ChangeCallback onreading;     // callback handler for change events
     attribute ActivateCallback onactivate;  // callback handler for activate events
     attribute ErrorCallback onerror;        // callback handler for error events
-};
-
-dictionary SensorOptions {
-    double frequency;  // desire frequency, default is 20 if unset
-};
-
-interface SensorErrorEvent {
+};

dictionary SensorOptions { + double frequency; // desired frequency, default is 20 if unset +};

interface SensorErrorEvent { attribute Error error; -}; - -callback ChangeCallback = void(); +};

callback ChangeCallback = void(); callback ActivateCallback = void(); -callback ErrorCallback = void(SensorErrorEvent error); -``` -####Accelerometer Interface -```javascript -[Constructor(optional AccelerometerOptions accelerometerOptions)] +callback ErrorCallback = void(SensorErrorEvent error);

[Constructor(optional AccelerometerOptions accelerometerOptions)] interface Accelerometer : Sensor { readonly attribute double x; readonly attribute double y; readonly attribute double z; -}; - -dictionary AccelerometerOptions : SensorOptions { +};

dictionary AccelerometerOptions : SensorOptions { string controller; // controller name, default to "bmi160" -}; -``` -####GyroscopeSensor Interface -```javascript -[Constructor(optional SensorOptions sensorOptions)] +};

[Constructor(optional SensorOptions sensorOptions)] interface GyroscopeSensor : Sensor { readonly attribute double x; readonly attribute double y; readonly attribute double z; -}; - +};

dictionary GyroscopeOptions : SensorOptions { string controller; // controller name, default to "bmi160" -}; -``` -####AmbientLightSensor Interface -```javascript +};

[Constructor(optional SensorOptions sensorOptions)] interface AmbientLightSensor : Sensor { readonly attribute unsigned long pin; readonly attribute double illuminance; -}; - -dictionary AmbientLightSensorOptions : SensorOptions { +};

dictionary AmbientLightSensorOptions : SensorOptions { string controller; // controller name, default to "ADC_0" unsigned long pin; // analog pin where the light is connected -}; -``` -####TemperatureSensor Interface -```javascript -[Constructor(optional SensorOptions sensorOptions)] +};

[Constructor(optional SensorOptions sensorOptions)] interface TemperatureSensor : Sensor { readonly attribute double celsius; -}; - -dictionary TemperatureSensorOptions : SensorOptions { +};

dictionary TemperatureSensorOptions : SensorOptions { string controller; // controller name, default to "bmi160" -}; -``` +};

-API Documentation ------------------ +Sensor API +---------- ### onreading `Sensor.onreading` @@ -120,13 +100,11 @@ The onactivate attribute is an EventHandler which is called when the sensor is a The onactivate attribute is an EventHandler which is called whenever an exception cannot be handled synchronously. -### start -`void Sensor.start()` +### sensor.start() Starts the sensor instance, the sensor will get callback on onreading whenever there's a new reading available. -### stop -`void Sensor.stop()` +### sensor.stop() Stop the sensor instance, the sensor will stop reporting new readings. diff --git a/docs/spi.md b/docs/spi.md index 8c8544bdf..90fc3515e 100644 --- a/docs/spi.md +++ b/docs/spi.md @@ -3,89 +3,93 @@ ZJS API for SPI * [Introduction](#introduction) * [Web IDL](#web-idl) -* [API Documentation](#api-documentation) -* [Sample Apps](#sample-apps) +* [SPI API](#spi-api) + * [spi.open(options)](#spiopenoptions) +* [SPIBus API](#spibus-api) + * [spiBus.transceive(target, data, direction)](#spibustransceivetarget-data-direction) + * [spiBus.close()](#spibusclose) Introduction ------------ The SPI API supports the Serial Peripheral Interface, a synchronous -serial protocol that allows multiple slave chips to communicate with a master chip. -A single SPI bus uses the following pins: SCLK for clock, -MOSI (Master Out, Slave In) for write, MISO (Master In, Slave Out) for read, and -one or more SS (Slave Select) for selecting the slave device. - -For each clock signal one bit is written from the master to the selected slave and -one bit is read by the master from the selected slave, so there is no separate -read and write, but one transceive operation. - -When a slave device's chip select is 0 (low), then it communicates with the -master, otherwise it ignores the master. The master can select multiple slaves in -a write-only configuration; in this case no slave is writing data, they only read. - -Since the SS pins may be connected to slave chip select through a demultiplexer -and thereby work as an address bus, slave devices are identified by an index in -this API, rather than by SS pins. Also, since multiple SPI buses may be present -on a board, these are identified by an index in this API. Implementations SHOULD -encapsulate the mapping from SPI bus number and device number to the physical SPI +serial protocol that allows multiple slave chips to communicate with a +master chip. A single SPI bus uses the following pins: SCLK for +clock, MOSI (Master Out, Slave In) for write, MISO (Master In, Slave +Out) for read, and one or more SS (Slave Select) for selecting the +slave device. + +For each clock signal, one bit is written from the master to the +selected slave, and one bit is read by the master from the selected +slave, so there is one transceive operation, instead of a separate +read and write. + +When a slave device's chip select is 0 (low), it communicates with the +master; otherwise it ignores the master. The master can select +multiple slaves in a write-only configuration; in this case, no slave +is writing data, each only reads. + +Since the SS pins may be connected to slave chip select through a +demultiplexer and thereby work as an address bus, slave devices are +identified by an index in this API, rather than by SS pins. Also, +since multiple SPI buses may be present on a board, these are +identified by an index in this API. Implementations SHOULD encapsulate +the mapping from SPI bus number and device number to the physical SPI pins. -Note that on the Arduino 101, using SPI will cause one of the onboard LED to +Note that on the Arduino 101, using SPI will cause one of the onboard LEDs to become unavailable. Web IDL ------- -This IDL provides an overview of the interface; see below for documentation of -specific API functions. - -```javascript -// require returns a SPI object -// var spi = require('spi'); - -[NoInterfaceObject] +This IDL provides an overview of the interface; see below for +documentation of specific API functions. We have a short document +explaining [ZJS WebIDL conventions](Notes_on_WebIDL.md). + +
+Click to show WebIDL +
// require returns a SPI object
+// var spi = require('spi');

[ReturnFromRequire] interface SPI { SPIBus open(SPIOptions init); -}; - -dictionary SPIOptions { +};

dictionary SPIOptions { octet bus; long speed; // bus clock frequency in Hz - bool msbFirst; + boolean msbFirst; long polarity; long phase; unsigned long frameGap; string topology; - -}; - -[NoInterfaceObject] +};

[ExternalInterface=(buffer,Buffer)] interface SPIBus { - transceive(octet target, Buffer data, string direction); + void transceive(octet target, Buffer data, string direction); close(); }; -``` - -API Documentation ------------------ -### SPI.open - -`SPIBus open(SPIOptions options);` +

+
-The `options` object lets you pass optional values to use instead of the defaults. -Note these values can't be changed once the SPI object is created. If you need -to change the settings afterwards, you'll need to use the 'close' command and -create a new SPI object with the settings you desire. - -### SPIBus.transceive - -`Buffer transceive(octet target, Buffer data, string direction);` +SPI API +------- +### spi.open(options) +* `options` *SPIOptions* The `options` object lets you pass optional values to use instead of the defaults. +* Returns: an SPIBus object. + +Note these `options` values can't be changed once the SPI object is +created. If you need to change the settings afterwards, you'll need +to use the 'close' command and create a new SPI object with the +settings you desire. + +SPIBus API +---------- +### spiBus.transceive(target, data, direction) +* `target` *octet* The number identifying the slave. +* `data` *Buffer* The data to be written to, and returned from, the slave. +* `direction` *string* Writes data buffer using SPI to the slave identified by the target argument, and reads from the slave device into a readBuffer that is returned. The read and write buffers are the same size. -### SPIBus.close - -`void close();` +### spiBus.close() Closes the SPI connection. diff --git a/docs/timers.md b/docs/timers.md index 250458153..0bdf32b16 100644 --- a/docs/timers.md +++ b/docs/timers.md @@ -3,7 +3,11 @@ ZJS API for Timers * [Introduction](#introduction) * [Web IDL](#web-idl) -* [API Documentation](#api-documentation) +* [Class: Timers](#timers-api) + * [timers.setInterval(func, delay, args_for_func)](#timerssetintervalfunc-delay-args_for_func) + * [timers.setTimeout(func, delay, args_for_func)](#timerssettimeoutfunc-delay-args_for_func) + * [timers.clearInterval(intervalID)](#timersclearintervalintervalid) + * [timers.clearTimeout(timeoutID)](#timerscleartimeouttimeoutid) * [Sample Apps](#sample-apps) Introduction @@ -13,70 +17,56 @@ available. Web IDL ------- -This IDL provides an overview of the interface; see below for documentation of -specific API functions. - -```javascript -intervalID setInterval(TimerCallback func, unsigned long delay, optional arg1, ...); -timeoutID setTimeout(TimerCallback func, unsigned long delay, optional arg1, ...); -void clearInterval(intervalID); -void clearTimeout(timeoutID); - -callback TimerCallback = void (optional arg1, ...); -``` - -API Documentation ------------------ -### setInterval - -`intervalID setInterval(TimerCallback func, unsigned long delay, optional arg1, ...); -` - -The `func` argument is a callback function that should expect whatever arguments -you pass as arg1, arg2, and so on. - -The `delay` argument is in milliseconds. Currently, the delay resolution is -about 10 milliseconds and if you choose a value less than that it will probably -fail. - -Any additional arguments such as `arg1` will be passed to the callback you -provide. They can be whatever type you wish. - -Every `delay` milliseconds, your callback function will be called. An -`intervalID` will be returned that you can save and pass to clearInterval later -to stop the timer. - -### setTimeout - -`timeoutID setTimeout(TimerCallback func, unsigned long delay, optional arg1, ...);` - -The `func` argument is a callback function that should expect whatever arguments -you pass as arg1, arg2, and so on. - -The `delay` argument is in milliseconds. Currently, the delay resolution is -about 10 milliseconds. - -Any additional arguments such as `arg1` will be passed to the callback you -provide. They can be whatever type you wish. - -After `delay` milliseconds, your callback function will be called *one time*. A -`timeoutID` will be returned that you can save and pass to clearTimeout later -to stop the timer. - -### clearInterval - -`void clearInterval(intervalID);` - -The `intervalID` should be what was returned from a previous call to -`setInterval`. That interval timer will be cleared and its callback function +This IDL provides an overview of the interface; see below for +documentation of specific API functions. We have a short document +explaining [ZJS WebIDL conventions](Notes_on_WebIDL.md). + +
+Click to show WebIDL +
+// require returns a Timers object
+// var timers = require('timers');
+

+[ReturnFromRequire] +interface Timers { + intervalID setInterval(TimerCallback func, unsigned long delay, any... args_for_func); + timeoutID setTimeout(TimerCallback func, unsigned long delay, any... args_for_func); + void clearInterval(long intervalID); + void clearTimeout(long timeoutID); +};

+callback TimerCallback = void (any... callback_args);

+

+typedef timeoutID long; +

+ +Timers API +---------- +### timers.setInterval(func, delay, args_for_func) +* `func` *TimerCallback* A callback function that will take the arguments passed in the variadic `args_for_func` parameter. +* `delay` *unsigned long* The `delay` argument is in milliseconds. Currently, the delay resolution is about 10 milliseconds, and if you choose a value less than that it will probably fail. +* `args_for_func` *any* The user can pass an arbitrary number of additional arguments that will then be passed to `func`. +* Returns: an `intervalID` object that can be passed to `clearInterval` to stop the timer. + +Every `delay` milliseconds, your callback function will be called. + +### timers.setTimeout(func, delay, args_for_func) +* `func` *TimerCallback* A callback function that will take the arguments passed in the variadic `args_for_func` parameter. +* `delay` *unsigned long* The `delay` argument is in milliseconds. Currently, the delay resolution is about 10 milliseconds. +* `args_for_func` *any* The user can pass an arbitrary number of additional arguments that will then be passed to `func`. +* Returns: a `timeoutID` that can be passed to `clearTimeout` to stop the timer. + +After `delay` milliseconds, your callback function will be called *one time*. + +### timers.clearInterval(intervalID) +* `intervalID` *long* This value was returned from a call to `setInterval`. + +That interval timer will be cleared and its callback function no longer called. -### clearTimeout - -`void clearTimeout(timeoutID);` +### timers.clearTimeout(timeoutID) +* `timeoutID` *long* This value was returned from a call to `setTimeout`. -The `timeoutID` should be what was returned from a previous call to -`setTimeout`. That timer will be cleared and its callback function will not be +The `timeoutID` timer will be cleared and its callback function will not be called. Sample Apps diff --git a/docs/uart.md b/docs/uart.md index 4a201703c..95a24f713 100644 --- a/docs/uart.md +++ b/docs/uart.md @@ -3,13 +3,17 @@ Zephyr.js API for UART * [Introduction](#introduction) * [Web IDL](#web-idl) -* [API Documentation](#api-documentation) -* [Sample Apps](#sample-apps) +* [Class UART](#uart-api) + * [uart.init(options)](#uartinitoptions) +* [UARTConnection API](#uartconnection-api) + * [Event: 'read'](#event-read) + * [uartConnection.write(data)](#uartconnectionwritedata) + * [uartConnection.setReadRange(min, max)](#uartconnectionsetreadrangemin-max) Introduction ------------ -The UART module supports both read and write capabilities. Write is achieved -with a 'write' function, and read is done via a callback function property that +The UART module supports both read and write capabilities. Writes are +done through the 'write' function, and reads are done via a callback function property that can be set. Read and write data should be a JavaScript string. The module can be used on both QEMU and the Arduino 101. When using QEMU, you @@ -18,69 +22,59 @@ read/written from the serial console just as print does. Web IDL ------- -This IDL provides an overview of the interface; see below for documentation of -specific API functions. Commented out properties or functions are not -implemented because the feature is not available on Zephyr. - -```javascript -// require returns a UART object -// var uart = require('uart'); - -enum UARTParity { "none", "event", "odd" } - -interface UART { +This IDL provides an overview of the interface; see below for +documentation of specific API functions. We have a short document +explaining [ZJS WebIDL conventions](Notes_on_WebIDL.md). + +
+Click to show WebIDL +
// require returns a UART object
+// var uart = require('uart');

interface UART { UARTConnection init(UARTOptions options); -}; - -dictionary UARTOptions { +};

dictionary UARTOptions { string port; - // number baud = 115200; - // number dataBits = 8; - // number stopBits = 1; + // long baud = 115200; + // long dataBits = 8; + // long stopBits = 1; // UARTParity parity = "none"; // boolean flowControl = false; -}; - -[NoInterfaceObject] +};

[ExternalInterface=(buffer,Buffer),ExternalInterface=(eventemitter, EventEmitter)] interface UARTConnection: EventEmitter { // void close(); void write(Buffer data); - void setReadRange(number min, number max); -}; -``` + void setReadRange(long min, long max); +};

enum UARTParity { "none", "event", "odd" }; +

+
-API Documentation ------------------ -## UART interface +UART API +-------- +### uart.init(options) +* `options` *UARTOptions* The `UARTOptions` object lets you choose the + UART device/port you would like to initialize. The Arduino 101, for + example, should be "tty0". +* Returns: UARTConnection interface, described below. -### UART.init +UARTConnection API +------------------ -`UARTConnection init(UARTOptions options);` - -The `options` object lets you choose the UART device/port you would like to -initialize. The Arduino 101, for example, should be "tty0". - -## UARTConnection interface -UARTConnection is an [EventEmitter](./events.md) with the following events: +A UARTConnection is an [EventEmitter](./events.md) with the following events: ### Event: 'read' - * `Buffer` `data` Emitted when data is received on the UART RX line. The `data` parameter is a `Buffer` with the received data. -### UARTConnection.write - -`void write(Buffer data);` - -Write data out to the UART TX line. `data` is a string that will be written. +### uartConnection.write(data) +* `data` *Buffer* The data to be written. -### UARTConnection.setReadRange +Write data out to the UART TX line. -`void setReadRange(number min, number max);` +### uartConnection.setReadRange(min, max);` +* `min` *long* The minimum number of bytes for triggering the `onread` event. +* `max` *long* The maximum number of bytes for triggering the `onread` event. -Set the minimum and maximum number of bytes for triggering the `onread` event. Whenever at least the `min` number of bytes is available, a `Buffer` object containing at most `max` number of bytes is sent with the `onread` event. diff --git a/docs/web-socket.md b/docs/web-socket.md index f3fc58cd1..849715def 100644 --- a/docs/web-socket.md +++ b/docs/web-socket.md @@ -3,47 +3,58 @@ ZJS API for Web Sockets * [Introduction](#introduction) * [Web IDL](#web-idl) -* [API Documentation](#api-documentation) +* [WebSocket API](#websocket-api) + * [ws.Server(options)](#wsserveroptions) +* [WebSocketServer API](#websocketserver-api) + * [Event: 'connection'](#event-connection) +* [WebSocket API](#websocket-api) + * [Event: 'close'](#event-close) + * [Event: 'error'](#event-error) + * [Event: 'message'](#event-message) + * [Event: 'ping'](#event-ping) + * [Event: 'pong'](#event-pong) +* [WebSocketConnection API](#websocketconnection-api) + * [webSocketConnection.send(data, mask)](#websocketconnectionsenddata-mask) + * [webSocketConnection.ping(data, mask)](#websocketconnectionpingdata-mask) + * [webSocketConnection.pong(data, mask)](#websocketconnectionpongdata-mask) * [Sample Apps](#sample-apps) Introduction ------------ The Web Socket API is modeled after Node.js' 'ws' module. This module only -supports the Web Socket server portion of the API. +supports the Web Socket server portion of that API. Web IDL ------- -This IDL provides an overview of the interface; see below for documentation of -specific API functions. - -```javascript -// require returns a WebSocket object -// var ws = require('ws'); - +This IDL provides an overview of the interface; see below for +documentation of specific API functions. We have a short document +explaining [ZJS WebIDL conventions](Notes_on_WebIDL.md). + +
+Click to show WebIDL +
// require returns a WebSocket object
+// var ws = require('ws');

[ReturnFromRequire] interface WebSocket { - WebSocketServer Server(Object options); -}; - -interface WebSocketServer: EventEmitter; - + WebSocketServer Server(object options); +};

[ExternalInterface=(eventemitter, EventEmitter)]interface WebSocketServer: EventEmitter{};

[ExternalInterface=(buffer,Buffer),] interface WebSocketConnection: EventEmitter { - // WebSocketConnection methods - void send(Buffer data, Boolean mask); - void ping(Buffer data, Boolean mask); - void pong(Buffer data, Boolean mask); -}; -``` + void send(Buffer data, boolean mask); + void ping(Buffer data, boolean mask); + void pong(Buffer data, boolean mask); +};

+
-WebSocket API Documentation ---------------------------- +WebSocket API +------------- -### WebSocket.Server -`WebSocketServer Server(Object options)` +### ws.Server(options) +* `options` *Object* +* Returns: a WebSocketServer object. Create a Web Socket server object. Options object may contain: -WebSocketServer API Documentation ---------------------------------- +WebSocketServer API +------------------- WebSocketServer is [EventEmitter](./events.md) with the following events: @@ -70,10 +81,10 @@ strings from the handler. Returns a `WebSocketServer` object. -WebSocketConnection API Documentation -------------------------------------- +WebSocket API +------------- -WebSocketServer is [EventEmitter](./events.md) with the following events: +WebSocketServer is an [EventEmitter](./events.md) with the following events: ### Event: 'close' @@ -107,29 +118,27 @@ the `data` argument. Emitted when the socket has received a pong. The pong's payload is contained in the `data` argument. -### WebSocketConnection.send - -`void send(Buffer data, Boolean mask)` -Send data to the other end of the web socket connection. The `data` parameter -should contain the data payload to send. The `mask` parameter says whether the -data payload should be masked. +WebSocketConnection API +----------------------- -### WebSocketConnection.ping +### webSocketConnection.send(data, mask) +* `data` *Buffer* The data payload to send. +* `mask` *boolean* Describes whether the data payload should be masked. -`void ping(Buffer data, Boolean mask)` +Send data to the other end of the web socket connection. -Send a ping to the other end of the web socket connection. The `data` parameter -should contain the data payload to send. The `mask` parameter says whether the -data payload should be masked. +### webSocketConnection.ping(data, mask) +* `data` *Buffer* Contains the data payload to send. +* `mask` *boolean* Describes whether the data payload should be masked. -### WebSocketConnection.pong +Send a ping to the other end of the web socket connection. -`void pong(Buffer data, Boolean mask)` +### webSocketConnection.pong(data, mask) +* `data` *Buffer* The data payload to send. +* `mask` *boolean* Describes whether the data payload should be masked. -Send a pong to the other end of the web socket connection. The `data` parameter -should contain the data payload to send. The `mask` parameter says whether the -data payload should be masked. +Send a pong to the other end of the web socket connection. Sample Apps ----------- From 759a697227fecbb586f2f061d4ba3056dea0defc Mon Sep 17 00:00:00 2001 From: Geoff Gustafson Date: Fri, 18 May 2018 12:43:36 -0700 Subject: [PATCH 08/18] [net] Increase multicast addresses so neighbor solicitation will work (#1881) Thanks to Paul Sokolovsky for finding this solution. Signed-off-by: Geoff Gustafson --- src/zjs_dgram.json | 2 +- src/zjs_net.json | 2 +- src/zjs_ws.json | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/zjs_dgram.json b/src/zjs_dgram.json index b86ee02f8..d98c8f6b2 100644 --- a/src/zjs_dgram.json +++ b/src/zjs_dgram.json @@ -18,7 +18,7 @@ "CONFIG_NET_BUF_RX_COUNT=10", "CONFIG_NET_BUF_TX_COUNT=6", "CONFIG_NET_IF_UNICAST_IPV6_ADDR_COUNT=3", - "CONFIG_NET_IF_MCAST_IPV6_ADDR_COUNT=2", + "CONFIG_NET_IF_MCAST_IPV6_ADDR_COUNT=4", "CONFIG_NET_MAX_CONTEXTS=10", "CONFIG_NET_MGMT=y", "CONFIG_NET_MGMT_EVENT=y" diff --git a/src/zjs_net.json b/src/zjs_net.json index e9e021893..dc94bc6be 100644 --- a/src/zjs_net.json +++ b/src/zjs_net.json @@ -20,7 +20,7 @@ "CONFIG_NET_BUF_RX_COUNT=10", "CONFIG_NET_BUF_TX_COUNT=6", "CONFIG_NET_IF_UNICAST_IPV6_ADDR_COUNT=3", - "CONFIG_NET_IF_MCAST_IPV6_ADDR_COUNT=2", + "CONFIG_NET_IF_MCAST_IPV6_ADDR_COUNT=4", "CONFIG_NET_MAX_CONTEXTS=10", "CONFIG_NET_MGMT=y", "CONFIG_NET_MGMT_EVENT=y" diff --git a/src/zjs_ws.json b/src/zjs_ws.json index f1969e14d..bc4682d9d 100644 --- a/src/zjs_ws.json +++ b/src/zjs_ws.json @@ -20,7 +20,7 @@ "CONFIG_NET_BUF_TX_COUNT=6", "CONFIG_NET_BUF_DATA_SIZE=512", "CONFIG_NET_IF_UNICAST_IPV6_ADDR_COUNT=3", - "CONFIG_NET_IF_MCAST_IPV6_ADDR_COUNT=2", + "CONFIG_NET_IF_MCAST_IPV6_ADDR_COUNT=4", "CONFIG_NET_MAX_CONTEXTS=10", "CONFIG_NET_MGMT=y", "CONFIG_NET_MGMT_EVENT=y", From c5b0176b8eca591e7eb8beffa4c446752624b0af Mon Sep 17 00:00:00 2001 From: Jimmy Huang Date: Thu, 1 Feb 2018 10:54:42 -0800 Subject: [PATCH 09/18] [debugger] Added debugger support for Zephyr Created shim layer for building against the POSIX network stack on Zephyr which enables the debugger to run on the frdm_k64f board with TCP IPV4 on port 5001. Signed-off-by: Jimmy Huang --- Makefile | 20 ++++++++++++-- README.md | 47 ++++++++++++++++++++++++++++----- cmake/jerry.cmake | 22 +++++++++++---- cmake/zjs.cmake | 45 ++++++++++++++++++++----------- cmake/zjs_linux.cmake | 19 ++++++++----- scripts/convert.py | 19 ++++++++++--- scripts/trlite | 8 ++++++ src/jerry-port/arpa/inet.h | 20 ++++++++++++++ src/jerry-port/zjs_jerry_port.c | 37 +++++++++++++++++++------- src/main.c | 12 ++++++--- src/zjs_common.h | 6 ----- src/zjs_console.c | 19 +++++++++++++ src/zjs_debugger.json | 34 ++++++++++++++++++++++++ tools/Makefile.snapshot | 2 +- 14 files changed, 250 insertions(+), 60 deletions(-) create mode 100644 src/jerry-port/arpa/inet.h create mode 100644 src/zjs_debugger.json diff --git a/Makefile b/Makefile index b99ea2b1f..853420b6f 100644 --- a/Makefile +++ b/Makefile @@ -10,6 +10,7 @@ OS := $(shell uname) BOARD ?= arduino_101 +SCRIPT_SIZE ?= 8192 RAM ?= 64 ROM ?= 144 V ?= 0 @@ -37,9 +38,11 @@ $(error ZJS_BASE not defined. You need to source zjs-env.sh) endif ifeq ($(DEBUGGER), on) -ifneq ($(BOARD), linux) -$(error Debugger only runs on linux, set BOARD=linux) +ifneq (,$(filter $(MAKECMDGOALS), linux arduino_101)) +$(error Debugger only runs on linux and arduino_101) endif +# debugger requires unminimized JS which will require much a larger script size +SCRIPT_SIZE = 16384 ifneq ($(SNAPSHOT), on) $(warning Debugger on, disabling snapshot) SNAPSHOT=off @@ -120,6 +123,8 @@ else SNAPSHOT ?= on endif +ZJS_FLAGS += -DMAX_SCRIPT_SIZE=$(SCRIPT_SIZE) + ifeq ($(FUNC_NAME), on) ZJS_FLAGS += -DZJS_FIND_FUNC_NAME endif @@ -130,6 +135,11 @@ else FORCED := $(FORCE),zjs_common.json endif +ifeq ($(DEBUGGER), on) +# debugger will require networking support +FORCED := $(FORCED),zjs_debugger.json +endif + # Settings for ashell builds ifneq (,$(filter $(MAKECMDGOALS),ide ashell)) ASHELL=zjs_ashell_$(ASHELL_TYPE).json @@ -308,6 +318,7 @@ analyze: $(JS) -DBLE_ADDR=$(BLE_ADDR) \ -DBOARD=$(BOARD) \ -DCB_STATS=$(CB_STATS) \ + -DDEBUGGER=$(DEBUGGER) \ -DJERRY_BASE=$(JERRY_BASE) \ -DJERRY_OUTPUT=$(JERRY_OUTPUT) \ -DJERRY_PROFILE=$(OUT)/$(BOARD)/jerry_feature.profile \ @@ -389,10 +400,14 @@ else @echo Creating C string from JS application... ifeq ($(BOARD), linux) @./scripts/convert.py $(JS) $(OUT)/include/zjs_script_gen.h +else +ifeq ($(DEBUGGER), on) + @./scripts/convert.py --full $(OUT)/$(JS_TMP) $(OUT)/include/zjs_script_gen.h else @./scripts/convert.py $(OUT)/$(JS_TMP) $(OUT)/include/zjs_script_gen.h endif endif +endif # Run QEMU target .PHONY: qemu @@ -466,6 +481,7 @@ linux: generate -DDEBUGGER=$(DEBUGGER) \ -DV=$(V) \ -DVARIANT=$(VARIANT) \ + -DZJS_FLAGS="$(ZJS_FLAGS)" \ -H. && \ make -C $(OUT)/linux; diff --git a/README.md b/README.md index ab0127c28..b1d50594a 100644 --- a/README.md +++ b/README.md @@ -282,12 +282,48 @@ breakpoints such as `b main` and `run` to start debugging as usual with gdb. ##### Debugging JavaScript code JerryScript has a built-in remote debugger which allows debugging JavaScript programs. At the moment only a Websocket-based implementation is provided by -JerryScript which transmits messages over TCP/IP networks. This implementation -requires a socket API which currently only work when running on Linux. The -socket API is not yet supported with NewLib when building with Zephyr natively. +JerryScript which transmits messages over TCP/IP networks, but it currently +only supports ethernet, so you'll need to run it on a board that has ethernet +support, for example, the FRDM-K64F or Linux. To enable the remote debugger for a particular JS application: ```bash +make BOARD=frdm_k64f DEBUGGER=on JS=xxx.js +``` + +When you flash and run the JS application, it will start in debugging mode, +running on 192.168.1.101:5001, and you will see the following on serial output: + +```bash +Debugger mode: connect using jerry-client-ws.py + +Waiting for client connection +``` +you might need to add a route on your PC to connect to the network if you +are connecting the board directly to your PC: + +```bash +ip route add 192.168.1/24 dev eno1 +``` + +Then you can use the jerryscript command line or html client to connect to the +debugger to debug your JS application: + +python jerryscript/jerry-debugger/jerry-client-ws.py --display 10 192.168.1.1 + +In the client, type 'help' to get a list of debugger commands, such as +adding breakpoints, stepping through JS sources, etc. + +Alternatively, we've created a client that integrates with Chome DevTools, +which lets you use the Chrome's built-in debugger to connect and you can +use it to set breakpoints and step through source from all within the browser. +Please see installation instructions on how to set it up from +[here](https://github.com/jerryscript-project/jerryscript-debugger-ts) + +##### Debugging JavaScript code on Linux: + +To enable the remote debugger on Linux: +```bash make BOARD=linux DEBUGGER=on outdir/linux/release/jslinux app.js --debugger ``` @@ -296,12 +332,9 @@ It will then be run on debugger mode waiting for client connection, you can then in another terminal, you can connect to it by running the python client in JerryScript: ```bash -jerry-debugger/jerry-client-ws.py +python jerryscript/jerry-debugger/jerry-client-ws.py --display 10 localhost ``` -In the client, type 'help' to get a list of debugger commands, such as -adding breakpoints, stepping through JS sources, etc. - #### Additional details See below for a few more tips, such as increasing the space available for your diff --git a/cmake/jerry.cmake b/cmake/jerry.cmake index a504c4e5e..20ae4c3a9 100644 --- a/cmake/jerry.cmake +++ b/cmake/jerry.cmake @@ -4,12 +4,16 @@ include(ExternalProject) # Additional build flags to work around JerryScript warnings set(jerry_cflags " \ - -Wall \ - -Werror \ -Wno-conversion \ -Wno-implicit-function-declaration \ -Wno-old-style-declaration \ - -Wno-undef" + -Wno-pedantic \ + -Wno-shadow \ + -Wno-sign-compare \ + -Wno-sign-conversion \ + -Wno-undef \ + -Wno-unused-parameter \ + -Wno-unused-variable" ) zephyr_get_include_directories_for_lang_as_string(C includes) @@ -17,8 +21,15 @@ zephyr_get_system_include_directories_for_lang_as_string(C system_includes) zephyr_get_compile_definitions_for_lang_as_string(C definitions) zephyr_get_compile_options_for_lang_as_string(C options) +# include the shim layer that ports the network API to build on Zephyr +if("${DEBUGGER}" STREQUAL "on") + set(net_includes + "-I${CMAKE_SOURCE_DIR}/src/jerry-port" + ) +endif() + set(external_project_cflags - "${includes} ${definitions} ${options} ${system_includes}${jerry_cflags}" + "${includes} ${definitions} ${options} ${system_includes} ${jerry_cflags} ${net_includes}" ) if("${SNAPSHOT}" STREQUAL "on") @@ -33,10 +44,11 @@ set(CMAKE_ARGS -DCMAKE_C_COMPILER=${CMAKE_C_COMPILER} -DCMAKE_C_COMPILER_WORKS=TRUE -DCMAKE_SYSTEM_NAME=Zephyr - -DENABLE_ALL_IN_ONE=${ALL_IN_ONE} + -DENABLE_ALL_IN_ONE=OFF -DENABLE_LTO=OFF -DEXTERNAL_COMPILE_FLAGS=${external_project_cflags} -DFEATURE_ERROR_MESSAGES=ON + -DFEATURE_DEBUGGER=${DEBUGGER} -DFEATURE_INIT_FINI=ON -DFEATURE_PROFILE=${JERRY_PROFILE} -DFEATURE_SNAPSHOT_EXEC=OFF diff --git a/cmake/zjs.cmake b/cmake/zjs.cmake index 3b7ba241e..953b95d20 100644 --- a/cmake/zjs.cmake +++ b/cmake/zjs.cmake @@ -56,22 +56,35 @@ target_compile_options(app PRIVATE -Wno-implicit-function-declaration ) -target_include_directories(app PRIVATE ./src) -target_include_directories(app PRIVATE ${ZEPHYR_BASE}/drivers) -target_include_directories(app PRIVATE ${JERRY_BASE}/jerry-core/include) -target_include_directories(app PRIVATE ${JERRY_BASE}/jerry-core/jrt) -target_include_directories(app PRIVATE ${JERRY_BASE}/jerry-ext/include) -target_include_directories(app PRIVATE ${CMAKE_BINARY_DIR}/../include) - -target_sources(app PRIVATE src/main.c) -target_sources(app PRIVATE src/zjs_callbacks.c) -target_sources(app PRIVATE src/zjs_common.c) -target_sources(app PRIVATE src/zjs_error.c) -target_sources(app PRIVATE src/zjs_modules.c) -target_sources(app PRIVATE src/zjs_script.c) -target_sources(app PRIVATE src/zjs_timers.c) -target_sources(app PRIVATE src/zjs_util.c) -target_sources(app PRIVATE src/jerry-port/zjs_jerry_port.c) +set(APP_INCLUDES + ./src + ${ZEPHYR_BASE}/drivers + ${JERRY_BASE}/jerry-core/include + ${JERRY_BASE}/jerry-core/jrt + ${JERRY_BASE}/jerry-ext/include + ${CMAKE_BINARY_DIR}/../include + ) + +set(APP_SRC + src/main.c + src/zjs_callbacks.c + src/zjs_common.c + src/zjs_error.c + src/zjs_modules.c + src/zjs_script.c + src/zjs_timers.c + src/zjs_util.c + src/jerry-port/zjs_jerry_port.c + ) + +if("${DEBUGGER}" STREQUAL "on") + add_definitions(-DJERRY_DEBUGGER) + add_definitions(-DZJS_DEBUGGER) +endif() + +target_include_directories(app PRIVATE ${APP_INCLUDES}) + +target_sources(app PRIVATE ${APP_SRC}) target_link_libraries(app jerry-core jerry-ext) diff --git a/cmake/zjs_linux.cmake b/cmake/zjs_linux.cmake index 21314ef02..3fe4a929e 100644 --- a/cmake/zjs_linux.cmake +++ b/cmake/zjs_linux.cmake @@ -77,12 +77,8 @@ set(APP_COMPILE_OPTIONS -std=gnu99 ) -if(CB_STATS) - add_definitions(-DCB_STATS=${CB_STATS}) -endif() - -if(DEBUGGER) - add_definitions(-DZJS_DEBUGGER=${ZJS_DEBUGGER}) +if("${CB_STATS}" STREQUAL "on") + add_definitions(-DZJS_PRINT_CALLBACK_STATS) endif() if("${VARIANT}" STREQUAL "debug") @@ -141,6 +137,17 @@ if(NOT APPLE) # these flags are needed to get rid of warnings in iotivity-constrained list(APPEND APP_COMPILE_OPTIONS -Wno-pointer-sign) + + if("${DEBUGGER}" STREQUAL "on") + list(APPEND APP_INCLUDES + ${JERRY_BASE}/jerry-core/debugger + ${JERRY_BASE}/jerry-core/ecma/base + ${JERRY_BASE}/jerry-core/jmem + ${JERRY_BASE}/jerry-core/lit + ) + add_definitions(-DJERRY_DEBUGGER) + add_definitions(-DZJS_DEBUGGER) + endif() endif() # build libjerry as a static library diff --git a/scripts/convert.py b/scripts/convert.py index 284e667ba..df40f8b49 100755 --- a/scripts/convert.py +++ b/scripts/convert.py @@ -20,10 +20,18 @@ def main(): args = parse_args() - minified_result = uglifyjs(args.input) + minified_result = None + if not args.full: + minified_result = uglifyjs(args.input) + if minified_result == None: + # full JS or couldn't uglify the JS, + # return content of the file as is + fp = open(str(args.input), "r") + content = fp.read() + fp.close() + minified_result = Uglify(content, False) write_minified(args.output, minified_result) - def write_minified(output_path, minified_result): """Write the minified output, escaping things as necessary @@ -61,6 +69,7 @@ def uglifyjs(input_path): :param input_path: A pathlib.Path() object of the input file. :returns: An Uglify() object """ + filename = str(input_path) # NOTE(jlvillal): The docs say that '-nc' is the same as '--no-copyright' # but in testing it is not. @@ -73,8 +82,8 @@ def uglifyjs(input_path): try: result = subprocess.call(cmd_line, stdout=subprocess.DEVNULL) except FileNotFoundError: - # We don't have uglifyjs, so return the contents of the file - return Uglify(input_path.read_text(), False) + # We don't have uglifyjs + return None if result == 0: # We have newer uglifyjs @@ -96,6 +105,8 @@ def parse_args(): "a C string format.")) parser.add_argument("input", metavar='INPUT_FILE') parser.add_argument("output", metavar='OUTPUT_FILE') + parser.add_argument("-f", "--full", help="Skip minimizing JS for debugging", + action="store_true") args = parser.parse_args() # Make all paths absolute and expand any "~/" usage. for arg_name in ('input', 'output'): diff --git a/scripts/trlite b/scripts/trlite index 7691ee205..cd68116a7 100755 --- a/scripts/trlite +++ b/scripts/trlite @@ -332,6 +332,11 @@ if [ "$RUN" == "all" -o "$RUN" == "2" ]; then write_modules_test $TMPFILE $MODULES $SENSORS try_command "k64f net" make $VERBOSE JS=$TMPFILE ROM=256 BOARD=frdm_k64f + # debugger test + MODULES=(buffer) + write_modules_test $TMPFILE $MODULE + try_command "k64f debugger" make $VERBOSE JS=$TMPFILE ROM=256 BOARD=frdm_k64f DEBUGGER=on + # OCF test echo "var ocf = require('ocf');" > $TMPFILE echo "var client = ocf.client;" >> $TMPFILE @@ -450,6 +455,9 @@ if [ "$RUN" == "all" -o "$RUN" == "3" ]; then # linux build tests try_command "linux" make $VERBOSE BOARD=linux + # linux debugger tests + try_command "linux debuger" make $VERBOSE BOARD=linux DEBUGGER=on + # linux unit tests try_command "unit tests" ./outdir/linux/release/jslinux --unittest diff --git a/src/jerry-port/arpa/inet.h b/src/jerry-port/arpa/inet.h new file mode 100644 index 000000000..1e4ff1517 --- /dev/null +++ b/src/jerry-port/arpa/inet.h @@ -0,0 +1,20 @@ +// Copyright (c) 2018, Intel Corporation. + +// Zephyr network stack port +// JerryScript debugger includes but Zephyr has different headers + +#include +#include + +#define SOL_SOCKET (1) +#define SO_REUSEADDR (201) + +#define setsockopt(sd, level, optname, optval, optlen) 0 + +char addr_str[NET_IPV4_ADDR_LEN]; + +#define socket(domain, type, protocol) socket(domain, type, IPPROTO_TCP) + +inline char *inet_ntoa (struct in_addr addr) { + return net_addr_ntop(AF_INET, &addr, addr_str, sizeof(addr_str)); +} diff --git a/src/jerry-port/zjs_jerry_port.c b/src/jerry-port/zjs_jerry_port.c index eaf59e091..a81432aee 100644 --- a/src/jerry-port/zjs_jerry_port.c +++ b/src/jerry-port/zjs_jerry_port.c @@ -4,6 +4,11 @@ #include "jerryscript-port.h" #include +#ifdef ZJS_LINUX_BUILD +#include +#else +#include +#endif // Stubbed out functions for jerry-port features @@ -24,19 +29,31 @@ void jerry_port_fatal(jerry_fatal_code_t code) while (1) {}; } -void jerry_port_console(const char *fmat, ...) +void jerry_port_console(const char *format, ...) { - va_list va; - va_start(va, fmat); - vprintf(fmat, va); - va_end(va); + va_list args; + va_start(args, format); + vprintf(format, args); + va_end(args); } -void jerry_port_log(jerry_log_level_t level, const char *fmat, ...) +void jerry_port_log(jerry_log_level_t level, const char *format, ...) { (void)(level); - va_list va; - va_start(va, fmat); - vprintf(fmat, va); - va_end(va); + va_list args; + va_start(args, format); +#ifdef JERRY_DEBUGGER + char buffer[256]; + int length = 0; + length = vsnprintf(buffer, 255, format, args); + buffer[length] = '\0'; + fprintf (stderr, "%s", buffer); + jerry_char_t *jbuffer = (jerry_char_t *)buffer; + jerry_debugger_send_output(jbuffer, + (jerry_size_t)length, + (uint8_t)(level + 2)); +#else /* If jerry-debugger isn't defined, libc is turned on */ + vfprintf(stderr, format, args); +#endif /* JERRY_DEBUGGER */ + va_end(args); } diff --git a/src/main.c b/src/main.c index de363b4f3..7dc2097a7 100644 --- a/src/main.c +++ b/src/main.c @@ -31,6 +31,7 @@ // JerryScript includes #include "jerryscript.h" +#include "jerryscript-port.h" // Platform agnostic modules/headers #include "zjs_callbacks.h" @@ -71,7 +72,12 @@ static bool ashell_mode = false; #endif #ifdef ZJS_DEBUGGER +#ifdef ZJS_LINUX_BUILD +// JS debugging on linux is toggled over cmdline static bool start_debug_server = false; +#else +static bool start_debug_server = true; +#endif static uint16_t debug_port = 5001; #endif @@ -189,6 +195,8 @@ int main(int argc, char *argv[]) char *script = NULL; #else const char *script = NULL; + file_name = "js.tmp"; + file_name_len = strlen("js.tmp"); #endif jerry_value_t code_eval; u32_t script_len = 0; @@ -279,6 +287,7 @@ int main(int argc, char *argv[]) #ifdef ZJS_DEBUGGER if (start_debug_server) { + ZJS_PRINT("Debugger mode: connect using jerry-client-ws.py\n\n"); jerry_debugger_init(debug_port); } #endif @@ -304,9 +313,6 @@ int main(int argc, char *argv[]) #ifdef ZJS_SNAPSHOT_BUILD result = jerry_exec_snapshot(snapshot_bytecode, snapshot_len, false); #else -#ifdef ZJS_DEBUGGER - ZJS_PRINT("Debugger mode: connect using jerry-client-ws.py\n"); -#endif result = jerry_run(code_eval); #endif diff --git a/src/zjs_common.h b/src/zjs_common.h index 390ba31f2..1386c5eb5 100644 --- a/src/zjs_common.h +++ b/src/zjs_common.h @@ -124,12 +124,6 @@ int zjs_get_ms(void); #define LPRINT(str) do {} while (0) #endif -// TODO: We should instead have a macro that changes in debug vs. release build, -// to save string space and instead print error codes or something for release. - -// this is arbitrary but okay for now; added to avoid plain strlen below -#define MAX_SCRIPT_SIZE 8192 - // board-specific #if defined(CONFIG_BOARD_ARDUINO_101) || defined(CONFIG_BOARD_ARDUINO_101_SSS) #define ADC_DEVICE_NAME "ADC_0" diff --git a/src/zjs_console.c b/src/zjs_console.c index 3548973ce..852c51b18 100644 --- a/src/zjs_console.c +++ b/src/zjs_console.c @@ -12,6 +12,10 @@ #include "zjs_zephyr_port.h" #endif +#ifdef JERRY_DEBUGGER +#include "debugger.h" +#endif + #define MAX_STR_LENGTH 256 #ifdef ZJS_LINUX_BUILD @@ -118,17 +122,29 @@ static void print_value(const jerry_value_t value, FILE *out, bool deep, if (!value2str(value, buf, MAX_STR_LENGTH, quotes) && deep) { if (jerry_value_is_array(value)) { u32_t len = jerry_get_array_length(value); +#ifdef JERRY_DEBUGGER + jerry_debugger_send_output((jerry_char_t *)"[", 1, JERRY_DEBUGGER_OUTPUT_OK); +#endif fprintf(out, "["); for (int i = 0; i < len; i++) { if (i) { +#ifdef JERRY_DEBUGGER + jerry_debugger_send_output((jerry_char_t *)", ", 2, JERRY_DEBUGGER_OUTPUT_OK); +#endif fprintf(out, ", "); } ZVAL element = jerry_get_property_by_index(value, i); print_value(element, out, false, true); } +#ifdef JERRY_DEBUGGER + jerry_debugger_send_output((jerry_char_t *)"]", 1, JERRY_DEBUGGER_OUTPUT_OK); +#endif fprintf(out, "]"); } } else { +#ifdef JERRY_DEBUGGER + jerry_debugger_send_output((jerry_char_t *)buf, strlen(buf), JERRY_DEBUGGER_OUTPUT_OK); +#endif fprintf(out, "%s", buf); } } @@ -138,6 +154,9 @@ static ZJS_DECL_FUNC_ARGS(do_print, FILE *out) for (int i = 0; i < argc; i++) { if (i) { // insert spaces between arguments +#ifdef JERRY_DEBUGGER + jerry_debugger_send_output((jerry_char_t *)" ", 1, JERRY_DEBUGGER_OUTPUT_OK); +#endif fprintf(out, " "); } print_value(argv[i], out, true, false); diff --git a/src/zjs_debugger.json b/src/zjs_debugger.json new file mode 100644 index 000000000..8c753ef77 --- /dev/null +++ b/src/zjs_debugger.json @@ -0,0 +1,34 @@ +{ + "module": "debugger", + "depends": ["net_config_default"], + "virtualdeps": ["net-l2"], + "zephyr_conf": { + "all": [ + "CONFIG_INIT_STACKS=y", + "CONFIG_NETWORKING=y", + "CONFIG_NET_APP_SETTINGS=y", + "CONFIG_NET_IPV4=y", + "CONFIG_NET_IPV6=y", + "CONFIG_NET_TCP=y", + "CONFIG_NET_UDP=y", + "CONFIG_NET_SOCKETS=y", + "CONFIG_NET_SOCKETS_POSIX_NAMES=y", + "CONFIG_NET_STATISTICS=y", + "CONFIG_PRINTK=y", + "CONFIG_TEST_RANDOM_GENERATOR=y" + ], + "frdm_k64f": [ + "CONFIG_NET_APP_NEED_IPV4=y", + "CONFIG_NET_APP_NEED_IPV6=y", + "CONFIG_NET_APP_MY_IPV4_ADDR=\"192.168.1.1\"", + "CONFIG_NET_APP_MY_IPV6_ADDR=\"2001:db8::1\"", + "CONFIG_NET_MAX_CONTEXTS=10" + ] + }, + "zjs_config": [ + "-I${JERRY_BASE}/jerry-core/ecma/base", + "-I${JERRY_BASE}/jerry-core/jmem", + "-I${JERRY_BASE}/jerry-core/lit", + "-I${JERRY_BASE}/jerry-core/debugger" + ] +} diff --git a/tools/Makefile.snapshot b/tools/Makefile.snapshot index eb0242a55..5ee644b90 100644 --- a/tools/Makefile.snapshot +++ b/tools/Makefile.snapshot @@ -81,7 +81,7 @@ snapshot_copy: .PHONY: snapshot snapshot: setup snapshot_copy $(BUILD_OBJ) @echo "Building for snapshot $(BUILD_OBJ)" - cd deps/jerryscript; python ./tools/build.py --builddir=build $(JERRY_FLAGS) $(VERBOSE); + cd deps/jerryscript; python ./tools/build.py --builddir=build --jerry-libc=off $(JERRY_FLAGS) $(VERBOSE); gcc $(SNAPSHOT_INCLUDES) $(JERRY_LIB_PATH) -o $(BUILD_DIR)/snapshot $(BUILD_OBJ) $(SNAPSHOT_FLAGS) $(CFLAGS) $(SNAPSHOT_DEFINES) $(SNAPSHOT_LIBS) .PHONY: clean From f64722f8bf37d0a0fa338d527735401bedb7d06a Mon Sep 17 00:00:00 2001 From: Jimmy Huang Date: Fri, 18 May 2018 13:19:24 -0700 Subject: [PATCH 10/18] [build] Enable LTO to further shrink ROM size Signed-off-by: Jimmy Huang --- cmake/jerry.cmake | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmake/jerry.cmake b/cmake/jerry.cmake index 20ae4c3a9..22c9a6478 100644 --- a/cmake/jerry.cmake +++ b/cmake/jerry.cmake @@ -45,7 +45,7 @@ set(CMAKE_ARGS -DCMAKE_C_COMPILER_WORKS=TRUE -DCMAKE_SYSTEM_NAME=Zephyr -DENABLE_ALL_IN_ONE=OFF - -DENABLE_LTO=OFF + -DENABLE_LTO=ON -DEXTERNAL_COMPILE_FLAGS=${external_project_cflags} -DFEATURE_ERROR_MESSAGES=ON -DFEATURE_DEBUGGER=${DEBUGGER} From 7a15158a4cbf8217211d439b85adc49942f202b9 Mon Sep 17 00:00:00 2001 From: Jimmy Huang Date: Wed, 6 Jun 2018 10:17:52 -0700 Subject: [PATCH 11/18] [jerryscript] Rebase to latest JerryScript (#1883) Signed-off-by: Jimmy Huang --- deps/jerryscript | 2 +- src/ashell/jerry-code.c | 9 +++++---- src/jerry-port/zjs_jerry_port.c | 9 +++++++++ src/main.c | 22 +++++++++++++--------- src/sensors/zjs_sensor_accel.c | 2 +- src/sensors/zjs_sensor_gyro.c | 2 +- src/sensors/zjs_sensor_light.c | 2 +- src/sensors/zjs_sensor_magn.c | 2 +- src/sensors/zjs_sensor_temp.c | 2 +- src/zjs_aio_a101.c | 2 +- src/zjs_ble.c | 12 ++++++------ src/zjs_callbacks.c | 2 +- src/zjs_event.c | 4 ++-- src/zjs_gfx.c | 6 +++--- src/zjs_grove_lcd_ipm.c | 4 ++-- src/zjs_modules.c | 13 +++++++------ src/zjs_sensor.c | 2 +- src/zjs_util.c | 14 +++++++------- tools/snapshot.c | 13 +++++++------ 19 files changed, 70 insertions(+), 54 deletions(-) diff --git a/deps/jerryscript b/deps/jerryscript index c429530d0..145ab1ed7 160000 --- a/deps/jerryscript +++ b/deps/jerryscript @@ -1 +1 @@ -Subproject commit c429530d02347431856fa0bfa1c161c6f3b6953a +Subproject commit 145ab1ed79d3fc1e8618040c3495f9cfd400f64c diff --git a/src/ashell/jerry-code.c b/src/ashell/jerry-code.c index e6235fe58..ae8b52be4 100644 --- a/src/ashell/jerry-code.c +++ b/src/ashell/jerry-code.c @@ -35,7 +35,7 @@ static jerry_value_t parsed_code = 0; void javascript_eval_code(const char *source_buffer, ssize_t size) { ZVAL ret_val = jerry_eval((jerry_char_t *)source_buffer, size, false); - if (jerry_value_has_error_flag(ret_val)) { + if (jerry_value_is_error(ret_val)) { printf("[ERR] failed to evaluate JS\n"); zjs_print_error_message(ret_val, ZJS_UNDEFINED); } @@ -63,8 +63,9 @@ int javascript_parse_code(const char *file_name) if (buf && size > 0) { /* Setup Global scope code */ - parsed_code = jerry_parse((const jerry_char_t *)buf, size, false); - if (jerry_value_has_error_flag(parsed_code)) { + parsed_code = jerry_parse(NULL, 0, (const jerry_char_t *)buf, size, + JERRY_PARSE_NO_OPTS); + if (jerry_value_is_error(parsed_code)) { DBG_PRINT("Error parsing JS\n"); zjs_print_error_message(parsed_code, ZJS_UNDEFINED); jerry_release_value(parsed_code); @@ -85,7 +86,7 @@ void javascript_run_code(const char *file_name) /* Execute the parsed source code in the Global scope */ ZVAL ret_value = jerry_run(parsed_code); - if (jerry_value_has_error_flag(ret_value)) { + if (jerry_value_is_error(ret_value)) { DBG_PRINT("Error running JS\n"); zjs_print_error_message(ret_value, ZJS_UNDEFINED); } diff --git a/src/jerry-port/zjs_jerry_port.c b/src/jerry-port/zjs_jerry_port.c index a81432aee..c93914665 100644 --- a/src/jerry-port/zjs_jerry_port.c +++ b/src/jerry-port/zjs_jerry_port.c @@ -57,3 +57,12 @@ void jerry_port_log(jerry_log_level_t level, const char *format, ...) #endif /* JERRY_DEBUGGER */ va_end(args); } + +void jerry_port_sleep (uint32_t sleep_time) +{ +#ifdef ZJS_LINUX_BUILD + usleep ((useconds_t) sleep_time * 1000); +#else + k_sleep ((useconds_t) sleep_time); +#endif +} diff --git a/src/main.c b/src/main.c index 7dc2097a7..53a5c36d6 100644 --- a/src/main.c +++ b/src/main.c @@ -293,13 +293,13 @@ int main(int argc, char *argv[]) #endif #ifndef ZJS_SNAPSHOT_BUILD - code_eval = jerry_parse_named_resource((jerry_char_t *)file_name, - file_name_len, - (jerry_char_t *)script, - script_len, - false); + code_eval = jerry_parse((jerry_char_t *)file_name, + file_name_len, + (jerry_char_t *)script, + script_len, + JERRY_PARSE_NO_OPTS); - if (jerry_value_has_error_flag(code_eval)) { + if (jerry_value_is_error(code_eval)) { DBG_PRINT("Error parsing JS\n"); zjs_print_error_message(code_eval, ZJS_UNDEFINED); goto error; @@ -311,12 +311,16 @@ int main(int argc, char *argv[]) #endif #ifdef ZJS_SNAPSHOT_BUILD - result = jerry_exec_snapshot(snapshot_bytecode, snapshot_len, false); + result = jerry_exec_snapshot(snapshot_bytecode, + snapshot_len, + 0, + JERRY_SNAPSHOT_EXEC_COPY_DATA); + #else result = jerry_run(code_eval); #endif - if (jerry_value_has_error_flag(result)) { + if (jerry_value_is_error(result)) { DBG_PRINT("Error running JS\n"); zjs_print_error_message(result, ZJS_UNDEFINED); goto error; @@ -406,7 +410,7 @@ int main(int argc, char *argv[]) #ifdef BUILD_MODULE_PROMISE // run queued jobs for promises result = jerry_run_all_enqueued_jobs(); - if (jerry_value_has_error_flag(result)) { + if (jerry_value_is_error(result)) { DBG_PRINT("Error running JS in promise jobqueue\n"); zjs_print_error_message(result, ZJS_UNDEFINED); goto error; diff --git a/src/sensors/zjs_sensor_accel.c b/src/sensors/zjs_sensor_accel.c index efa5544e1..50a9ff96f 100644 --- a/src/sensors/zjs_sensor_accel.c +++ b/src/sensors/zjs_sensor_accel.c @@ -47,7 +47,7 @@ static ZJS_DECL_FUNC(zjs_sensor_constructor) zjs_sensor_create, g_instance, SENSOR_CHAN_ACCEL_XYZ, ACCEL_DEVICE_NAME, 0, 800, onchange, NULL, onstop); - if (!jerry_value_has_error_flag(sensor_obj)) { + if (!jerry_value_is_error(sensor_obj)) { ZVAL null_val = jerry_create_null(); zjs_set_readonly_property(sensor_obj, "x", null_val); zjs_set_readonly_property(sensor_obj, "y", null_val); diff --git a/src/sensors/zjs_sensor_gyro.c b/src/sensors/zjs_sensor_gyro.c index 4d653a000..476e00038 100644 --- a/src/sensors/zjs_sensor_gyro.c +++ b/src/sensors/zjs_sensor_gyro.c @@ -47,7 +47,7 @@ static ZJS_DECL_FUNC(zjs_sensor_constructor) ZJS_CHAIN_FUNC_ARGS(zjs_sensor_create, g_instance, SENSOR_CHAN_GYRO_XYZ, GYRO_DEVICE_NAME, 0, 800, onchange, NULL, onstop); - if (!jerry_value_has_error_flag(sensor_obj)) { + if (!jerry_value_is_error(sensor_obj)) { ZVAL null_val = jerry_create_null(); zjs_set_readonly_property(sensor_obj, "x", null_val); zjs_set_readonly_property(sensor_obj, "y", null_val); diff --git a/src/sensors/zjs_sensor_light.c b/src/sensors/zjs_sensor_light.c index 5477f2e12..53cc261ee 100644 --- a/src/sensors/zjs_sensor_light.c +++ b/src/sensors/zjs_sensor_light.c @@ -41,7 +41,7 @@ static ZJS_DECL_FUNC(zjs_sensor_constructor) ZJS_CHAIN_FUNC_ARGS(zjs_sensor_create, g_instance, SENSOR_CHAN_LIGHT, ADC_DEVICE_NAME, -1, 100, onchange, NULL, onstop); - if (!jerry_value_has_error_flag(sensor_obj)) { + if (!jerry_value_is_error(sensor_obj)) { ZVAL null_val = jerry_create_null(); zjs_set_readonly_property(sensor_obj, "illuminance", null_val); } diff --git a/src/sensors/zjs_sensor_magn.c b/src/sensors/zjs_sensor_magn.c index dc2acc745..ea3a89c90 100644 --- a/src/sensors/zjs_sensor_magn.c +++ b/src/sensors/zjs_sensor_magn.c @@ -47,7 +47,7 @@ static ZJS_DECL_FUNC(zjs_sensor_constructor) ZJS_CHAIN_FUNC_ARGS(zjs_sensor_create, g_instance, SENSOR_CHAN_MAGN_XYZ, MAGN_DEVICE_NAME, 0, 800, onchange, NULL, onstop); - if (!jerry_value_has_error_flag(sensor_obj)) { + if (!jerry_value_is_error(sensor_obj)) { ZVAL null_val = jerry_create_null(); zjs_set_readonly_property(sensor_obj, "x", null_val); zjs_set_readonly_property(sensor_obj, "y", null_val); diff --git a/src/sensors/zjs_sensor_temp.c b/src/sensors/zjs_sensor_temp.c index d2ba0d11a..ee4d78cf3 100644 --- a/src/sensors/zjs_sensor_temp.c +++ b/src/sensors/zjs_sensor_temp.c @@ -41,7 +41,7 @@ static ZJS_DECL_FUNC(zjs_sensor_constructor) ZJS_CHAIN_FUNC_ARGS(zjs_sensor_create, g_instance, SENSOR_CHAN_TEMP, TEMP_DEVICE_NAME, 0, 800, onchange, NULL, onstop); - if (!jerry_value_has_error_flag(sensor_obj)) { + if (!jerry_value_is_error(sensor_obj)) { ZVAL null_val = jerry_create_null(); zjs_set_readonly_property(sensor_obj, "celsius", null_val); } diff --git a/src/zjs_aio_a101.c b/src/zjs_aio_a101.c index 1a143da4e..82e0a0110 100644 --- a/src/zjs_aio_a101.c +++ b/src/zjs_aio_a101.c @@ -239,7 +239,7 @@ static ZJS_DECL_FUNC(zjs_aio_open) send.data.aio.pin = pin; ZVAL result = zjs_aio_call_remote_function(&send); - if (jerry_value_has_error_flag(result)) + if (jerry_value_is_error(result)) return result; // create the AIOPin object diff --git a/src/zjs_ble.c b/src/zjs_ble.c index ad0c302f9..482a96af9 100644 --- a/src/zjs_ble.c +++ b/src/zjs_ble.c @@ -260,7 +260,7 @@ static void zjs_ble_read_c_callback(void *handle, const void *argv) jerry_value_t args[2] = { offset, callback }; ZVAL rval = jerry_call_function(cb->js_callback, chrc->chrc_obj, args, 2); - if (jerry_value_has_error_flag(rval)) { + if (jerry_value_is_error(rval)) { DBG_PRINT("failed to call onReadRequest function\n"); } } @@ -366,7 +366,7 @@ static void zjs_ble_write_c_callback(void *handle, const void *argv) jerry_value_t args[4] = { buf_obj, offset, without_response, callback }; ZVAL rval = jerry_call_function(cb->js_callback, chrc->chrc_obj, args, 4); - if (jerry_value_has_error_flag(rval)) { + if (jerry_value_is_error(rval)) { DBG_PRINT("failed to call onWriteRequest function\n"); } } @@ -444,7 +444,7 @@ static void zjs_ble_subscribe_c_callback(void *handle, const void *argv) jerry_value_t args[2] = { max_size, callback }; ZVAL rval = jerry_call_function(cb->js_callback, chrc->chrc_obj, args, 2); - if (jerry_value_has_error_flag(rval)) { + if (jerry_value_is_error(rval)) { DBG_PRINT("failed to call onSubscribe function\n"); } } @@ -455,7 +455,7 @@ static void zjs_ble_unsubscribe_c_callback(void *handle, const void *argv) ble_notify_handle_t *cb = &chrc->unsubscribe_cb; ZVAL rval = jerry_call_function(cb->js_callback, chrc->chrc_obj, NULL, 0); - if (jerry_value_has_error_flag(rval)) { + if (jerry_value_is_error(rval)) { DBG_PRINT("failed to call onUnsubscribe function\n"); } } @@ -466,7 +466,7 @@ static void zjs_ble_notify_c_callback(void *handle, const void *argv) ble_notify_handle_t *cb = &chrc->notify_cb; ZVAL rval = jerry_call_function(cb->js_callback, chrc->chrc_obj, NULL, 0); - if (jerry_value_has_error_flag(rval)) { + if (jerry_value_is_error(rval)) { DBG_PRINT("failed to call onNotify function\n"); } } @@ -1212,7 +1212,7 @@ static ZJS_DECL_FUNC(zjs_ble_set_services) ZVAL arg = success ? ZJS_UNDEFINED : jerry_create_string("failed to register services"); ZVAL rval = jerry_call_function(argv[1], ZJS_UNDEFINED, &arg, 1); - if (jerry_value_has_error_flag(rval)) { + if (jerry_value_is_error(rval)) { DBG_PRINT("failed to call callback function\n"); } } diff --git a/src/zjs_callbacks.c b/src/zjs_callbacks.c index 39e2a3d58..0068c559f 100644 --- a/src/zjs_callbacks.c +++ b/src/zjs_callbacks.c @@ -523,7 +523,7 @@ void zjs_call_callback(zjs_callback_id id, const void *data, u32_t sz) if (!jerry_value_is_undefined(cb_map[id]->js_func)) { rval = jerry_call_function(cb_map[id]->js_func, cb_map[id]->this, values, sz); - if (jerry_value_has_error_flag(rval)) { + if (jerry_value_is_error(rval)) { #ifdef INSTRUMENT_CALLBACKS DBG_PRINT("callback %d had error; creator: %s, " "caller: %s\n", diff --git a/src/zjs_event.c b/src/zjs_event.c index 62e9f6f96..2edb11f0b 100644 --- a/src/zjs_event.c +++ b/src/zjs_event.c @@ -136,7 +136,7 @@ static ZJS_DECL_FUNC(add_listener) jerry_value_t rval = zjs_add_event_listener(this, name, argv[1]); zjs_free(name); - if (jerry_value_has_error_flag(rval)) { + if (jerry_value_is_error(rval)) { return rval; } @@ -422,7 +422,7 @@ bool zjs_emit_event_priv(jerry_value_t obj, const char *event_name, listener_t *listener = event->listeners; while (listener) { ZVAL rval = jerry_call_function(listener->func, obj, argv, argc); - if (jerry_value_has_error_flag(rval)) { + if (jerry_value_is_error(rval)) { ERR_PRINT("error calling listener\n"); } listener = listener->next; diff --git a/src/zjs_gfx.c b/src/zjs_gfx.c index 97e63de43..9c7532b3c 100644 --- a/src/zjs_gfx.c +++ b/src/zjs_gfx.c @@ -188,7 +188,7 @@ static jerry_value_t zjs_gfx_call_cb(u32_t x, u32_t y, u32_t w, u32_t h, jerry_value_t ret = jerry_call_function(gfxHandle->drawDataCB, gfxHandle->jsThis, args, 5); - if (jerry_value_has_error_flag(ret)) { + if (jerry_value_is_error(ret)) { ERR_PRINT("JS callback failed with %u..\n", (u32_t)ret); return ret; } @@ -273,7 +273,7 @@ static jerry_value_t zjs_gfx_flush(gfx_handle_t *gfxHandle) ret = zjs_gfx_call_cb(xStart, yStart, currW, currH, recBufObj, gfxHandle); - if (jerry_value_has_error_flag(ret)) { + if (jerry_value_is_error(ret)) { zjs_gfx_reset_touched_pixels(gfxHandle); return ret; } @@ -625,7 +625,7 @@ static ZJS_DECL_FUNC(zjs_gfx_draw_string) ret = zjs_gfx_draw_char_priv(x, argData.coords[1], argData.text[i], argData.color, argData.size, handle); - if (jerry_value_has_error_flag(ret)) { + if (jerry_value_is_error(ret)) { return ret; } diff --git a/src/zjs_grove_lcd_ipm.c b/src/zjs_grove_lcd_ipm.c index 36c724779..634379336 100644 --- a/src/zjs_grove_lcd_ipm.c +++ b/src/zjs_grove_lcd_ipm.c @@ -75,7 +75,7 @@ static jerry_value_t zjs_glcd_call_remote_function(zjs_ipm_message_t *send) static jerry_value_t zjs_glcd_call_remote_ignore(zjs_ipm_message_t *send) { ZVAL rval = zjs_glcd_call_remote_function(send); - if (jerry_value_has_error_flag(rval)) + if (jerry_value_is_error(rval)) return rval; return ZJS_UNDEFINED; @@ -231,7 +231,7 @@ static ZJS_DECL_FUNC(zjs_glcd_init) send.type = TYPE_GLCD_INIT; ZVAL result = zjs_glcd_call_remote_function(&send); - if (jerry_value_has_error_flag(result)) { + if (jerry_value_is_error(result)) { return result; } diff --git a/src/zjs_modules.c b/src/zjs_modules.c index 930fc1304..ef32ea3fc 100644 --- a/src/zjs_modules.c +++ b/src/zjs_modules.c @@ -50,7 +50,7 @@ static bool javascript_eval_code(const char *source_buffer, ssize_t size, jerry_value_t *ret_val) { (*ret_val) = jerry_eval((jerry_char_t *)source_buffer, size, false); - if (jerry_value_has_error_flag(*ret_val)) { + if (jerry_value_is_error(*ret_val)) { ERR_PRINT("failed to evaluate JS\n"); return false; } @@ -114,7 +114,7 @@ static bool load_js_module_fs(const jerry_value_t module_name, } (*result) = jerry_eval((jerry_char_t *)str, len, false); - if (jerry_value_has_error_flag(*result)) { + if (jerry_value_is_error(*result)) { ERR_PRINT("failed to evaluate JS\n"); ret = false; } else { @@ -202,7 +202,7 @@ static ZJS_DECL_FUNC(native_require_handler) // Try each of the resolvers to see if we can find the requested module jerry_value_t result = jerryx_module_resolve(argv[0], resolvers, 3); - if (jerry_value_has_error_flag(result)) { + if (jerry_value_is_error(result)) { DBG_PRINT("Couldn't load module %s\n", module); return NOTSUPPORTED_ERROR("Module not found"); } else { @@ -279,12 +279,13 @@ void zjs_modules_check_load_file() size_t size; jerry_value_t parsed_code = 0; buf = read_file_alloc(load_file, &size); - parsed_code = jerry_parse((const jerry_char_t *)buf, size, false); + parsed_code = jerry_parse(NULL, 0, const jerry_char_t *)buf, size, + JERRY_PARSE_NO_OPTS); zjs_free(buf); - if (!jerry_value_has_error_flag(parsed_code)) { + if (!jerry_value_is_error(parsed_code)) { ZVAL ret_value = jerry_run(parsed_code); - if (jerry_value_has_error_flag(ret_value)) { + if (jerry_value_is_error(ret_value)) { ERR_PRINT("Error running JS\n"); } } diff --git a/src/zjs_sensor.c b/src/zjs_sensor.c index 92356f22b..4692b0fc5 100644 --- a/src/zjs_sensor.c +++ b/src/zjs_sensor.c @@ -171,7 +171,7 @@ void zjs_sensor_trigger_change(jerry_value_t obj) ZVAL event = zjs_create_object(); // if onreading exists, call it ZVAL rval = jerry_call_function(func, obj, NULL, 0); - if (jerry_value_has_error_flag(rval)) { + if (jerry_value_is_error(rval)) { ERR_PRINT("Error calling onreading\n"); } } diff --git a/src/zjs_util.c b/src/zjs_util.c index 7058ab480..d7ddfaff7 100644 --- a/src/zjs_util.c +++ b/src/zjs_util.c @@ -217,7 +217,7 @@ bool zjs_obj_get_boolean(jerry_value_t obj, const char *name, bool *flag) ZVAL value = zjs_get_property(obj, name); bool rval = false; - if (!jerry_value_has_error_flag(value) && jerry_value_is_boolean(value)) { + if (!jerry_value_is_error(value) && jerry_value_is_boolean(value)) { *flag = jerry_get_boolean_value(value); rval = true; } @@ -237,7 +237,7 @@ bool zjs_obj_get_string(jerry_value_t obj, const char *name, char *buffer, ZVAL value = zjs_get_property(obj, name); bool rval = false; - if (!jerry_value_has_error_flag(value) && jerry_value_is_string(value)) { + if (!jerry_value_is_error(value) && jerry_value_is_string(value)) { jerry_size_t size = len; zjs_copy_jstring(value, buffer, &size); if (size) @@ -254,7 +254,7 @@ bool zjs_obj_get_double(jerry_value_t obj, const char *name, double *num) ZVAL value = zjs_get_property(obj, name); bool rval = false; - if (!jerry_value_has_error_flag(value) && jerry_value_is_number(value)) { + if (!jerry_value_is_error(value) && jerry_value_is_number(value)) { *num = jerry_get_number_value(value); rval = true; } @@ -269,7 +269,7 @@ bool zjs_obj_get_uint32(jerry_value_t obj, const char *name, u32_t *num) ZVAL value = zjs_get_property(obj, name); bool rval = false; - if (!jerry_value_has_error_flag(value) && jerry_value_is_number(value)) { + if (!jerry_value_is_error(value) && jerry_value_is_number(value)) { *num = (u32_t)jerry_get_number_value(value); rval = true; } @@ -284,7 +284,7 @@ bool zjs_obj_get_int32(jerry_value_t obj, const char *name, s32_t *num) ZVAL value = zjs_get_property(obj, name); bool rval = false; - if (!jerry_value_has_error_flag(value) && jerry_value_is_number(value)) { + if (!jerry_value_is_error(value) && jerry_value_is_number(value)) { *num = (s32_t)jerry_get_number_value(value); rval = true; } @@ -738,7 +738,7 @@ int zjs_validate_args(const char *expectations[], const jerry_length_t argc, int zjs_require_bool_if_prop(jerry_value_t obj, const char *prop, bool *result) { ZVAL value = zjs_get_property(obj, prop); - if (jerry_value_is_undefined(value) || jerry_value_has_error_flag(value)) { + if (jerry_value_is_undefined(value) || jerry_value_is_error(value)) { // not found; leave default return 0; } @@ -755,7 +755,7 @@ int zjs_require_string_if_prop_map(jerry_value_t obj, const char *prop, str2int_t map[], int maxlen, int *result) { ZVAL value = zjs_get_property(obj, prop); - if (jerry_value_is_undefined(value) || jerry_value_has_error_flag(value)) { + if (jerry_value_is_undefined(value) || jerry_value_is_error(value)) { // not found; leave default return 0; } diff --git a/tools/snapshot.c b/tools/snapshot.c index f6f7f0e5b..3da3d6201 100644 --- a/tools/snapshot.c +++ b/tools/snapshot.c @@ -39,12 +39,13 @@ int main(int argc, char *argv[]) return 1; } - size_t size = jerry_parse_and_save_snapshot((jerry_char_t *)script, - len, - true, - false, - snapshot_buf, - sizeof(snapshot_buf)); + size_t size = jerry_generate_snapshot(NULL, + 0, + (const jerry_char_t *)script, + len, + 0, + snapshot_buf, + sizeof(snapshot_buf)); if (script != NULL) free(script); From 65323ee5393fe1ba5ce504ca862eb69e8f2791eb Mon Sep 17 00:00:00 2001 From: Timothy Harvey Date: Fri, 29 Jun 2018 17:18:45 -0500 Subject: [PATCH 12/18] Fixed a problem with too many newlines --- docs/net.md | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/docs/net.md b/docs/net.md index a8673f1ac..05b136345 100644 --- a/docs/net.md +++ b/docs/net.md @@ -3,11 +3,6 @@ ZJS API for Net * [Introduction](#introduction) * [Web IDL](#web-idl) - - - - - * [Class: Net](#net-api) * [net.createServer(callback onconnection)](#netcreateservercallback-onconnection) * [net.Socket()](#netsocket) @@ -34,11 +29,6 @@ ZJS API for Net * [Server.close()](#serverclose) * [Server.getConnections(ListenerCallback onconnection)](#servergetconnectionslistenercallback-onconnection) * [Server.listen(options, onlistening)](#serverlistenoptions-onlistening) - - - - - * [Sample Apps](#sample-apps) Introduction From 6fe497ee5b66f10fd606629830a8d9f1e755af74 Mon Sep 17 00:00:00 2001 From: Timothy Harvey Date: Mon, 2 Jul 2018 20:15:33 -0500 Subject: [PATCH 13/18] Fixed some node.js-style syntax... --- docs/ble.md | 6 +++--- docs/console.md | 21 +++++++++++---------- docs/dgram.md | 4 ++-- docs/events.md | 4 ++-- docs/fs.md | 10 +++++----- docs/gfx.md | 26 +++++++++++++------------- docs/net.md | 36 ++++++++++++++++++------------------ docs/ocf.md | 4 ++-- 8 files changed, 56 insertions(+), 55 deletions(-) diff --git a/docs/ble.md b/docs/ble.md index 3e3e2a132..29abc8b71 100644 --- a/docs/ble.md +++ b/docs/ble.md @@ -6,7 +6,7 @@ ZJS API for Bluetooth Low Energy (BLE) * [BLE-supported Events](#ble\-supported-events) * [Class: BLE](#ble-api) * [ble.disconnect(address)](#bledisconnectaddress) - * [ble.startAdvertising(name, uuids, url)](#blestartadvertisingname-uuids-url) + * [ble.startAdvertising(name, uuids, [url])](#blestartadvertisingname-uuids-url) * [ble.stopAdvertising()](#blestopadvertising) * [ble.setServices(primaryServices)](#blesetservicesprimaryservices) * [ble.newPrimaryService(init)](#blenewprimaryserviceinit) @@ -49,7 +49,7 @@ specific API functions. We also have a short document explaining [ZJS WebIDL co [ReturnFromRequire,ExternalInterface=(eventemitter, EventEmitter)] interface BLE: EventEmitter { void disconnect(string address); - void startAdvertising(string name, sequence < string > uuids, string url); + void startAdvertising(string name, sequence < string > uuids, optional string url); void stopAdvertising(); void setServices(sequence < PrimaryService > services); PrimaryService newPrimaryService(PrimaryServiceInit init); @@ -148,7 +148,7 @@ BLE API Disconnect the remote client. -### ble.startAdvertising(name, uuids, url) +### ble.startAdvertising(name, uuids, [url]) * `name` *string* The `name` is limited to 26 characters and will be advertised as the device name to nearby BLE devices. * `uuids` *string[]* The `uuids` array may contain at most 7 16-bit diff --git a/docs/console.md b/docs/console.md index 149b08ce9..dd2a5225b 100644 --- a/docs/console.md +++ b/docs/console.md @@ -4,11 +4,11 @@ ZJS API for Console * [Introduction](#introduction) * [Web IDL](#web-idl) * [Class: Console](#console-api) - * [console.assert(value, message)](#consoleassertvalue-message) - * [console.error(data)](#consoleerrordata) - * [console.warn(data)](#consolewarndata) - * [console.log(data)](#consolelogdata) - * [console.info(data)](#consoleinfodata) + * [console.assert(value, [message])](#consoleassertvalue-message) + * [console.error([data])](#consoleerrordata) + * [console.warn([data])](#consolewarndata) + * [console.log([data])](#consolelogdata) + * [console.info([data])](#consoleinfodata) * [console.time(label)](#consoletimelabel) * [console.timeEnd(label)](#consoletimeendlabel) * [Sample Apps](#sample-apps) @@ -34,6 +34,7 @@ explaining [ZJS WebIDL conventions](Notes_on_WebIDL.md). interface Console { void assert(boolean value, optional string message); void error(optional string data); + void warn(optional string data); void log(optional string data); void info(optional string data); void time(string label); @@ -44,28 +45,28 @@ interface Console { Console API ----------- -### console.assert(value, message) +### console.assert(value, [message]) * `value` *boolean* * `message` *string* Optional message to print. Assert/throw an error if `value` is false. -### console.error(data) +### console.error([data]) * `data` *string* Optional message to print. Prints `data` to `stderr` with newline. (On Zephyr this will just print to stdout). -### console.warn(data) +### console.warn([data]) * `data` *string* Optional message to print. Alias for `console.error()` -### console.log(data) +### console.log([data]) * `data` *string* Optional message to print. Prints `data` to `stdout` with newline. -### console.info(data) +### console.info([data]) * `data` *string* Optional message to print. Alias for `console.log()`. diff --git a/docs/dgram.md b/docs/dgram.md index 59e4cf5e2..1ca2aca01 100644 --- a/docs/dgram.md +++ b/docs/dgram.md @@ -8,7 +8,7 @@ ZJS API for UDP datagram sockets * [DgramSocket API](#dgramsocket-api) * [DgramSocket.on(event, callback)](#dgramsocketonevent-callback) * [DgramSocket.bind(port, ip_addr)](#dgramsocketbindport-ip_addr) - * [DgramSocket.send(buf, offset, len, port, ip_addr, cb)](#dgramsocketsendbuf-offset-len-port-ip_addr-cb) + * [DgramSocket.send(buf, offset, len, port, ip_addr, [cb])](#dgramsocketsendbuf-offset-len-port-ip_addr-cb) * [DgramSocket.close](#dgramsocketclose) * [Sample Apps](#sample-apps) @@ -92,7 +92,7 @@ IP addresses are allowed. At the time of writing, local interface addresses are hardcoded to be: `'192.0.2.1'` (IPv4) and `'2001:db8::1'` (IPv6), but these will become configurable in the future. -### DgramSocket.send(buf, offset, len, port, ip_addr, cb) +### DgramSocket.send(buf, offset, len, port, ip_addr, [cb]) * `buf` *Buffer* * `offset` *unsigned long* * `len` *unsigned long* diff --git a/docs/events.md b/docs/events.md index 3e5f82c0b..48e0c8f44 100644 --- a/docs/events.md +++ b/docs/events.md @@ -6,7 +6,7 @@ ZJS API for Events * [Class: EventEmitter](#eventemitter-api) * [EventEmitter.on(event, listener)](#eventemitteronevent-listener) * [EventEmitter.addListener(event, listener)](#eventemitteraddlistenerevent-listener) - * [EventEmitter.emit(event, args...)](#eventemitteremitevent-args) + * [EventEmitter.emit(event, [args...])](#eventemitteremitevent-args) * [EventEmitter.removeListener(event, listener)](#eventemitterremovelistenerevent-listener) * [EventEmitter.removeAllListeners(event)](#eventemitterremovealllistenersevent) * [EventEmitter.eventNames()](#eventemittereventnames) @@ -57,7 +57,7 @@ Add an event listener function. Same as `EventEmitter.on()`. -### EventEmitter.emit(event, args...) +### EventEmitter.emit(event, [args...]) * `event` *string* The name of the event that you want to emit. * `args` *optional* All other arguments will be given to any registered listener functions. * Returns: true if there were any listener functions called. diff --git a/docs/fs.md b/docs/fs.md index 1381a60f3..ccfaba749 100644 --- a/docs/fs.md +++ b/docs/fs.md @@ -8,8 +8,8 @@ ZJS API for File System * [fs.closeSync(fd)](#fsclosesyncfd) * [fs.unlinkSync(path)](#fsunlinksyncpath) * [fs.rmdirSync(path)](#fsrmdirsyncpath) - * [fs.writeSync(fd, data, offset, length, position)](#fswritesyncfd-data-offset-length-position) - * [fs.readSync(fd, data, offset, length, position)](#fsreadsyncfd-data-offset-length-position) + * [fs.writeSync(fd, data, offset, length, [position])](#fswritesyncfd-data-offset-length-position) + * [fs.readSync(fd, data, offset, length, [position])](#fsreadsyncfd-data-offset-length-position) * [fs.truncateSync(path, length)](#fstruncatesyncpath-length) * [fs.mkdirSync(path)](#fsmkdirsyncpath) * [fs.readdirSync(path)](#fsreaddirsyncpath) @@ -76,7 +76,7 @@ interface FS { long writeSync(FileDescriptor fd, (string or Buffer) data, long offset, long length, optional long position); long readSync(FileDescriptor fd, Buffer data, long offset, - long length, long position); + long length, optional long position); void truncateSync(string path, long length); void mkdirSync(string path); sequence < string > readdirSync(string path); @@ -117,7 +117,7 @@ Unlink (remove) a file from the file system. Remove a directory from the file system. -### fs.writeSync(fd, data, offset, length, position) +### fs.writeSync(fd, data, offset, length, [position]) * `fd` *FileDescriptor* The file descriptor returned from `openSync()`. * `data` *string or Buffer* The data to write to 'fd'. * `offset` *long* The position in 'data' from which to start writing. @@ -128,7 +128,7 @@ Remove a directory from the file system. Write bytes to an opened file. -### fs.readSync(fd, data, offset, length, position) +### fs.readSync(fd, data, offset, length, [position]) * `fd` *FileDescriptor* The file descriptor returned from 'openSync()'. * `data` *Buffer* The buffer into which the data will be read. * `offset` *long* The offset in 'data' at which to start writing. diff --git a/docs/gfx.md b/docs/gfx.md index cac2dc9bc..65395fd9a 100644 --- a/docs/gfx.md +++ b/docs/gfx.md @@ -4,16 +4,16 @@ ZJS API for GFX * [Introduction](#introduction) * [Web IDL](#web-idl) * [Class: GFX](#gfx-api) - * [gfx.init(screen_width, screen_height, init_screen, draw, this)](#gfxinitscreen_width-screen_height-init_screen-draw-this) + * [gfx.init(screen_width, screen_height, init_screen, draw, [this])](#gfxinitscreen_width-screen_height-init_screen-draw-this) * [Class: GFXContext](#gfxcontext-api) * [gfxcontext.fillRect(x_coord, y_coord, width, height, color)](#gfxcontextfillrectx_coord-y_coord-width-height-color) * [gfxcontext.drawPixel(x_coord, y_coord, color)](#gfxcontextdrawpixelx_coord-y_coord-color) - * [gfxcontext.drawLine(x0_coord, y0_coord, x1_coord, y1_coord, color, size)](#gfxcontextdrawlinex0_coord-y0_coord-x1_coord-y1_coord-color-size) - * [gfxcontext.drawVLine(x_coord, y_coord, height, color, size)](#gfxcontextdrawvlinex_coord-y_coord-height-color-size) - * [gfxcontext.drawHLine(x_coord, y_coord, width, color, size)](#gfxcontextdrawhlinex_coord-y_coord-width-color-size) - * [gfxcontext.drawRect(x_coord, y_coord, width, height, color, size)](#gfxcontextdrawrectx_coord-y_coord-width-height-color-size) - * [gfxcontext.drawChar(x_coord, y_coord, char, color, size)](#gfxcontextdrawcharx_coord-y_coord-char-color-size) - * [gfxcontext.drawString(x_coord, y_coord, str, color, size)](#gfxcontextdrawstringx_coord-y_coord-str-color-size) + * [gfxcontext.drawLine(x0_coord, y0_coord, x1_coord, y1_coord, color, [size])](#gfxcontextdrawlinex0_coord-y0_coord-x1_coord-y1_coord-color-size) + * [gfxcontext.drawVLine(x_coord, y_coord, height, color, [size])](#gfxcontextdrawvlinex_coord-y_coord-height-color-size) + * [gfxcontext.drawHLine(x_coord, y_coord, width, color, [size])](#gfxcontextdrawhlinex_coord-y_coord-width-color-size) + * [gfxcontext.drawRect(x_coord, y_coord, width, height, color, [size])](#gfxcontextdrawrectx_coord-y_coord-width-height-color-size) + * [gfxcontext.drawChar(x_coord, y_coord, char, color, [size])](#gfxcontextdrawcharx_coord-y_coord-char-color-size) + * [gfxcontext.drawString(x_coord, y_coord, str, color, [size])](#gfxcontextdrawstringx_coord-y_coord-str-color-size) * [Sample Apps](#sample-apps) Introduction @@ -87,7 +87,7 @@ Draws a solid rectangle of the given color at the coordinates provided. Draws a pixel of the given color at the coordinates provided. -### gfxcontext.drawLine(x0_coord, y0_coord, x1_coord, y1_coord, color, size) +### gfxcontext.drawLine(x0_coord, y0_coord, x1_coord, y1_coord, color, [size]) * `x0_coord` *long* * `y0_coord` *long* * `x1_coord` *long* @@ -99,7 +99,7 @@ Draws a pixel of the given color at the coordinates provided. Draws a line of the given color at the coordinates provided. The optional size number controls how thick the line is. -### gfxcontext.drawVLine(x_coord, y_coord, height, color, size) +### gfxcontext.drawVLine(x_coord, y_coord, height, color, [size]) * `x_coord` *long* * `y_coord` *long* * `height` *long* @@ -110,7 +110,7 @@ size number controls how thick the line is. Draws a vertical line of the given color at the coordinates provided. The optional size number controls how thick the line is. -### gfxcontext.drawHLine(x_coord, y_coord, width, color, size) +### gfxcontext.drawHLine(x_coord, y_coord, width, color, [size]) * `x_coord` *long* * `y_coord` *long* * `width` *long* @@ -121,7 +121,7 @@ optional size number controls how thick the line is. Draws a horizontal line of the given color at the coordinates provided. The optional size number controls how thick the line is. -### gfxcontext.drawRect(x_coord, y_coord, width, height, color, size) +### gfxcontext.drawRect(x_coord, y_coord, width, height, color, [size]) * `x_coord` *long* * `y_coord` *long* * `width` *long* @@ -133,7 +133,7 @@ optional size number controls how thick the line is. Draws a hollow rectangle of the given color at the coordinates provided. The optional size number controls how thick the line is. -### gfxcontext.drawChar(x_coord, y_coord, char, color, size) +### gfxcontext.drawChar(x_coord, y_coord, char, color, [size]) * `x_coord` *long* * `y_coord` *long* * `char` *byte* @@ -144,7 +144,7 @@ optional size number controls how thick the line is. Draw a character at the coordinates given. The optional size number sets how large the character is. -### gfxcontext.drawString(x_coord, y_coord, str, color, size) +### gfxcontext.drawString(x_coord, y_coord, str, color, [size]) * `x_coord` *long* * `y_coord` *long* * `str` *string* diff --git a/docs/net.md b/docs/net.md index 05b136345..edba56a19 100644 --- a/docs/net.md +++ b/docs/net.md @@ -4,22 +4,22 @@ ZJS API for Net * [Introduction](#introduction) * [Web IDL](#web-idl) * [Class: Net](#net-api) - * [net.createServer(callback onconnection)](#netcreateservercallback-onconnection) + * [net.createServer([onconnection])](#netcreateserveronconnection) * [net.Socket()](#netsocket) - * [net.isIP(string input)](#netisipstring-input) - * [Net.isIPv4(string input)](#netisipv4string-input) - * [Net.isIPv6(string input)](#netisipv6string-input) + * [net.isIP(input)](#netisipinput) + * [Net.isIPv4(input)](#netisipv4input) + * [Net.isIPv6(input)](#netisipv6input) * [Class: Socket](#socket-api) * [Event: 'close'](#event-close) * [Event: 'connect'](#event-connect) * [Event: 'data'](#event-data) * [Event: 'error'](#event-error) * [Event: 'timeout'](#event-timeout) - * [Socket.connect(options, onconnect)](#socketconnectoptions-onconnect) + * [Socket.connect(options, [onconnect])](#socketconnectoptions-onconnect) * [Socket.pause()](#socketpause) * [Socket.resume()](#socketresume) * [Socket.setTimeout(time, ontimeout)](#socketsettimeouttime-ontimeout) - * [Socket.write(buf, writeDone)](#socketwritebuf-writedone) + * [Socket.write(buf, [writeDone])](#socketwritebuf-writedone) * [Class: Server](#server-api) * [Event: 'close'](#event-close) * [Event: 'connection'](#event-connection) @@ -27,8 +27,8 @@ ZJS API for Net * [Event: 'listening'](#event-listening) * [Server.address](#serveraddress) * [Server.close()](#serverclose) - * [Server.getConnections(ListenerCallback onconnection)](#servergetconnectionslistenercallback-onconnection) - * [Server.listen(options, onlistening)](#serverlistenoptions-onlistening) + * [Server.getConnections(onconnection)](#servergetconnectionsonconnection) + * [Server.listen(options, [onlistening])](#serverlistenoptions-onlistening) * [Sample Apps](#sample-apps) Introduction @@ -44,9 +44,9 @@ specific API functions. We also have a short document explaining [ZJS WebIDL co Click to show/hide WebIDL
 // require returns a Net object
-// var net = require('net');

[ReturnFromRequire] +// var net = require('net');

[ReturnFromRequire,ExternalCallback=(eventemitter,ListenerCallback)] interface Net { - Server createServer(optional callback onconnection); + Server createServer(optional ListenerCallback onconnection); Socket Socket(); long isIP(string input); Boolean isIPv4(string input); @@ -101,7 +101,7 @@ dictionary AddressInfo { Net API ------- -### net.createServer(callback onconnection) +### net.createServer([onconnection]) * `onconnection` *callback* The (optional) callback function registered as the the event listener for the `connection` event. * Returns: a `Server` object. @@ -112,20 +112,20 @@ Create a TCP server that can accept client connections. Socket constructor. -### net.isIP(string input) +### net.isIP(input) * `input` *string* * Returns: 4 if the input is an IPv4 address, 6 if the input is an IPv6 address, or 0 if the input is not an IP address. Checks if the input is a valid IP address. -### Net.isIPv4(string input) +### Net.isIPv4(input) * `input` *string* * Returns: true if input is IPv4, false otherwise. Checks if input is an IPv4 address. -### Net.isIPv6(string input) +### Net.isIPv6(input) * `input` *string* * Returns: true if input is IPv6, false otherwise. @@ -159,7 +159,7 @@ Emitted when there was an error on the socket during read, write, or connect. Emitted only when a timeout set with `setTimeout` expires. -### Socket.connect(options, onconnect) +### Socket.connect(options, [onconnect]) * `options` *AddressOptions* Describes the remote server being connected to. * `onconnect` *ListenerCallback* Optional callback added as the listener for the `connect` event. @@ -182,7 +182,7 @@ Allow a socket to resume receiving data after a call to `Socket.pause`. Set a socket timeout. This will start a timer on the socket that will expire in `time` milliseconds if there has been no activity on the socket. -### Socket.write(buf, writeDone) +### Socket.write(buf, [writeDone]) * `buf` *Buffer* `buf` Contains the data to be written. * `writeDone` *ListenerCallback* Optional function called once the data is written. @@ -225,12 +225,12 @@ Signals the server to close. This will stop the server from accepting any new connections but will keep any existing connections alive. Once all existing connections have been closed the server will emit the `close` event. -### Server.getConnections(ListenerCallback onconnection) +### Server.getConnections(onconnection) * `onconnection` *ListenerCallback* Should be a function with `err` and `count` parameters. Get the number of connections to the server. -### Server.listen(options, onlistening) +### Server.listen(options, [onlistening]) * `options` *object* * `onlistening` *ListenerCallback* Optional function added to the `listening` event. diff --git a/docs/ocf.md b/docs/ocf.md index 7ab327f39..e798b6692 100644 --- a/docs/ocf.md +++ b/docs/ocf.md @@ -12,7 +12,7 @@ ZJS API for OCF * [request.respond(data)](#requestresponddata) * [OCFClient-supported Events](#ocfclient-supported-events) * [Class: OCFClient](#ocfclient-api) - * [client.findResources(options, listener)](#clientfindresourcesoptions-listener) + * [client.findResources(options, [listener])](#clientfindresourcesoptions-listener) * [client.retrieve(deviceId, options)](#clientretrievedeviceid-options) * [client.update(resource)](#clientupdateresource) * [client.getPlatformInfo(deviceId)](#clientgetplatforminfodeviceid) @@ -188,7 +188,7 @@ Emitted when a resource is updated. OCFClient API ------------- -### client.findResources(options, listener) +### client.findResources(options, [listener]) * `options` *ClientOptions* Should contain a filter of resource options. Only resources matching these options will be found. * `listener` *FoundListener* An optional event-listener callback. This From a2f14e38e51a0b97d9c41a8ef1eea3310fcf387e Mon Sep 17 00:00:00 2001 From: Timothy Harvey Date: Fri, 6 Jul 2018 10:47:01 -0500 Subject: [PATCH 14/18] Simplified the External* attribute --- docs/Notes_on_WebIDL.md | 8 ++++++++ docs/ble.md | 4 ++-- docs/dgram.md | 2 +- docs/fs.md | 2 +- docs/i2c.md | 4 ++-- docs/net-config.md | 2 +- docs/net.md | 6 +++--- docs/ocf.md | 6 ++---- docs/spi.md | 2 +- docs/timers.md | 7 ++++--- docs/uart.md | 2 +- docs/web-socket.md | 3 ++- 12 files changed, 28 insertions(+), 20 deletions(-) diff --git a/docs/Notes_on_WebIDL.md b/docs/Notes_on_WebIDL.md index d4dab86e8..bd5170392 100644 --- a/docs/Notes_on_WebIDL.md +++ b/docs/Notes_on_WebIDL.md @@ -30,3 +30,11 @@ The node.js notion of "require" is subtly different from constructing an object with JavaScript's "new", but it has appealing semantics. We annotate WebIDL definitions that should be implemented with node.js's "require" semantics with the external attribute "ReturnFromRequire". + +Similarly, many people's general model is one of separate compilation, +which WebIDL does not support. WebIDL's model is to assume that all +of the required files will be concatenated together and then compiled +-- thus, one file can reference types that are found in another file, +and there is no annotation to alert the reader that the definition of +some type is to be found elsewhere. We use WebIDL attributes to +specify and call attention to types that are defined in other files. diff --git a/docs/ble.md b/docs/ble.md index 29abc8b71..4617943d7 100644 --- a/docs/ble.md +++ b/docs/ble.md @@ -46,7 +46,7 @@ specific API functions. We also have a short document explaining [ZJS WebIDL co // require returns a BLE object // var ble = require('ble');

-[ReturnFromRequire,ExternalInterface=(eventemitter, EventEmitter)] +[ReturnFromRequire,ExternalInterface=(EventEmitter)] interface BLE: EventEmitter { void disconnect(string address); void startAdvertising(string name, sequence < string > uuids, optional string url); @@ -88,7 +88,7 @@ interface Characteristic {

callback ReadCallback = void (unsigned long offset, FulfillReadCallback fulfillReadCallback); -[ExternalInterface=(buffer,Buffer)] +[ExternalInterface=(Buffer)] callback WriteCallback = void (Buffer data, unsigned long offset, boolean withoutResponse, FulfillWriteCallback fulfillWriteCallback); diff --git a/docs/dgram.md b/docs/dgram.md index 1ca2aca01..a6c78f105 100644 --- a/docs/dgram.md +++ b/docs/dgram.md @@ -33,7 +33,7 @@ interface Dgram { DgramSocket createSocket(string udp4_or_udp6); };

-[ExternalInterface=(buffer,Buffer)] +[ExternalInterface=(Buffer)] interface DgramSocket { void on(string event, RecvCallback cb); void bind(long port, string ip_addr); diff --git a/docs/fs.md b/docs/fs.md index ccfaba749..ebeef2b94 100644 --- a/docs/fs.md +++ b/docs/fs.md @@ -67,7 +67,7 @@ explaining [ZJS WebIDL conventions](Notes_on_WebIDL.md). // require returns a FS object // var fs = require('fs');

-[ReturnFromRequire, ExternalInterface=(buffer,Buffer)] +[ReturnFromRequire, ExternalInterface=(Buffer)] interface FS { FileDescriptor openSync(string path, FileMode mode); void closeSync(FileDescriptor fd); diff --git a/docs/i2c.md b/docs/i2c.md index 6c4a0b209..0c969a210 100644 --- a/docs/i2c.md +++ b/docs/i2c.md @@ -32,7 +32,7 @@ interface I2C { };

dictionary I2CInit { octet bus; I2CBusSpeed speed; -};

[ExternalInterface=(buffer,Buffer)] +};

[ExternalInterface=(Buffer)] interface I2CBus { // has all the properties of I2CInit as read-only attributes void write(octet device, Buffer data); @@ -40,7 +40,7 @@ interface I2CBus { void burstRead(octet device, unsigned long size, octet registerAddress); };

-typedef I2CBusSpeed long;

+typedef long I2CBusSpeed;
I2C API diff --git a/docs/net-config.md b/docs/net-config.md index 98e52c12b..0d34103b2 100644 --- a/docs/net-config.md +++ b/docs/net-config.md @@ -29,7 +29,7 @@ specific API functions. We have a short document explaining [ZJS WebIDL convent Click to show/hide WebIDL
 // require returns a Net object
-// var net_cfg = require('netconfig');

[ReturnFromRequire,ExternalInterface=(eventemitter, EventEmitter)] +// var net_cfg = require('netconfig');

[ReturnFromRequire,ExternalInterface=(EventEmitter)] interface NetConfig: EventEmitter { boolean setStaticIP(string ip); void dhcp(DHCPCallback callback); diff --git a/docs/net.md b/docs/net.md index edba56a19..71e592c14 100644 --- a/docs/net.md +++ b/docs/net.md @@ -44,7 +44,7 @@ specific API functions. We also have a short document explaining [ZJS WebIDL co

Click to show/hide WebIDL
 // require returns a Net object
-// var net = require('net');

[ReturnFromRequire,ExternalCallback=(eventemitter,ListenerCallback)] +// var net = require('net');

[ReturnFromRequire,ExternalCallback=(ListenerCallback)] interface Net { Server createServer(optional ListenerCallback onconnection); Socket Socket(); @@ -52,7 +52,7 @@ interface Net { Boolean isIPv4(string input); Boolean isIPv6(string input); }; -

[ExternalInterface=(eventemitter,EventEmitter),ExternalInterface=(buffer,Buffer),ExternalCallback=(eventemitter,ListenerCallback)] +

[ExternalInterface=(EventEmitter),ExternalInterface=(Buffer),ExternalCallback=(ListenerCallback)] interface Socket: EventEmitter { // Socket methods void connect(object options, optional ListenerCallback onconnect); @@ -70,7 +70,7 @@ interface Socket: EventEmitter { attribute string remoteFamily; // Remote IP family attribute long remotePort; // Remote port };

-[ExternalInterface=(eventemitter, EventEmitter),ExternalCallback=(eventemitter,ListenerCallback)] +[ExternalInterface=(EventEmitter),ExternalCallback=(ListenerCallback)] interface Server: EventEmitter { // Server methods AddressInfo address(); diff --git a/docs/ocf.md b/docs/ocf.md index e798b6692..90bc4732f 100644 --- a/docs/ocf.md +++ b/docs/ocf.md @@ -66,8 +66,7 @@ interface OCFObject { string coreSpecVersion; };

/////////////////////////////////////////// // OCF Server -///////////////////////////////////////////

[ExternalInterface=(eventemitter, -EventEmitter)] +///////////////////////////////////////////

[ExternalInterface=(EventEmitter)] interface OCFServer: EventEmitter { Promise register(ResourceInit init); };

dictionary ResourceInit { @@ -89,8 +88,7 @@ interface OCFServer: EventEmitter { Promise respond(object data); };

/////////////////////////////////////////// // OCF Client -///////////////////////////////////////////

[ExternalInterface=(eventemitter, -EventEmitter)] +///////////////////////////////////////////

[ExternalInterface=(EventEmitter)] interface OCFClient: EventEmitter { Promise findResources(ClientOptions options, optional FoundListener listener); Promise retrieve(string deviceId, object options); diff --git a/docs/spi.md b/docs/spi.md index 90fc3515e..76e778e87 100644 --- a/docs/spi.md +++ b/docs/spi.md @@ -59,7 +59,7 @@ interface SPI { long phase; unsigned long frameGap; string topology; -};

[ExternalInterface=(buffer,Buffer)] +};

[ExternalInterface=(Buffer)] interface SPIBus { void transceive(octet target, Buffer data, string direction); close(); diff --git a/docs/timers.md b/docs/timers.md index 0bdf32b16..a08c8b73d 100644 --- a/docs/timers.md +++ b/docs/timers.md @@ -34,9 +34,10 @@ interface Timers { void clearInterval(long intervalID); void clearTimeout(long timeoutID); };

-callback TimerCallback = void (any... callback_args);

+callback TimerCallback = void (any... callback_args);

-typedef timeoutID long; +typedef long timeoutID;

+typedef long intervalID;

Timers API @@ -45,7 +46,7 @@ Timers API * `func` *TimerCallback* A callback function that will take the arguments passed in the variadic `args_for_func` parameter. * `delay` *unsigned long* The `delay` argument is in milliseconds. Currently, the delay resolution is about 10 milliseconds, and if you choose a value less than that it will probably fail. * `args_for_func` *any* The user can pass an arbitrary number of additional arguments that will then be passed to `func`. -* Returns: an `intervalID` object that can be passed to `clearInterval` to stop the timer. +* Returns: an `intervalID` value that can be passed to `clearInterval` to stop the timer. Every `delay` milliseconds, your callback function will be called. diff --git a/docs/uart.md b/docs/uart.md index 95a24f713..45054a139 100644 --- a/docs/uart.md +++ b/docs/uart.md @@ -38,7 +38,7 @@ explaining [ZJS WebIDL conventions](Notes_on_WebIDL.md). // long stopBits = 1; // UARTParity parity = "none"; // boolean flowControl = false; -};

[ExternalInterface=(buffer,Buffer),ExternalInterface=(eventemitter, EventEmitter)] +};

[ExternalInterface=(Buffer),ExternalInterface=(EventEmitter)] interface UARTConnection: EventEmitter { // void close(); void write(Buffer data); diff --git a/docs/web-socket.md b/docs/web-socket.md index 849715def..d02fdd1de 100644 --- a/docs/web-socket.md +++ b/docs/web-socket.md @@ -36,7 +36,8 @@ explaining [ZJS WebIDL conventions](Notes_on_WebIDL.md). // var ws = require('ws');

[ReturnFromRequire] interface WebSocket { WebSocketServer Server(object options); -};

[ExternalInterface=(eventemitter, EventEmitter)]interface WebSocketServer: EventEmitter{};

[ExternalInterface=(buffer,Buffer),] +};

[ExternalInterface=(EventEmitter)] +interface WebSocketServer: EventEmitter{};

[ExternalInterface=(Buffer),] interface WebSocketConnection: EventEmitter { void send(Buffer data, boolean mask); void ping(Buffer data, boolean mask); From c7d135e4f4a3904abdd76830be8354868e520daf Mon Sep 17 00:00:00 2001 From: Timothy Harvey Date: Fri, 6 Jul 2018 10:47:01 -0500 Subject: [PATCH 15/18] Simplified the External* attribute Signed-off-by: Timothy Harvey --- docs/Notes_on_WebIDL.md | 8 ++++++++ docs/ble.md | 4 ++-- docs/dgram.md | 2 +- docs/fs.md | 2 +- docs/i2c.md | 4 ++-- docs/net-config.md | 2 +- docs/net.md | 6 +++--- docs/ocf.md | 6 ++---- docs/spi.md | 2 +- docs/timers.md | 7 ++++--- docs/uart.md | 2 +- docs/web-socket.md | 3 ++- 12 files changed, 28 insertions(+), 20 deletions(-) diff --git a/docs/Notes_on_WebIDL.md b/docs/Notes_on_WebIDL.md index d4dab86e8..bd5170392 100644 --- a/docs/Notes_on_WebIDL.md +++ b/docs/Notes_on_WebIDL.md @@ -30,3 +30,11 @@ The node.js notion of "require" is subtly different from constructing an object with JavaScript's "new", but it has appealing semantics. We annotate WebIDL definitions that should be implemented with node.js's "require" semantics with the external attribute "ReturnFromRequire". + +Similarly, many people's general model is one of separate compilation, +which WebIDL does not support. WebIDL's model is to assume that all +of the required files will be concatenated together and then compiled +-- thus, one file can reference types that are found in another file, +and there is no annotation to alert the reader that the definition of +some type is to be found elsewhere. We use WebIDL attributes to +specify and call attention to types that are defined in other files. diff --git a/docs/ble.md b/docs/ble.md index 29abc8b71..4617943d7 100644 --- a/docs/ble.md +++ b/docs/ble.md @@ -46,7 +46,7 @@ specific API functions. We also have a short document explaining [ZJS WebIDL co // require returns a BLE object // var ble = require('ble');

-[ReturnFromRequire,ExternalInterface=(eventemitter, EventEmitter)] +[ReturnFromRequire,ExternalInterface=(EventEmitter)] interface BLE: EventEmitter { void disconnect(string address); void startAdvertising(string name, sequence < string > uuids, optional string url); @@ -88,7 +88,7 @@ interface Characteristic {

callback ReadCallback = void (unsigned long offset, FulfillReadCallback fulfillReadCallback); -[ExternalInterface=(buffer,Buffer)] +[ExternalInterface=(Buffer)] callback WriteCallback = void (Buffer data, unsigned long offset, boolean withoutResponse, FulfillWriteCallback fulfillWriteCallback); diff --git a/docs/dgram.md b/docs/dgram.md index 1ca2aca01..a6c78f105 100644 --- a/docs/dgram.md +++ b/docs/dgram.md @@ -33,7 +33,7 @@ interface Dgram { DgramSocket createSocket(string udp4_or_udp6); };

-[ExternalInterface=(buffer,Buffer)] +[ExternalInterface=(Buffer)] interface DgramSocket { void on(string event, RecvCallback cb); void bind(long port, string ip_addr); diff --git a/docs/fs.md b/docs/fs.md index ccfaba749..ebeef2b94 100644 --- a/docs/fs.md +++ b/docs/fs.md @@ -67,7 +67,7 @@ explaining [ZJS WebIDL conventions](Notes_on_WebIDL.md). // require returns a FS object // var fs = require('fs');

-[ReturnFromRequire, ExternalInterface=(buffer,Buffer)] +[ReturnFromRequire, ExternalInterface=(Buffer)] interface FS { FileDescriptor openSync(string path, FileMode mode); void closeSync(FileDescriptor fd); diff --git a/docs/i2c.md b/docs/i2c.md index 6c4a0b209..0c969a210 100644 --- a/docs/i2c.md +++ b/docs/i2c.md @@ -32,7 +32,7 @@ interface I2C { };

dictionary I2CInit { octet bus; I2CBusSpeed speed; -};

[ExternalInterface=(buffer,Buffer)] +};

[ExternalInterface=(Buffer)] interface I2CBus { // has all the properties of I2CInit as read-only attributes void write(octet device, Buffer data); @@ -40,7 +40,7 @@ interface I2CBus { void burstRead(octet device, unsigned long size, octet registerAddress); };

-typedef I2CBusSpeed long; +typedef long I2CBusSpeed; I2C API diff --git a/docs/net-config.md b/docs/net-config.md index 98e52c12b..0d34103b2 100644 --- a/docs/net-config.md +++ b/docs/net-config.md @@ -29,7 +29,7 @@ specific API functions. We have a short document explaining [ZJS WebIDL convent

Click to show/hide WebIDL
 // require returns a Net object
-// var net_cfg = require('netconfig');

[ReturnFromRequire,ExternalInterface=(eventemitter, EventEmitter)] +// var net_cfg = require('netconfig');

[ReturnFromRequire,ExternalInterface=(EventEmitter)] interface NetConfig: EventEmitter { boolean setStaticIP(string ip); void dhcp(DHCPCallback callback); diff --git a/docs/net.md b/docs/net.md index edba56a19..71e592c14 100644 --- a/docs/net.md +++ b/docs/net.md @@ -44,7 +44,7 @@ specific API functions. We also have a short document explaining [ZJS WebIDL co

Click to show/hide WebIDL
 // require returns a Net object
-// var net = require('net');

[ReturnFromRequire,ExternalCallback=(eventemitter,ListenerCallback)] +// var net = require('net');

[ReturnFromRequire,ExternalCallback=(ListenerCallback)] interface Net { Server createServer(optional ListenerCallback onconnection); Socket Socket(); @@ -52,7 +52,7 @@ interface Net { Boolean isIPv4(string input); Boolean isIPv6(string input); }; -

[ExternalInterface=(eventemitter,EventEmitter),ExternalInterface=(buffer,Buffer),ExternalCallback=(eventemitter,ListenerCallback)] +

[ExternalInterface=(EventEmitter),ExternalInterface=(Buffer),ExternalCallback=(ListenerCallback)] interface Socket: EventEmitter { // Socket methods void connect(object options, optional ListenerCallback onconnect); @@ -70,7 +70,7 @@ interface Socket: EventEmitter { attribute string remoteFamily; // Remote IP family attribute long remotePort; // Remote port };

-[ExternalInterface=(eventemitter, EventEmitter),ExternalCallback=(eventemitter,ListenerCallback)] +[ExternalInterface=(EventEmitter),ExternalCallback=(ListenerCallback)] interface Server: EventEmitter { // Server methods AddressInfo address(); diff --git a/docs/ocf.md b/docs/ocf.md index e798b6692..90bc4732f 100644 --- a/docs/ocf.md +++ b/docs/ocf.md @@ -66,8 +66,7 @@ interface OCFObject { string coreSpecVersion; };

/////////////////////////////////////////// // OCF Server -///////////////////////////////////////////

[ExternalInterface=(eventemitter, -EventEmitter)] +///////////////////////////////////////////

[ExternalInterface=(EventEmitter)] interface OCFServer: EventEmitter { Promise register(ResourceInit init); };

dictionary ResourceInit { @@ -89,8 +88,7 @@ interface OCFServer: EventEmitter { Promise respond(object data); };

/////////////////////////////////////////// // OCF Client -///////////////////////////////////////////

[ExternalInterface=(eventemitter, -EventEmitter)] +///////////////////////////////////////////

[ExternalInterface=(EventEmitter)] interface OCFClient: EventEmitter { Promise findResources(ClientOptions options, optional FoundListener listener); Promise retrieve(string deviceId, object options); diff --git a/docs/spi.md b/docs/spi.md index 90fc3515e..76e778e87 100644 --- a/docs/spi.md +++ b/docs/spi.md @@ -59,7 +59,7 @@ interface SPI { long phase; unsigned long frameGap; string topology; -};

[ExternalInterface=(buffer,Buffer)] +};

[ExternalInterface=(Buffer)] interface SPIBus { void transceive(octet target, Buffer data, string direction); close(); diff --git a/docs/timers.md b/docs/timers.md index 0bdf32b16..a08c8b73d 100644 --- a/docs/timers.md +++ b/docs/timers.md @@ -34,9 +34,10 @@ interface Timers { void clearInterval(long intervalID); void clearTimeout(long timeoutID); };

-callback TimerCallback = void (any... callback_args);

+callback TimerCallback = void (any... callback_args);

-typedef timeoutID long; +typedef long timeoutID;

+typedef long intervalID;

Timers API @@ -45,7 +46,7 @@ Timers API * `func` *TimerCallback* A callback function that will take the arguments passed in the variadic `args_for_func` parameter. * `delay` *unsigned long* The `delay` argument is in milliseconds. Currently, the delay resolution is about 10 milliseconds, and if you choose a value less than that it will probably fail. * `args_for_func` *any* The user can pass an arbitrary number of additional arguments that will then be passed to `func`. -* Returns: an `intervalID` object that can be passed to `clearInterval` to stop the timer. +* Returns: an `intervalID` value that can be passed to `clearInterval` to stop the timer. Every `delay` milliseconds, your callback function will be called. diff --git a/docs/uart.md b/docs/uart.md index 95a24f713..45054a139 100644 --- a/docs/uart.md +++ b/docs/uart.md @@ -38,7 +38,7 @@ explaining [ZJS WebIDL conventions](Notes_on_WebIDL.md). // long stopBits = 1; // UARTParity parity = "none"; // boolean flowControl = false; -};

[ExternalInterface=(buffer,Buffer),ExternalInterface=(eventemitter, EventEmitter)] +};

[ExternalInterface=(Buffer),ExternalInterface=(EventEmitter)] interface UARTConnection: EventEmitter { // void close(); void write(Buffer data); diff --git a/docs/web-socket.md b/docs/web-socket.md index 849715def..d02fdd1de 100644 --- a/docs/web-socket.md +++ b/docs/web-socket.md @@ -36,7 +36,8 @@ explaining [ZJS WebIDL conventions](Notes_on_WebIDL.md). // var ws = require('ws');

[ReturnFromRequire] interface WebSocket { WebSocketServer Server(object options); -};

[ExternalInterface=(eventemitter, EventEmitter)]interface WebSocketServer: EventEmitter{};

[ExternalInterface=(buffer,Buffer),] +};

[ExternalInterface=(EventEmitter)] +interface WebSocketServer: EventEmitter{};

[ExternalInterface=(Buffer),] interface WebSocketConnection: EventEmitter { void send(Buffer data, boolean mask); void ping(Buffer data, boolean mask); From 549aeec2fa8250e09480ee5c6d89c861fdf38164 Mon Sep 17 00:00:00 2001 From: Timothy Harvey Date: Fri, 6 Jul 2018 16:44:36 -0500 Subject: [PATCH 16/18] Fixed a few minor anoyances impeding clean compilation. Signed-off-by: Timothy Harvey --- docs/net.md | 4 ++-- docs/ocf.md | 4 +++- docs/pme.md | 8 ++++---- docs/spi.md | 2 +- 4 files changed, 10 insertions(+), 8 deletions(-) diff --git a/docs/net.md b/docs/net.md index 71e592c14..5e6e85c0d 100644 --- a/docs/net.md +++ b/docs/net.md @@ -49,8 +49,8 @@ interface Net { Server createServer(optional ListenerCallback onconnection); Socket Socket(); long isIP(string input); - Boolean isIPv4(string input); - Boolean isIPv6(string input); + boolean isIPv4(string input); + boolean isIPv6(string input); };

[ExternalInterface=(EventEmitter),ExternalInterface=(Buffer),ExternalCallback=(ListenerCallback)] interface Socket: EventEmitter { diff --git a/docs/ocf.md b/docs/ocf.md index 90bc4732f..812e34f83 100644 --- a/docs/ocf.md +++ b/docs/ocf.md @@ -104,7 +104,9 @@ dictionary ClientResource { string deviceId; string resourceType; string resourcePath; -}; +};

+typedef long OCFResource; /* THIS WAS ADD JUST TO GET THIS FILE + TO COMPILE!!! 7/6/18 */ diff --git a/docs/pme.md b/docs/pme.md index c7a3fcf68..c737a5e78 100644 --- a/docs/pme.md +++ b/docs/pme.md @@ -59,10 +59,10 @@ interface PME { unsigned short distanceMode, unsigned short minInfluence, unsigned short maxInfluence); - void learn(sequence < number > pattern, unsigned long category); - unsigned long classify(sequence < number > pattern); + void learn(sequence < long > pattern, unsigned long category); + unsigned long classify(sequence < long > pattern); Neuron readNeuron(unsigned long id); - void writeVector(sequence < number > pattern); + void writeVector(sequence < long > pattern); unsigned short getCommittedCount(); unsigned short getGlobalContext(); unsigned short getClassifierMode(); @@ -70,7 +70,7 @@ interface PME { unsigned short getDistanceMode(); void setDistanceMode(unsigned short mode); sequence < Json > saveNeurons(); - restoreNeurons(sequence < Json > objects); + void restoreNeurons(sequence < Json > objects);

attribute unsigned short RBF_MODE; // RBF classification mode attribute unsigned short KNN_MODE; // KNN classification mode diff --git a/docs/spi.md b/docs/spi.md index 76e778e87..96c245711 100644 --- a/docs/spi.md +++ b/docs/spi.md @@ -62,7 +62,7 @@ interface SPI { };

[ExternalInterface=(Buffer)] interface SPIBus { void transceive(octet target, Buffer data, string direction); - close(); + void close(); }; From 620b41acf983c00dd5cf4f49bd00584e68203026 Mon Sep 17 00:00:00 2001 From: Timothy Harvey Date: Mon, 9 Jul 2018 17:48:22 -0500 Subject: [PATCH 17/18] Experiment to see what surrounding "details" with the "pre" looks like. Signed-off-by: Timothy Harvey --- docs/i2c.md | 20 ++++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/docs/i2c.md b/docs/i2c.md index 0c969a210..cb8aef233 100644 --- a/docs/i2c.md +++ b/docs/i2c.md @@ -23,25 +23,33 @@ This IDL provides an overview of the interface; see below for documentation of specific API functions. We have a short document explaining [ZJS WebIDL conventions](Notes_on_WebIDL.md). +

 
Click to show WebIDL -
// require returns a I2C object
-// var i2c = require('i2c');

[ReturnFromRequire] +// require returns a I2C object +// var i2c = require('i2c'); + +[ReturnFromRequire] interface I2C { I2CBus open(I2CInit init); -};

dictionary I2CInit { +}; + +dictionary I2CInit { octet bus; I2CBusSpeed speed; -};

[ExternalInterface=(Buffer)] +}; + +[ExternalInterface=(Buffer)] interface I2CBus { // has all the properties of I2CInit as read-only attributes void write(octet device, Buffer data); void read(octet device, unsigned long size, octet registerAddress); void burstRead(octet device, unsigned long size, octet registerAddress); }; -

-typedef long I2CBusSpeed;

+ +typedef long I2CBusSpeed;
+
I2C API ------- From 56d12fbb4de9f68d0b1bbe9d7686f6da1ace509f Mon Sep 17 00:00:00 2001 From: Timothy Harvey Date: Tue, 10 Jul 2018 15:52:48 -0500 Subject: [PATCH 18/18] Fixed vertical whitespace to make all of the WebIDL files consistent. Signed-off-by: Timothy Harvey --- docs/aio.md | 5 ++--- docs/ble.md | 23 ++++++----------------- docs/board.md | 1 - docs/console.md | 3 ++- docs/dgram.md | 13 +++---------- docs/fs.md | 4 ++-- docs/gfx.md | 9 +++++---- docs/gpio.md | 5 +++-- docs/grove_lcd.md | 14 +++++--------- docs/i2c.md | 10 +++++----- docs/mathstubs.md | 3 ++- docs/net-config.md | 2 +- docs/net.md | 18 +++++++----------- docs/ocf.md | 7 ++----- docs/performance.md | 1 - docs/pme.md | 5 +++-- docs/pwm.md | 4 +--- docs/sensors.md | 9 ++++----- docs/spi.md | 6 ++++-- docs/timers.md | 4 +--- docs/uart.md | 6 ++++-- docs/web-socket.md | 6 ++++-- 22 files changed, 66 insertions(+), 92 deletions(-) diff --git a/docs/aio.md b/docs/aio.md index 3d3cc3ec4..bdd1d153d 100644 --- a/docs/aio.md +++ b/docs/aio.md @@ -38,7 +38,7 @@ explaining [ZJS WebIDL conventions](Notes_on_WebIDL.md). Click to show WebIDL
 // require returns an AIO object
-// var aio = require('aio');

[ReturnFromRequire] +// var aio = require('aio');

[ReturnFromRequire] interface AIO { AIOPin open(AIOInit init); };

dictionary AIOInit { @@ -49,8 +49,7 @@ interface AIO { void on(string eventType, ReadCallback callback); void close(); };

callback ReadCallback = void (unsigned long value); -

- + AIO API ------- diff --git a/docs/ble.md b/docs/ble.md index 4617943d7..5908562d4 100644 --- a/docs/ble.md +++ b/docs/ble.md @@ -45,7 +45,6 @@ specific API functions. We also have a short document explaining [ZJS WebIDL co
 // require returns a BLE object
 // var ble = require('ble');
-

[ReturnFromRequire,ExternalInterface=(EventEmitter)] interface BLE: EventEmitter { void disconnect(string address); @@ -55,18 +54,14 @@ interface BLE: EventEmitter { PrimaryService newPrimaryService(PrimaryServiceInit init); Characteristic newCharacteristic(CharacteristicInit init); DescriptorInit newDescriptor(DescriptorInit init); -}; -

+};

dictionary PrimaryServiceInit { string uuid; sequence < Characteristic > characteristics; -};

-dictionary PrimaryService { +};

dictionary PrimaryService { string uuid; sequence < Characteristic > characteristics; -}; -

-dictionary CharacteristicInit { +};

dictionary CharacteristicInit { string uuid; sequence < string > properties; // 'read', 'write', 'notify' sequence < DescriptorInit > descriptors; @@ -75,18 +70,14 @@ dictionary CharacteristicInit { SubscribeCallback onSubscribe; // optional UnsubscribeCallback onUnsubscribe; // optional NotifyCallback onNotify; // optional -}; -

-interface Characteristic { +};

interface Characteristic { attribute ReadCallback onReadRequest; attribute WriteCallback onWriteRequest; attribute SubscribeCallback onSubscribe; attribute UnsubscribeCallback onUnsubscribe; attribute NotifyCallback onNotify; attribute CharacteristicResult response; -}; -

-callback ReadCallback = void (unsigned long offset, +};

callback ReadCallback = void (unsigned long offset, FulfillReadCallback fulfillReadCallback); [ExternalInterface=(Buffer)] callback WriteCallback = void (Buffer data, unsigned long offset, @@ -99,10 +90,8 @@ callback FulfillWriteCallback = void (CharacteristicResult result); callback FulfillSubscribeCallback = void (Buffer data); callback NotifyCallback = void (any... params); callback UnsubscribeCallback = void (any... params); -

enum CharacteristicResult { "RESULT_SUCCESS", "RESULT_INVALID_OFFSET", - "RESULT_INVALID_ATTRIBUTE_LENGTH", "RESULT_UNLIKELY_ERROR" } ; -

+ "RESULT_INVALID_ATTRIBUTE_LENGTH", "RESULT_UNLIKELY_ERROR" }; dictionary DescriptorInit { string uuid; string value; diff --git a/docs/board.md b/docs/board.md index 33d88f2db..c738baf99 100644 --- a/docs/board.md +++ b/docs/board.md @@ -24,7 +24,6 @@ documentation of specific API functions. We have a short document explaining [Z

Click to show/hide WebIDL
// require returns the Board API object
 // var board = require('board');
-

[ReturnFromRequire] interface Board { attribute string name5; diff --git a/docs/console.md b/docs/console.md index dd2a5225b..eee4c81e2 100644 --- a/docs/console.md +++ b/docs/console.md @@ -30,7 +30,8 @@ explaining [ZJS WebIDL conventions](Notes_on_WebIDL.md).

Click to show WebIDL
 // require returns a Console object
-// var console = require('console');

[ReturnFromRequire] +// var console = require('console'); +[ReturnFromRequire] interface Console { void assert(boolean value, optional string message); void error(optional string data); diff --git a/docs/dgram.md b/docs/dgram.md index a6c78f105..1284db5ec 100644 --- a/docs/dgram.md +++ b/docs/dgram.md @@ -27,12 +27,10 @@ specific API functions. We also have a short document explaining [ZJS WebIDL co

 // require returns a socket factory object
 // var dgram = require('dgram');
-

[ReturnFromRequire] interface Dgram { DgramSocket createSocket(string udp4_or_udp6); -}; -

+};

[ExternalInterface=(Buffer)] interface DgramSocket { void on(string event, RecvCallback cb); @@ -40,14 +38,9 @@ interface DgramSocket { void send(Buffer buf, unsigned long offset, unsigned long len, long port, string ip_addr, optional SendCallback cb); void close(); -}; -

-callback RecvCallback = void (Buffer msg, RemoteInfo rinfo); +};

callback RecvCallback = void (Buffer msg, RemoteInfo rinfo); callback SendCallback = void (Error err); // or undefined if no error -

-callback EventCallback = void (any... args); // callback args depend on event -

-dictionary RemoteInfo { +callback EventCallback = void (any... args); // callback args depend on event

dictionary RemoteInfo { string ip_addr; string family; long port; diff --git a/docs/fs.md b/docs/fs.md index ebeef2b94..0cd981936 100644 --- a/docs/fs.md +++ b/docs/fs.md @@ -66,7 +66,6 @@ explaining [ZJS WebIDL conventions](Notes_on_WebIDL.md).

 // require returns a FS object
 // var fs = require('fs');
-

[ReturnFromRequire, ExternalInterface=(Buffer)] interface FS { FileDescriptor openSync(string path, FileMode mode); @@ -82,7 +81,8 @@ interface FS { sequence < string > readdirSync(string path); Stat statSync(string path); void writeFileSync(string file, (string or Buffer) data); -};

// file descriptors are inherently platform specific, so we leave this +};

+// file descriptors are inherently platform specific, so we leave this // as a placeholder dictionary FileDescriptor { //string name; diff --git a/docs/gfx.md b/docs/gfx.md index 65395fd9a..d77263689 100644 --- a/docs/gfx.md +++ b/docs/gfx.md @@ -31,11 +31,13 @@ specific API functions. We also have a short document explaining [ZJS WebIDL co

Click to show/hide WebIDL
 // require returns a GFX object
-// var gfx = require('gfx');

[ReturnFromRequire] +// var gfx = require('gfx'); +[ReturnFromRequire] interface GFX { GFXContext init(long screen_width, long screen_height, InitCallback init_screen, DrawingCallback draw, optional this this_object); -};

interface GFXContext { +};

+interface GFXContext { void fillRect(long x_coord, long y_coord, long width, long height, sequence < byte > color); void drawPixel(long x_coord, long y_coord, sequence < byte > color); @@ -51,8 +53,7 @@ interface GFX { optional long size); void drawString(long x_coord, long y_coord, string str, sequence < byte > color, optional long size); -}; -callback InitCallback = void (any... params); +};

callback InitCallback = void (any... params); callback DrawingCallback = void (any... params);

diff --git a/docs/gpio.md b/docs/gpio.md index e9f12b94d..5e9d9769a 100644 --- a/docs/gpio.md +++ b/docs/gpio.md @@ -29,11 +29,12 @@ specific API functions. We have a short document explaining [ZJS WebIDL convent Click to show/hide WebIDL
 // require returns a GPIO object
-// var gpio = require('gpio');

+// var gpio = require('gpio'); [ReturnFromRequire] interface GPIO { GPIOPin open( (long or string or GPIOInit) init); -};

dictionary GPIOInit { +};

+dictionary GPIOInit { (long or string) pin; boolean activeLow = false; GPIOMode mode = "out"; diff --git a/docs/grove_lcd.md b/docs/grove_lcd.md index f8140a325..ed7c611f6 100644 --- a/docs/grove_lcd.md +++ b/docs/grove_lcd.md @@ -33,28 +33,24 @@ explaining [ZJS WebIDL conventions](Notes_on_WebIDL.md).

Click to show WebIDL
// require returns a GroveLCD object
-// var grove_lcd = require('grove_lcd');

[ReturnFromRequire] +// var grove_lcd = require('grove_lcd'); +[ReturnFromRequire] interface GroveLCD { GroveLCDDevice init(); attribute unsigned long GLCD_FS_8BIT_MODE; attribute unsigned long GLCD_FS_ROWS_2; attribute unsigned long GLCD_FS_ROWS_1; attribute unsigned long GLCD_FS_DOT_SIZE_BIG; - attribute unsigned long GLCD_FS_DOT_SIZE_LITTLE; -

+ attribute unsigned long GLCD_FS_DOT_SIZE_LITTLE;

attribute unsigned long GLCD_DS_DISPLAY_ON; attribute unsigned long GLCD_DS_DISPLAY_OFF; attribute unsigned long GLCD_DS_CURSOR_ON; attribute unsigned long GLCD_DS_CURSOR_OFF; attribute unsigned long GLCD_DS_BLINK_ON; - attribute unsigned long GLCD_DS_BLINK_OFF; -

- attribute unsigned long GLCD_IS_SHIFT_INCREMENT; + attribute unsigned long GLCD_DS_BLINK_OFF;

attribute unsigned long GLCD_IS_SHIFT_INCREMENT; attribute unsigned long GLCD_IS_SHIFT_DECREMENT; attribute unsigned long GLCD_IS_ENTRY_LEFT; - attribute unsigned long GLCD_IS_ENTRY_RIGHT; -

- attribute unsigned long GROVE_RGB_WHITE; + attribute unsigned long GLCD_IS_ENTRY_RIGHT;

attribute unsigned long GROVE_RGB_WHITE; attribute unsigned long GROVE_RGB_RED; attribute unsigned long GROVE_RGB_GREEN; attribute unsigned long GROVE_RGB_BLUE; diff --git a/docs/i2c.md b/docs/i2c.md index 0c969a210..1ae81a9fa 100644 --- a/docs/i2c.md +++ b/docs/i2c.md @@ -26,10 +26,12 @@ explaining [ZJS WebIDL conventions](Notes_on_WebIDL.md).

Click to show WebIDL
// require returns a I2C object
-// var i2c = require('i2c');

[ReturnFromRequire] +// var i2c = require('i2c'); +[ReturnFromRequire] interface I2C { I2CBus open(I2CInit init); -};

dictionary I2CInit { +};

+dictionary I2CInit { octet bus; I2CBusSpeed speed; };

[ExternalInterface=(Buffer)] @@ -38,9 +40,7 @@ interface I2CBus { void write(octet device, Buffer data); void read(octet device, unsigned long size, octet registerAddress); void burstRead(octet device, unsigned long size, octet registerAddress); -}; -

-typedef long I2CBusSpeed;

+};

typedef long I2CBusSpeed;

I2C API diff --git a/docs/mathstubs.md b/docs/mathstubs.md index 3574c70be..88bd1c682 100644 --- a/docs/mathstubs.md +++ b/docs/mathstubs.md @@ -25,7 +25,8 @@ specific API functions. We have a short document explaining [ZJS WebIDL convent
Click to show/hide WebIDL
// require returns a MathStubs object
-// var mathStubs = require('mathstubs');

[ReturnFromRequire] +// var mathStubs = require('mathstubs'); +[ReturnFromRequire] interface MathStubs { double random(); }; diff --git a/docs/net-config.md b/docs/net-config.md index 0d34103b2..6792d033f 100644 --- a/docs/net-config.md +++ b/docs/net-config.md @@ -29,7 +29,7 @@ specific API functions. We have a short document explaining [ZJS WebIDL convent

Click to show/hide WebIDL
 // require returns a Net object
-// var net_cfg = require('netconfig');

[ReturnFromRequire,ExternalInterface=(EventEmitter)] +// var net_cfg = require('netconfig');

[ReturnFromRequire,ExternalInterface=(EventEmitter)] interface NetConfig: EventEmitter { boolean setStaticIP(string ip); void dhcp(DHCPCallback callback); diff --git a/docs/net.md b/docs/net.md index 5e6e85c0d..350678984 100644 --- a/docs/net.md +++ b/docs/net.md @@ -44,15 +44,16 @@ specific API functions. We also have a short document explaining [ZJS WebIDL co

Click to show/hide WebIDL
 // require returns a Net object
-// var net = require('net');

[ReturnFromRequire,ExternalCallback=(ListenerCallback)] +// var net = require('net'); +[ReturnFromRequire,ExternalCallback=(ListenerCallback)] interface Net { Server createServer(optional ListenerCallback onconnection); Socket Socket(); long isIP(string input); boolean isIPv4(string input); boolean isIPv6(string input); -}; -

[ExternalInterface=(EventEmitter),ExternalInterface=(Buffer),ExternalCallback=(ListenerCallback)] +};

+[ExternalInterface=(EventEmitter),ExternalInterface=(Buffer),ExternalCallback=(ListenerCallback)] interface Socket: EventEmitter { // Socket methods void connect(object options, optional ListenerCallback onconnect); @@ -69,8 +70,7 @@ interface Socket: EventEmitter { attribute string remoteAddress; // Remote IP address attribute string remoteFamily; // Remote IP family attribute long remotePort; // Remote port -};

-[ExternalInterface=(EventEmitter),ExternalCallback=(ListenerCallback)] +};

[ExternalInterface=(EventEmitter),ExternalCallback=(ListenerCallback)] interface Server: EventEmitter { // Server methods AddressInfo address(); @@ -80,17 +80,13 @@ interface Server: EventEmitter { // Server properties attribute boolean listening; // true if the server is listening attribute long maxConnections; // maximum number of connections -}; -

-dictionary AddressOptions { +};

dictionary AddressOptions { long port; // Port the client should connect to (required) string host; // Host the client should connect to string localAddress; // Local address to bind to long localPort; // local port to bind to long family; // Version of IP stack, deafults to 4 -}; -

-dictionary AddressInfo { +};

dictionary AddressInfo { long port; // Server port string family; // IPv4 or IPv6 string address; // IP address for the server diff --git a/docs/ocf.md b/docs/ocf.md index 812e34f83..6feab53ca 100644 --- a/docs/ocf.md +++ b/docs/ocf.md @@ -99,14 +99,11 @@ interface OCFClient: EventEmitter { string deviceId; string resourceType; string resourcePath; -};

callback FoundListener = void (ClientResource resource); -dictionary ClientResource { +};

callback FoundListener = void (ClientResource resource);

dictionary ClientResource { string deviceId; string resourceType; string resourcePath; -};

-typedef long OCFResource; /* THIS WAS ADD JUST TO GET THIS FILE - TO COMPILE!!! 7/6/18 */ +};

typedef long OCFResource; /* may be some other type/object */

diff --git a/docs/performance.md b/docs/performance.md index ac3f5ebbe..2f049721f 100644 --- a/docs/performance.md +++ b/docs/performance.md @@ -25,7 +25,6 @@ specific API functions. We also have a short document explaining [ZJS WebIDL co
 // require returns a Performance object
 // var ble = require('performance');
-

[ReturnFromRequire] interface Performance { double now(); diff --git a/docs/pme.md b/docs/pme.md index c737a5e78..148e95099 100644 --- a/docs/pme.md +++ b/docs/pme.md @@ -50,7 +50,8 @@ specific API functions. We also have a short document explaining [ZJS WebIDL co

Click to show/hide WebIDL
 // require returns a PME object
-// var pme = require('pme');

[ReturnFromRequire] +// var pme = require('pme'); +[ReturnFromRequire] interface PME { void begin(); void forget(); @@ -76,7 +77,7 @@ interface PME { attribute unsigned short KNN_MODE; // KNN classification mode attribute unsigned short L1_DISTANCE; // L1 distance mode attribute unsigned short LSUP_DISTANCE; // LSUP distance mode - attribute unsigned long NO_MATCH; // indicate a pattern could not + attribute unsigned long NO_MATCH; // indicates a pattern could not // be classified attribute unsigned short MIN_CONTEXT; // minimum context value attribute unsigned short MAX_CONTEXT; // maximum context value diff --git a/docs/pwm.md b/docs/pwm.md index 0ce0fd183..47f81f6d7 100644 --- a/docs/pwm.md +++ b/docs/pwm.md @@ -47,7 +47,6 @@ specific API functions. We also have a short document explaining [ZJS WebIDL co

 // require returns a PWM object
 // var pwm = require('pwm');
-

[ReturnFromRequire] interface PWM { PWMPin open((long or string or PWMInit) init); @@ -55,8 +54,7 @@ interface PWM { dictionary PWMInit { (long or string) pin; boolean reversePolarity = false; -};

-interface PWMPin { +};

interface PWMPin { void setCycles(unsigned long period, unsigned long pulseWidth); void setMilliseconds(double period, double pulseWidth); };

diff --git a/docs/sensors.md b/docs/sensors.md index a77488de2..5f6d0f0d6 100644 --- a/docs/sensors.md +++ b/docs/sensors.md @@ -46,7 +46,8 @@ interface Sensor { attribute ChangeCallback onreading; // callback handler for change events attribute ActivateCallback onactivate; // callback handler for activate events attribute ErrorCallback onerror; // callback handler for error events -};

dictionary SensorOptions { +};

+dictionary SensorOptions { double frequency; // desired frequency, default is 20 if unset };

interface SensorErrorEvent { attribute Error error; @@ -64,11 +65,9 @@ interface GyroscopeSensor : Sensor { readonly attribute double x; readonly attribute double y; readonly attribute double z; -};

-dictionary GyroscopeOptions : SensorOptions { +};

dictionary GyroscopeOptions : SensorOptions { string controller; // controller name, default to "bmi160" -};

-[Constructor(optional SensorOptions sensorOptions)] +};

[Constructor(optional SensorOptions sensorOptions)] interface AmbientLightSensor : Sensor { readonly attribute unsigned long pin; readonly attribute double illuminance; diff --git a/docs/spi.md b/docs/spi.md index 96c245711..60d3920b2 100644 --- a/docs/spi.md +++ b/docs/spi.md @@ -48,10 +48,12 @@ explaining [ZJS WebIDL conventions](Notes_on_WebIDL.md).

Click to show WebIDL
// require returns a SPI object
-// var spi = require('spi');

[ReturnFromRequire] +// var spi = require('spi'); +[ReturnFromRequire] interface SPI { SPIBus open(SPIOptions init); -};

dictionary SPIOptions { +};

+dictionary SPIOptions { octet bus; long speed; // bus clock frequency in Hz boolean msbFirst; diff --git a/docs/timers.md b/docs/timers.md index a08c8b73d..6f7bab78b 100644 --- a/docs/timers.md +++ b/docs/timers.md @@ -26,7 +26,6 @@ explaining [ZJS WebIDL conventions](Notes_on_WebIDL.md).

 // require returns a Timers object
 // var timers = require('timers');
-

[ReturnFromRequire] interface Timers { intervalID setInterval(TimerCallback func, unsigned long delay, any... args_for_func); @@ -35,8 +34,7 @@ interface Timers { void clearTimeout(long timeoutID); };

callback TimerCallback = void (any... callback_args); -

-typedef long timeoutID;

+

typedef long timeoutID; typedef long intervalID;

diff --git a/docs/uart.md b/docs/uart.md index 45054a139..18f7b494b 100644 --- a/docs/uart.md +++ b/docs/uart.md @@ -29,9 +29,11 @@ explaining [ZJS WebIDL conventions](Notes_on_WebIDL.md).
Click to show WebIDL
// require returns a UART object
-// var uart = require('uart');

interface UART { +// var uart = require('uart'); +interface UART { UARTConnection init(UARTOptions options); -};

dictionary UARTOptions { +};

+dictionary UARTOptions { string port; // long baud = 115200; // long dataBits = 8; diff --git a/docs/web-socket.md b/docs/web-socket.md index d02fdd1de..806a7d908 100644 --- a/docs/web-socket.md +++ b/docs/web-socket.md @@ -33,10 +33,12 @@ explaining [ZJS WebIDL conventions](Notes_on_WebIDL.md).

Click to show WebIDL
// require returns a WebSocket object
-// var ws = require('ws');

[ReturnFromRequire] +// var ws = require('ws'); +[ReturnFromRequire] interface WebSocket { WebSocketServer Server(object options); -};

[ExternalInterface=(EventEmitter)] +};

+[ExternalInterface=(EventEmitter)] interface WebSocketServer: EventEmitter{};

[ExternalInterface=(Buffer),] interface WebSocketConnection: EventEmitter { void send(Buffer data, boolean mask);