diff --git a/typescript/generate.js b/typescript/generate.js index efcff1ae2..d6b7340a7 100644 --- a/typescript/generate.js +++ b/typescript/generate.js @@ -51,8 +51,9 @@ function get(key, obj, isGlobal, f) { .filter((line) => line) .map((line) => line + .replace("^

(.*)

$", "$1") .replace("

", "") - .replace("

", "") + .replace("

", "\n") .replace(/'/g, "'") .replace(/"/g, '"') .replace(/>/g, ">") @@ -62,19 +63,29 @@ function get(key, obj, isGlobal, f) { .replace(/<\/?strong>/g, "**") .replace(/<\/?em>/g, "*") .replace(/<\/?code>/g, "`") - .replace(/<\/?ul>/g, "") + .replace(/<\/?ul>/g, "\n") .replace(/
  • /g, "- ") .replace(/<\/li>/g, "") + .replace(/
    `/g, "\n```\n")
    +            .replace(/

    ([^\n]+)<\/h3>/g, "\n\n# $1\n\n") + .replace(/`<\/pre>/g, "```\n") + .replace(//g, "") + .replace(/<\/span>/g, "") .replace( - /([^\n]*)<\/a>/g, + /([^\n<>]*)<\/a>/g, (_, address, name) => { if (address.startsWith("/")) address = "https://espruino.com/" + address; return `[${name}](${address})`; } ) + .split("\n") ) + .flat() .concat([`@url ${obj["!url"]}`]) + .join("\n") + .replace(/\n\n+/g, "\n\n") + .split("\n") .map((line) => " * " + line) .join("\n") + "\n */", diff --git a/typescript/types/main.d.ts b/typescript/types/main.d.ts index 483d0380d..59967a8dc 100644 --- a/typescript/types/main.d.ts +++ b/typescript/types/main.d.ts @@ -2,24 +2,29 @@ /** * Class containing [micro:bit's](https://www.espruino.com/MicroBit) utility functions. + * * @url http://www.espruino.com/Reference#Microbit */ declare const Microbit: { /** * The micro:bit's speaker pin + * * @url http://www.espruino.com/Reference#l_Microbit_SPEAKER */ SPEAKER: Pin /** * The micro:bit's microphone pin + * * `MIC_ENABLE` should be set to 1 before using this + * * @url http://www.espruino.com/Reference#l_Microbit_MIC */ MIC: Pin /** * The micro:bit's microphone enable pin + * * @url http://www.espruino.com/Reference#l_Microbit_MIC_ENABLE */ MIC_ENABLE: Pin @@ -36,33 +41,40 @@ declare const Microbit: { /** * **Note:** This function is only available on the [BBC micro:bit](https://espruino.com//MicroBit) board + * * Write the given value to the accelerometer + * * @url http://www.espruino.com/Reference#l_Microbit_accelWr */ accelWr: (addr: number, data: number) => void; /** * Turn on the accelerometer, and create `Microbit.accel` and `Microbit.gesture` events. + * * **Note:** The accelerometer is currently always enabled - this code * just responds to interrupts and reads + * * @url http://www.espruino.com/Reference#l_Microbit_accelOn */ accelOn: () => void; /** * Turn off events from the accelerometer (started with `Microbit.accelOn`) + * * @url http://www.espruino.com/Reference#l_Microbit_accelOff */ accelOff: () => void; /** * Play a waveform on the Micro:bit's speaker + * * @url http://www.espruino.com/Reference#l_Microbit_play */ play: (waveform: any, samplesPerSecond: any, callback: any) => void; /** * Records sound from the micro:bit's onboard microphone and returns the result + * * @url http://www.espruino.com/Reference#l_Microbit_record */ record: (samplesPerSecond: any, callback: any, samples: any) => void; @@ -75,6 +87,7 @@ declare const Microbit: { /** * Class containing an instance of TFMicroInterpreter + * * @url http://www.espruino.com/Reference#TFMicroInterpreter */ declare function TFMicroInterpreter(): void; @@ -99,12 +112,15 @@ type TFMicroInterpreter = { /** * Class containing utility functions for accessing IO on the hexagonal badge + * * @url http://www.espruino.com/Reference#Badge */ declare const Badge: { /** * Capacitive sense - the higher the capacitance, the higher the number returned. + * * Supply a corner number between 1 and 6, and an integer value will be returned that is proportional to the capacitance + * * @url http://www.espruino.com/Reference#l_Badge_capSense */ capSense: (corner: number) => number; @@ -112,12 +128,14 @@ declare const Badge: { /** * Return an approximate battery percentage remaining based on * a normal CR2032 battery (2.8 - 2.2v) + * * @url http://www.espruino.com/Reference#l_Badge_getBatteryPercentage */ getBatteryPercentage: () => number; /** * Set the LCD's contrast + * * @url http://www.espruino.com/Reference#l_Badge_setContrast */ setContrast: (c: number) => void; @@ -126,33 +144,43 @@ declare const Badge: { /** * Class containing [Puck.js's](http://www.puck-js.com) utility functions. + * * @url http://www.espruino.com/Reference#Puck */ declare const Puck: { /** * Turn on the magnetometer, take a single reading, and then turn it off again. + * * An object of the form `{x,y,z}` is returned containing magnetometer readings. * Due to residual magnetism in the Puck and magnetometer itself, with * no magnetic field the Puck will not return `{x:0,y:0,z:0}`. + * * Instead, it's up to you to figure out what the 'zero value' is for your * Puck in your location and to then subtract that from the value returned. If * you're not trying to measure the Earth's magnetic field then it's a good idea * to just take a reading at startup and use that. + * * With the aerial at the top of the board, the `y` reading is vertical, `x` is * horizontal, and `z` is through the board. + * * Readings are in increments of 0.1 micro Tesla (uT). The Earth's magnetic field * varies from around 25-60 uT, so the reading will vary by 250 to 600 depending * on location. + * * @url http://www.espruino.com/Reference#l_Puck_mag */ mag: () => any; /** * Turn on the magnetometer, take a single temperature reading from the MAG3110 chip, and then turn it off again. + * * (If the magnetometer is already on, this just returns the last reading obtained) + * * `E.getTemperature()` uses the microcontroller's temperature sensor, but this uses the magnetometer's. + * * The reading obtained is an integer (so no decimal places), but the sensitivity is factory trimmed. to 1°C, however the temperature * offset isn't - so absolute readings may still need calibrating. + * * @url http://www.espruino.com/Reference#l_Puck_magTemp */ magTemp: () => number; @@ -160,14 +188,18 @@ declare const Puck: { /** * Turn the magnetometer on and start periodic sampling. Samples will then cause * a 'mag' event on 'Puck': - *
    `Puck.magOn();
    -   * Puck.on('mag', function(xyz) {
    -   *   console.log(xyz);
    -   *   // {x:..., y:..., z:...}
    +   *
    +   * ```
    +   * Puck.magOn();
    +   * Puck.on('mag', function(xyz) {
    +   *   console.log(xyz);
    +   *   // {x:..., y:..., z:...}
        * });
    -   * // Turn events off with Puck.magOff();
    -   * `
    + * // Turn events off with Puck.magOff(); + * ``` + * * This call will be ignored if the sampling is already on. + * * If given an argument, the sample rate is set (if not, it's at 0.63 Hz). * The sample rate must be one of the following (resulting in the given power consumption): * @@ -186,36 +218,44 @@ declare const Puck: { * When the battery level drops too low while sampling is turned on, * the magnetometer may stop sampling without warning, even while other * Puck functions continue uninterrupted. + * * Check out [the Puck.js page on the magnetometer](http://www.espruino.com/Puck.js#on-board-peripherals) * for more information. + * * @url http://www.espruino.com/Reference#l_Puck_magOn */ magOn: (samplerate: number) => void; /** * Turn the magnetometer off + * * @url http://www.espruino.com/Reference#l_Puck_magOff */ magOff: () => void; /** * Writes a register on the LIS3MDL / MAX3110 Magnetometer. Can be used for configuring advanced functions. + * * Check out [the Puck.js page on the magnetometer](http://www.espruino.com/Puck.js#on-board-peripherals) * for more information and links to modules that use this function. + * * @url http://www.espruino.com/Reference#l_Puck_magWr */ magWr: (reg: number, data: number) => void; /** * Reads a register from the LIS3MDL / MAX3110 Magnetometer. Can be used for configuring advanced functions. + * * Check out [the Puck.js page on the magnetometer](http://www.espruino.com/Puck.js#on-board-peripherals) * for more information and links to modules that use this function. + * * @url http://www.espruino.com/Reference#l_Puck_magRd */ magRd: (reg: number) => number; /** * On Puck.js v2.0 this will use the on-board PCT2075TP temperature sensor, but on Puck.js the less accurate on-chip Temperature sensor is used. + * * @url http://www.espruino.com/Reference#l_Puck_getTemperature */ getTemperature: () => number; @@ -234,50 +274,63 @@ declare const Puck: { * - 1660 Hz (with Gyro) (not recommended) * * Once `Puck.accelOn()` is called, the `Puck.accel` event will be called each time data is received. `Puck.accelOff()` can be called to turn the accelerometer off. + * * For instance to light the red LED whenever Puck.js is face up: - *
    `Puck.on('accel', function(a) {
    -   *  digitalWrite(LED1, a.acc.z > 0);
    +   *
    +   * ```
    +   * Puck.on('accel', function(a) {
    +   *  digitalWrite(LED1, a.acc.z > 0);
        * });
    -   * Puck.accelOn();
    -   * `
    + * Puck.accelOn(); + * ``` + * * Check out [the Puck.js page on the accelerometer](http://www.espruino.com/Puck.js#on-board-peripherals) * for more information. + * * @url http://www.espruino.com/Reference#l_Puck_accelOn */ accelOn: (samplerate: number) => void; /** * Turn the accelerometer off after it has been turned on by `Puck.accelOn()`. + * * Check out [the Puck.js page on the accelerometer](http://www.espruino.com/Puck.js#on-board-peripherals) * for more information. + * * @url http://www.espruino.com/Reference#l_Puck_accelOff */ accelOff: () => void; /** * Turn on the accelerometer, take a single reading, and then turn it off again. + * * The values reported are the raw values from the chip. In normal configuration: * * - accelerometer: full-scale (32768) is 4g, so you need to divide by 8192 to get correctly scaled values * - gyro: full-scale (32768) is 245 dps, so you need to divide by 134 to get correctly scaled values * * If taking more than one reading, we'd suggest you use `Puck.accelOn()` and the `Puck.accel` event. + * * @url http://www.espruino.com/Reference#l_Puck_accel */ accel: () => any; /** * Writes a register on the LSM6DS3TR-C Accelerometer. Can be used for configuring advanced functions. + * * Check out [the Puck.js page on the accelerometer](http://www.espruino.com/Puck.js#on-board-peripherals) * for more information and links to modules that use this function. + * * @url http://www.espruino.com/Reference#l_Puck_accelWr */ accelWr: (reg: number, data: number) => void; /** * Reads a register from the LSM6DS3TR-C Accelerometer. Can be used for configuring advanced functions. + * * Check out [the Puck.js page on the accelerometer](http://www.espruino.com/Puck.js#on-board-peripherals) * for more information and links to modules that use this function. + * * @url http://www.espruino.com/Reference#l_Puck_accelRd */ accelRd: (reg: number) => number; @@ -285,43 +338,55 @@ declare const Puck: { /** * Transmit the given set of IR pulses - data should be an array of pulse times * in milliseconds (as `[on, off, on, off, on, etc]`). + * * For example `Puck.IR(pulseTimes)` - see [http://www.espruino.com/Puck.js+Infrared](http://www.espruino.com/Puck.js+Infrared) * for a full example. + * * You can also attach an external LED to Puck.js, in which case * you can just execute `Puck.IR(pulseTimes, led_cathode, led_anode)` + * * It is also possible to just supply a single pin for IR transmission * with `Puck.IR(pulseTimes, led_anode)` (on 2v05 and above). + * * @url http://www.espruino.com/Reference#l_Puck_IR */ IR: (data: any, cathode: Pin, anode: Pin) => void; /** * Capacitive sense - the higher the capacitance, the higher the number returned. + * * If called without arguments, a value depending on the capacitance of what is * attached to pin D11 will be returned. If you attach a length of wire to D11, * you'll be able to see a higher value returned when your hand is near the wire * than when it is away. + * * You can also supply pins to use yourself, however if you do this then * the TX pin must be connected to RX pin and sense plate via a roughly 1MOhm * resistor. + * * When not supplying pins, Puck.js uses an internal resistor between D12(tx) * and D11(rx). + * * @url http://www.espruino.com/Reference#l_Puck_capSense */ capSense: (tx: Pin, rx: Pin) => number; /** * Return a light value based on the light the red LED is seeing. + * * **Note:** If called more than 5 times per second, the received light value * may not be accurate. + * * @url http://www.espruino.com/Reference#l_Puck_light */ light: () => number; /** * DEPRECATED - Please use `E.getBattery()` instead. + * * Return an approximate battery percentage remaining based on * a normal CR2032 battery (2.8 - 2.2v). + * * @url http://www.espruino.com/Reference#l_Puck_getBatteryPercentage */ getBatteryPercentage: () => number; @@ -329,12 +394,15 @@ declare const Puck: { /** * Run a self-test, and return true for a pass. This checks for shorts * between pins, so your Puck shouldn't have anything connected to it. + * * **Note:** This self-test auto starts if you hold the button on your Puck * down while inserting the battery, leave it pressed for 3 seconds (while * the green LED is lit) and release it soon after all LEDs turn on. 5 * red blinks is a fail, 5 green is a pass. + * * If the self test fails, it'll set the Puck.js Bluetooth advertising name * to `Puck.js !ERR` where ERR is a 3 letter error code. + * * @url http://www.espruino.com/Reference#l_Puck_selfTest */ selfTest: () => boolean; @@ -343,16 +411,23 @@ declare const Puck: { /** * This library handles interfacing with a FAT32 filesystem on an SD card. The API is designed to be similar to node.js's - However Espruino does not currently support asynchronous file IO, so the functions behave like node.js's xxxxSync functions. Versions of the functions with 'Sync' after them are also provided for compatibility. + * * To use this, you must type `var fs = require('fs')` to get access to the library + * * See [the page on File IO](http://www.espruino.com/File+IO) for more information, and for examples on wiring up an SD card if your device doesn't come with one. + * * **Note:** If you want to remove an SD card after you have started using it, you *must* call `E.unmountSD()` or you may cause damage to the card. + * * @url http://www.espruino.com/Reference#l_fs_undefined */ /** * This is the File object - it allows you to stream data to and from files (As opposed to the `require('fs').readFile(..)` style functions that read an entire file). + * * To create a File object, you must type `var fd = E.openFile('filepath','mode')` - see [E.openFile](#l_E_openFile) for more information. + * * **Note:** If you want to remove an SD card after you have started using it, you *must* call `E.unmountSD()` or you may cause damage to the card. + * * @url http://www.espruino.com/Reference#File */ declare function EspruinoFile(): void; @@ -360,42 +435,49 @@ declare function EspruinoFile(): void; type EspruinoFile = { /** * Close an open file. + * * @url http://www.espruino.com/Reference#l_File_close */ close: () => void; /** * Write data to a file. + * * **Note:** By default this function flushes all changes to the * SD card, which makes it slow (but also safe!). You can use * `E.setFlags({unsyncFiles:1})` to disable this behaviour and * really speed up writes - but then you must be sure to close * all files you are writing before power is lost or you will * cause damage to your SD card's filesystem. + * * @url http://www.espruino.com/Reference#l_File_write */ write: (buffer: any) => number; /** * Read data in a file in byte size chunks + * * @url http://www.espruino.com/Reference#l_File_read */ read: (length: number) => any; /** * Skip the specified number of bytes forward in the file + * * @url http://www.espruino.com/Reference#l_File_skip */ skip: (nBytes: number) => void; /** * Seek to a certain position in the file + * * @url http://www.espruino.com/Reference#l_File_seek */ seek: (nBytes: number) => void; /** * Pipe this file to a stream (an object with a 'write' method) + * * @url http://www.espruino.com/Reference#l_File_pipe */ pipe: (destination: any, options: any) => void; @@ -404,24 +486,29 @@ type EspruinoFile = { /** * Class containing utility functions for the Seeed WIO LTE board + * * @url http://www.espruino.com/Reference#WioLTE */ declare const WioLTE: { /** * Set the WIO's LED + * * @url http://www.espruino.com/Reference#l_WioLTE_LED */ LED: (red: number, green: number, blue: number) => void; /** * Set the power of Grove connectors, except for `D38` and `D39` which are always on. + * * @url http://www.espruino.com/Reference#l_WioLTE_setGrovePower */ setGrovePower: (onoff: boolean) => void; /** * Turn power to the WIO's LED on or off. + * * Turning the LED on won't immediately display a color - that must be done with `WioLTE.LED(r,g,b)` + * * @url http://www.espruino.com/Reference#l_WioLTE_setLEDPower */ setLEDPower: (onoff: boolean) => void; @@ -460,19 +547,23 @@ declare const WioLTE: { /** * Class containing utility functions for [Pixl.js](http://www.espruino.com/Pixl.js) + * * @url http://www.espruino.com/Reference#Pixl */ declare const Pixl: { /** * DEPRECATED - Please use `E.getBattery()` instead. + * * Return an approximate battery percentage remaining based on * a normal CR2032 battery (2.8 - 2.2v) + * * @url http://www.espruino.com/Reference#l_Pixl_getBatteryPercentage */ getBatteryPercentage: () => number; /** * Set the LCD's contrast + * * @url http://www.espruino.com/Reference#l_Pixl_setContrast */ setContrast: (c: number) => void; @@ -489,13 +580,16 @@ declare const Pixl: { /** * Writes a command directly to the ST7567 LCD controller + * * @url http://www.espruino.com/Reference#l_Pixl_lcdw */ lcdw: (c: number) => void; /** * Display a menu on Pixl.js's screen, and set up the buttons to navigate through it. + * * DEPRECATED: Use `E.showMenu` + * * @url http://www.espruino.com/Reference#l_Pixl_menu */ menu: (menu: any) => any; @@ -504,54 +598,64 @@ declare const Pixl: { /** * This class exists in order to interface Espruino with fast-moving trigger wheels. Trigger wheels are physical discs with evenly spaced teeth cut into them, and often with one or two teeth next to each other missing. A sensor sends a signal whenever a tooth passed by, and this allows a device to measure not only RPM, but absolute position. + * * This class is currently in testing - it is NOT AVAILABLE on normal boards. + * * @url http://www.espruino.com/Reference#Trig */ declare const Trig: { /** * Get the position of the trigger wheel at the given time (from getTime) + * * @url http://www.espruino.com/Reference#l_Trig_getPosAtTime */ getPosAtTime: (time: number) => number; /** * Initialise the trigger class + * * @url http://www.espruino.com/Reference#l_Trig_setup */ setup: (pin: Pin, options: any) => void; /** * Set a trigger for a certain point in the cycle + * * @url http://www.espruino.com/Reference#l_Trig_setTrigger */ setTrigger: (num: number, pos: number, pins: any, pulseLength: number) => void; /** * Disable a trigger + * * @url http://www.espruino.com/Reference#l_Trig_killTrigger */ killTrigger: (num: number) => void; /** * Get the current state of a trigger + * * @url http://www.espruino.com/Reference#l_Trig_getTrigger */ getTrigger: (num: number) => any; /** * Get the RPM of the trigger wheel + * * @url http://www.espruino.com/Reference#l_Trig_getRPM */ getRPM: () => number; /** * Get the current error flags from the trigger wheel - and zero them + * * @url http://www.espruino.com/Reference#l_Trig_getErrors */ getErrors: () => number; /** * Get the current error flags from the trigger wheel - and zero them + * * @url http://www.espruino.com/Reference#l_Trig_getErrorArray */ getErrorArray: () => any; @@ -560,13 +664,17 @@ declare const Trig: { /** * Cryptographic functions + * * **Note:** This library is currently only included in builds for boards where there is space. For other boards there is `crypto.js` which implements SHA1 in JS. + * * @url http://www.espruino.com/Reference#l_crypto_undefined */ /** * Class containing AES encryption/decryption + * * **Note:** This library is currently only included in builds for boards where there is space. For other boards there is `crypto.js` which implements SHA1 in JS. + * * @url http://www.espruino.com/Reference#AES */ declare const AES: { @@ -584,8 +692,11 @@ declare const AES: { /** * This class provides Graphics operations that can be applied to a surface. + * * Use Graphics.createXXX to create a graphics object that renders in the way you want. See [the Graphics page](https://www.espruino.com/Graphics) for more information. + * * **Note:** On boards that contain an LCD, there is a built-in 'LCD' object of type Graphics. For instance to draw a line you'd type: `LCD.drawLine(0,0,100,100)` + * * @url http://www.espruino.com/Reference#Graphics */ declare const Graphics: { @@ -593,44 +704,54 @@ declare const Graphics: { * On devices like Pixl.js or HYSTM boards that contain a built-in display * this will return an instance of the graphics class that can be used to * access that display. + * * Internally, this is stored as a member called `gfx` inside the 'hiddenRoot'. + * * @url http://www.espruino.com/Reference#l_Graphics_getInstance */ getInstance: () => any; /** * Create a Graphics object that renders to an Array Buffer. This will have a field called 'buffer' that can get used to get at the buffer itself + * * @url http://www.espruino.com/Reference#l_Graphics_createArrayBuffer */ createArrayBuffer: (width: number, height: number, bpp: number, options: any) => Graphics; /** * Create a Graphics object that renders by calling a JavaScript callback function to draw pixels + * * @url http://www.espruino.com/Reference#l_Graphics_createCallback */ createCallback: (width: number, height: number, bpp: number, callback: any) => Graphics; /** * Create a Graphics object that renders to SDL window (Linux-based devices only) + * * @url http://www.espruino.com/Reference#l_Graphics_createSDL */ createSDL: (width: number, height: number, bpp: number) => Graphics; /** * Create a simple Black and White image for use with `Graphics.drawImage`. + * * Use as follows: - *
    `var img = Graphics.createImage(`
    +   *
    +   * ```
    +   * var img = Graphics.createImage(`
        * XXXXXXXXX
    -   * X       X
    -   * X   X   X
    -   * X   X   X
    -   * X       X
    +   * X       X
    +   * X   X   X
    +   * X   X   X
    +   * X       X
        * XXXXXXXXX
        * `);
        * g.drawImage(img, x,y);
    -   * `
    + * ``` + * * If the characters at the beginning and end of the string are newlines, they * will be ignored. Spaces are treated as `0`, and any other character is a `1` + * * @url http://www.espruino.com/Reference#l_Graphics_createImage */ createImage: (str: any) => any; @@ -640,12 +761,14 @@ declare const Graphics: { type Graphics = { /** * Set the current font + * * @url http://www.espruino.com/Reference#l_Graphics_setFont6x15 */ setFont6x15: (scale: number) => Graphics; /** * Set the current font + * * @url http://www.espruino.com/Reference#l_Graphics_setFont12x20 */ setFont12x20: (scale: number) => Graphics; @@ -655,20 +778,25 @@ type Graphics = { * an offscreen buffer, calling this function will * copy the contents of the offscreen buffer to the * screen. + * * Call this when you have drawn something to Graphics * and you want it shown on the screen. + * * If a display does not have an offscreen buffer, * it may not have a `g.flip()` method. + * * On Bangle.js 1, there are different graphics modes * chosen with `Bangle.setLCDMode()`. The default mode * is unbuffered and in this mode `g.flip()` does not * affect the screen contents. + * * On some devices, this command will attempt to * only update the areas of the screen that have * changed in order to increase speed. If you have * accessed the `Graphics.buffer` directly then you * may need to use `Graphics.flip(true)` to force * a full update of the screen. + * * @url http://www.espruino.com/Reference#l_Graphics_flip */ flip: (all: boolean) => void; @@ -677,41 +805,48 @@ type Graphics = { * On Graphics instances with an offscreen buffer, this * is an `ArrayBuffer` that provides access to the underlying * pixel data. - *
    `g=Graphics.createArrayBuffer(8,8,8)
    -   * g.drawLine(0,0,7,7)
    -   * print(new Uint8Array(g.buffer))
    -   * new Uint8Array([
    -   * 255, 0, 0, 0, 0, 0, 0, 0,
    -   * 0, 255, 0, 0, 0, 0, 0, 0,
    -   * 0, 0, 255, 0, 0, 0, 0, 0,
    -   * 0, 0, 0, 255, 0, 0, 0, 0,
    -   * 0, 0, 0, 0, 255, 0, 0, 0,
    -   * 0, 0, 0, 0, 0, 255, 0, 0,
    -   * 0, 0, 0, 0, 0, 0, 255, 0,
    -   * 0, 0, 0, 0, 0, 0, 0, 255])
    -   * `
    + * + * ``` + * g=Graphics.createArrayBuffer(8,8,8) + * g.drawLine(0,0,7,7) + * print(new Uint8Array(g.buffer)) + * new Uint8Array([ + * 255, 0, 0, 0, 0, 0, 0, 0, + * 0, 255, 0, 0, 0, 0, 0, 0, + * 0, 0, 255, 0, 0, 0, 0, 0, + * 0, 0, 0, 255, 0, 0, 0, 0, + * 0, 0, 0, 0, 255, 0, 0, 0, + * 0, 0, 0, 0, 0, 255, 0, 0, + * 0, 0, 0, 0, 0, 0, 255, 0, + * 0, 0, 0, 0, 0, 0, 0, 255]) + * ``` + * * @url http://www.espruino.com/Reference#l_Graphics_buffer */ buffer: any /** * The width of this Graphics instance + * * @url http://www.espruino.com/Reference#l_Graphics_getWidth */ getWidth: () => number; /** * The height of this Graphics instance + * * @url http://www.espruino.com/Reference#l_Graphics_getHeight */ getHeight: () => number; /** * The number of bits per pixel of this Graphics instance + * * **Note:** Bangle.js 2 behaves a little differently here. The display * is 3 bit, so `getBPP` returns 3 and `asBMP`/`asImage`/etc return 3 bit images. * However in order to allow dithering, the colors returned by `Graphics.getColor` and `Graphics.theme` * are actually 16 bits. + * * @url http://www.espruino.com/Reference#l_Graphics_getBPP */ getBPP: () => number; @@ -719,109 +854,133 @@ type Graphics = { /** * Reset the state of Graphics to the defaults (eg. Color, Font, etc) * that would have been used when Graphics was initialised. + * * @url http://www.espruino.com/Reference#l_Graphics_reset */ reset: () => Graphics; /** * Clear the LCD with the Background Color + * * @url http://www.espruino.com/Reference#l_Graphics_clear */ clear: (reset: boolean) => Graphics; /** * Fill a rectangular area in the Foreground Color + * * On devices with enough memory, you can specify `{x,y,x2,y2,r}` as the first * argument, which allows you to draw a rounded rectangle. + * * @url http://www.espruino.com/Reference#l_Graphics_fillRect */ fillRect: (x1: any, y1: number, x2: number, y2: number) => Graphics; /** * Fill a rectangular area in the Background Color + * * On devices with enough memory, you can specify `{x,y,x2,y2,r}` as the first * argument, which allows you to draw a rounded rectangle. + * * @url http://www.espruino.com/Reference#l_Graphics_clearRect */ clearRect: (x1: any, y1: number, x2: number, y2: number) => Graphics; /** * Draw an unfilled rectangle 1px wide in the Foreground Color + * * @url http://www.espruino.com/Reference#l_Graphics_drawRect */ drawRect: (x1: any, y1: number, x2: number, y2: number) => Graphics; /** * Draw a filled circle in the Foreground Color + * * @url http://www.espruino.com/Reference#l_Graphics_fillCircle */ fillCircle: (x: number, y: number, rad: number) => Graphics; /** * Draw an unfilled circle 1px wide in the Foreground Color + * * @url http://www.espruino.com/Reference#l_Graphics_drawCircle */ drawCircle: (x: number, y: number, rad: number) => Graphics; /** * Draw a circle, centred at (x,y) with radius r in the current foreground color + * * @url http://www.espruino.com/Reference#l_Graphics_drawCircleAA */ drawCircleAA: (x: number, y: number, r: number) => Graphics; /** * Draw a filled ellipse in the Foreground Color + * * @url http://www.espruino.com/Reference#l_Graphics_fillEllipse */ fillEllipse: (x1: number, y1: number, x2: number, y2: number) => Graphics; /** * Draw an ellipse in the Foreground Color + * * @url http://www.espruino.com/Reference#l_Graphics_drawEllipse */ drawEllipse: (x1: number, y1: number, x2: number, y2: number) => Graphics; /** * Get a pixel's color + * * @url http://www.espruino.com/Reference#l_Graphics_getPixel */ getPixel: (x: number, y: number) => number; /** * Set a pixel's color + * * @url http://www.espruino.com/Reference#l_Graphics_setPixel */ setPixel: (x: number, y: number, col: any) => Graphics; /** * Work out the color value to be used in the current bit depth based on the arguments. + * * This is used internally by setColor and setBgColor - *
    `// 1 bit
    -   * g.toColor(1,1,1) => 1
    -   * // 16 bit
    -   * g.toColor(1,0,0) => 0xF800
    -   * `
    + * + * ``` + * // 1 bit + * g.toColor(1,1,1) => 1 + * // 16 bit + * g.toColor(1,0,0) => 0xF800 + * ``` + * * @url http://www.espruino.com/Reference#l_Graphics_toColor */ toColor: (r: any, g: any, b: any) => number; /** * Blend between two colors, and return the result. - *
    `// dark yellow - halfway between red and green
    -   * var col = g.blendColor("#f00","#0f0", 0.5);
    -   * // Get a color 25% brighter than the theme's background colour
    -   * var col = g.blendColor(g.theme.fg,g.theme.bg, 0.75);
    -   * // then...
    -   * g.setColor(col).fillRect(10,10,100,100);
    -   * `
    + * + * ``` + * // dark yellow - halfway between red and green + * var col = g.blendColor("#f00","#0f0", 0.5); + * // Get a color 25% brighter than the theme's background colour + * var col = g.blendColor(g.theme.fg,g.theme.bg, 0.75); + * // then... + * g.setColor(col).fillRect(10,10,100,100); + * ``` + * * @url http://www.espruino.com/Reference#l_Graphics_blendColor */ blendColor: (col_a: any, col_b: any, amt: any) => number; /** * Set the color to use for subsequent drawing operations. + * * If just `r` is specified as an integer, the numeric value will be written directly into a pixel. eg. On a 24 bit `Graphics` instance you set bright blue with either `g.setColor(0,0,1)` or `g.setColor(0x0000FF)`. + * * A good shortcut to ensure you get white on all platforms is to use `g.setColor(-1)` + * * The mapping is as follows: * * - 32 bit: `r,g,b` => `0xFFrrggbb` @@ -830,29 +989,36 @@ type Graphics = { * - Other bpp: `r,g,b` => white if `r+g+b > 50%`, otherwise black (use `r` on its own as an integer) * * If you specified `color_order` when creating the `Graphics` instance, `r`,`g` and `b` will be swapped as you specified. + * * **Note:** On devices with low flash memory, `r` **must** be an integer representing the color in the current bit depth. It cannot * be a floating point value, and `g` and `b` are ignored. + * * @url http://www.espruino.com/Reference#l_Graphics_setColor */ setColor: (r: any, g: any, b: any) => Graphics; /** * Set the background color to use for subsequent drawing operations. + * * See `Graphics.setColor` for more information on the mapping of `r`, `g`, and `b` to pixel values. + * * **Note:** On devices with low flash memory, `r` **must** be an integer representing the color in the current bit depth. It cannot * be a floating point value, and `g` and `b` are ignored. + * * @url http://www.espruino.com/Reference#l_Graphics_setBgColor */ setBgColor: (r: any, g: any, b: any) => Graphics; /** * Get the color to use for subsequent drawing operations + * * @url http://www.espruino.com/Reference#l_Graphics_getColor */ getColor: () => number; /** * Get the background color to use for subsequent drawing operations + * * @url http://www.espruino.com/Reference#l_Graphics_getBgColor */ getBgColor: () => number; @@ -860,27 +1026,35 @@ type Graphics = { /** * This sets the 'clip rect' that subsequent drawing operations are clipped to * sit between. + * * These values are inclusive - eg `g.setClipRect(1,0,5,0)` will ensure that only * pixel rows 1,2,3,4,5 are touched on column 0. + * * **Note:** For maximum flexibility on Bangle.js 1, the values here are not range checked. For normal * use, X and Y should be between 0 and `getWidth()-1`/`getHeight()-1`. + * * **Note:** The x/y values here are rotated, so that if `Graphics.setRotation` is used * they correspond to the coordinates given to the draw functions, *not to the * physical device pixels*. + * * @url http://www.espruino.com/Reference#l_Graphics_setClipRect */ setClipRect: (x1: number, y1: number, x2: number, y2: number) => Graphics; /** * Make subsequent calls to `drawString` use the built-in 4x6 pixel bitmapped Font + * * It is recommended that you use `Graphics.setFont("4x6")` for more flexibility. + * * @url http://www.espruino.com/Reference#l_Graphics_setFontBitmap */ setFontBitmap: () => Graphics; /** * Make subsequent calls to `drawString` use a Vector Font of the given height. + * * It is recommended that you use `Graphics.setFont("Vector", size)` for more flexibility. + * * @url http://www.espruino.com/Reference#l_Graphics_setFontVector */ setFontVector: (size: number) => Graphics; @@ -888,15 +1062,19 @@ type Graphics = { /** * Make subsequent calls to `drawString` use a Custom Font of the given height. See the [Fonts page](http://www.espruino.com/Fonts) for more * information about custom fonts and how to create them. + * * For examples of use, see the [font modules](https://www.espruino.com/Fonts#font-modules). + * * **Note:** while you can specify the character code of the first character with `firstChar`, * the newline character 13 will always be treated as a newline and not rendered. + * * @url http://www.espruino.com/Reference#l_Graphics_setFontCustom */ setFontCustom: (bitmap: any, firstChar: number, width: any, height: number) => Graphics; /** * Set the alignment for subsequent calls to `drawString` + * * @url http://www.espruino.com/Reference#l_Graphics_setFontAlign */ setFontAlign: (x: number, y: number, rotation: number) => Graphics; @@ -915,43 +1093,53 @@ type Graphics = { * - `g.setFont("4x6",2)` - 4x6 bitmap font, doubled in size * * `g.getFont()` will return the current font as a String. + * * For a list of available font names, you can use `g.getFonts()`. + * * @url http://www.espruino.com/Reference#l_Graphics_setFont */ setFont: (name: any, size: number) => Graphics; /** * Get the font by name - can be saved and used with `Graphics.setFont`. + * * Normally this might return something like `"4x6"`, but if a scale * factor is specified, a colon and then the size is reported, like "4x6:2" + * * **Note:** For custom fonts, `Custom` is currently * reported instead of the font name. + * * @url http://www.espruino.com/Reference#l_Graphics_getFont */ getFont: () => string; /** * Return an array of all fonts currently in the Graphics library. + * * **Note:** Vector fonts are specified as `Vector#` where `#` is the font height. As there * are effectively infinite fonts, just `Vector` is included in the list. + * * @url http://www.espruino.com/Reference#l_Graphics_getFonts */ getFonts: () => any[]; /** * Return the height in pixels of the current font + * * @url http://www.espruino.com/Reference#l_Graphics_getFontHeight */ getFontHeight: () => number; /** * Return the size in pixels of a string of text in the current font + * * @url http://www.espruino.com/Reference#l_Graphics_stringWidth */ stringWidth: (str: any) => number; /** * Return the width and height in pixels of a string of text in the current font + * * @url http://www.espruino.com/Reference#l_Graphics_stringMetrics */ stringMetrics: (str: any) => any; @@ -959,110 +1147,139 @@ type Graphics = { /** * Wrap a string to the given pixel width using the current font, and return the * lines as an array. + * * To render within the screen's width you can do: - *
    `g.drawString(g.wrapString(text, g.getWidth()).join("\n")),
    -   * `
    + * + * ``` + * g.drawString(g.wrapString(text, g.getWidth()).join("\n")), + * ``` + * * @url http://www.espruino.com/Reference#l_Graphics_wrapString */ wrapString: (str: any, maxWidth: number) => any; /** * Draw a string of text in the current font. - *
    `g.drawString("Hello World", 10, 10);
    -   * `
    + * + * ``` + * g.drawString("Hello World", 10, 10); + * ``` + * * Images may also be embedded inside strings (eg to render Emoji or characters not in the current font). * To do this, just add `0` then the image string ([about Images](http://www.espruino.com/Graphics#images-bitmaps)) * For example: - *
    `g.drawString("Hi \0\7\5\1\x82 D\x17\xC0");
    -   * // draws:
    -   * // # #  #      #     #
    -   * // # #            #
    -   * // ### ##         #
    -   * // # #  #      #     #
    -   * // # # ###      #####
    -   * `
    + * + * ``` + * g.drawString("Hi \0\7\5\1\x82 D\x17\xC0"); + * // draws: + * // # # # # # + * // # # # + * // ### ## # + * // # # # # # + * // # # ### ##### + * ``` + * * @url http://www.espruino.com/Reference#l_Graphics_drawString */ drawString: (str: any, x: number, y: number, solid: boolean) => Graphics; /** * Draw a line between x1,y1 and x2,y2 in the current foreground color + * * @url http://www.espruino.com/Reference#l_Graphics_drawLine */ drawLine: (x1: number, y1: number, x2: number, y2: number) => Graphics; /** * Draw a line between x1,y1 and x2,y2 in the current foreground color + * * @url http://www.espruino.com/Reference#l_Graphics_drawLineAA */ drawLineAA: (x1: number, y1: number, x2: number, y2: number) => Graphics; /** * Draw a line from the last position of lineTo or moveTo to this position + * * @url http://www.espruino.com/Reference#l_Graphics_lineTo */ lineTo: (x: number, y: number) => Graphics; /** * Move the cursor to a position - see lineTo + * * @url http://www.espruino.com/Reference#l_Graphics_moveTo */ moveTo: (x: number, y: number) => Graphics; /** * Draw a polyline (lines between each of the points in `poly`) in the current foreground color + * * **Note:** there is a limit of 64 points (128 XY elements) for polygons + * * @url http://www.espruino.com/Reference#l_Graphics_drawPoly */ drawPoly: (poly: any, closed: boolean) => Graphics; /** * Draw an **antialiased** polyline (lines between each of the points in `poly`) in the current foreground color + * * **Note:** there is a limit of 64 points (128 XY elements) for polygons + * * @url http://www.espruino.com/Reference#l_Graphics_drawPolyAA */ drawPolyAA: (poly: any, closed: boolean) => Graphics; /** * Draw a filled polygon in the current foreground color. - *
    `g.fillPoly([
    -   *   16, 0,
    -   *   31, 31,
    -   *   26, 31,
    -   *   16, 12,
    -   *   6, 28,
    -   *   0, 27 ]);
    -   * `
    + * + * ``` + * g.fillPoly([ + * 16, 0, + * 31, 31, + * 26, 31, + * 16, 12, + * 6, 28, + * 0, 27 ]); + * ``` + * * This fills from the top left hand side of the polygon (low X, low Y) * *down to but not including* the bottom right. When placed together polygons * will align perfectly without overdraw - but this will not fill the * same pixels as `drawPoly` (drawing a line around the edge of the polygon). + * * **Note:** there is a limit of 64 points (128 XY elements) for polygons + * * @url http://www.espruino.com/Reference#l_Graphics_fillPoly */ fillPoly: (poly: any) => Graphics; /** * Draw a filled polygon in the current foreground color. - *
    `g.fillPolyAA([
    -   *   16, 0,
    -   *   31, 31,
    -   *   26, 31,
    -   *   16, 12,
    -   *   6, 28,
    -   *   0, 27 ]);
    -   * `
    + * + * ``` + * g.fillPolyAA([ + * 16, 0, + * 31, 31, + * 26, 31, + * 16, 12, + * 6, 28, + * 0, 27 ]); + * ``` + * * This fills from the top left hand side of the polygon (low X, low Y) * *down to but not including* the bottom right. When placed together polygons * will align perfectly without overdraw - but this will not fill the * same pixels as `drawPoly` (drawing a line around the edge of the polygon). + * * **Note:** there is a limit of 64 points (128 XY elements) for polygons + * * @url http://www.espruino.com/Reference#l_Graphics_fillPolyAA */ fillPolyAA: (poly: any) => Graphics; /** * Set the current rotation of the graphics device. + * * @url http://www.espruino.com/Reference#l_Graphics_setRotation */ setRotation: (rotation: number, reflect: boolean) => Graphics; @@ -1070,8 +1287,10 @@ type Graphics = { /** * Return the width and height in pixels of an image (either Graphics, Image Object, Image String or ArrayBuffer). Returns * `undefined` if image couldn't be decoded. + * * `frames` is also included is the image contains more information than you'd expect for a single bitmap. In * this case the bitmap might be an animation with multiple frames + * * @url http://www.espruino.com/Reference#l_Graphics_imageMetrics */ imageMetrics: (str: any) => any; @@ -1094,22 +1313,28 @@ type Graphics = { * * If `options` is supplied, `drawImage` will allow images to be rendered at any scale or angle. If `options.rotate` is set it will * center images at `x,y`. `options` must be an object of the form: - *
    `{
    -   *   rotate : float, // the amount to rotate the image in radians (default 0)
    -   *   scale : float, // the amount to scale the image up (default 1)
    -   *   frame : int    // if specified and the image has frames of data
    -   *                  //  after the initial frame, draw one of those frames from the image
    +   *
    +   * ```
    +   * {
    +   *   rotate : float, // the amount to rotate the image in radians (default 0)
    +   *   scale : float, // the amount to scale the image up (default 1)
    +   *   frame : int    // if specified and the image has frames of data
    +   *                  //  after the initial frame, draw one of those frames from the image
        * }
    -   * `
    + * ``` + * * For example: - *
    `// In the top left of the screen
    -   * g.drawImage(img,0,0);
    -   * // In the top left of the screen, twice as big
    -   * g.drawImage(img,0,0,{scale:2});
    -   * // In the center of the screen, twice as big, 45 degrees
    -   * g.drawImage(img, g.getWidth()/2, g.getHeight()/2,
    -   *             {scale:2, rotate:Math.PI/4});
    -   * `
    + * + * ``` + * // In the top left of the screen + * g.drawImage(img,0,0); + * // In the top left of the screen, twice as big + * g.drawImage(img,0,0,{scale:2}); + * // In the center of the screen, twice as big, 45 degrees + * g.drawImage(img, g.getWidth()/2, g.getHeight()/2, + * {scale:2, rotate:Math.PI/4}); + * ``` + * * @url http://www.espruino.com/Reference#l_Graphics_drawImage */ drawImage: (image: any, x: number, y: number, options: any) => Graphics; @@ -1117,22 +1342,25 @@ type Graphics = { /** * Draws multiple images *at once* - which avoids flicker on unbuffered systems * like Bangle.js. Maximum layer count right now is 4. - *
    `layers = [ {
    -   *   {x : int, // x start position
    -   *    y : int, // y start position
    +   *
    +   * ```
    +   * layers = [ {
    +   *   {x : int, // x start position
    +   *    y : int, // y start position
        *    image : string/object,
    -   *    scale : float, // scale factor, default 1
    -   *    rotate : float, // angle in radians
    -   *    center : bool // center on x,y? default is top left
    -   *    repeat : should this image be repeated (tiled?)
    -   *    nobounds : bool // if true, the bounds of the image are not used to work out the default area to draw
    +   *    scale : float, // scale factor, default 1
    +   *    rotate : float, // angle in radians
    +   *    center : bool // center on x,y? default is top left
    +   *    repeat : should this image be repeated (tiled?)
    +   *    nobounds : bool // if true, the bounds of the image are not used to work out the default area to draw
        *   }
        * ]
    -   * options = { // the area to render. Defaults to rendering just enough to cover what's requested
    +   * options = { // the area to render. Defaults to rendering just enough to cover what's requested
        *  x,y,
        *  width,height
        * }
    -   * `
    + * ``` + * * @url http://www.espruino.com/Reference#l_Graphics_drawImages */ drawImages: (layers: any, options: any) => Graphics; @@ -1141,7 +1369,9 @@ type Graphics = { * Return this Graphics object as an Image that can be used with `Graphics.drawImage`. * Check out [the Graphics reference page](http://www.espruino.com/Graphics#images-bitmaps) * for more information on images. + * * Will return undefined if data can't be allocated for the image. + * * The image data itself will be referenced rather than copied if: * * - An image `object` was requested (not `string`) @@ -1151,6 +1381,7 @@ type Graphics = { * * Otherwise data will be copied, which takes up more space and * may be quite slow. + * * @url http://www.espruino.com/Reference#l_Graphics_asImage */ asImage: (type: any) => any; @@ -1158,7 +1389,9 @@ type Graphics = { /** * Return the area of the Graphics canvas that has been modified, and optionally clear * the modified area to 0. + * * For instance if `g.setPixel(10,20)` was called, this would return `{x1:10, y1:20, x2:10, y2:20}` + * * @url http://www.espruino.com/Reference#l_Graphics_getModified */ getModified: (reset: boolean) => any; @@ -1166,55 +1399,70 @@ type Graphics = { /** * Scroll the contents of this graphics in a certain direction. The remaining area * is filled with the background color. + * * Note: This uses repeated pixel reads and writes, so will not work on platforms that * don't support pixel reads. + * * @url http://www.espruino.com/Reference#l_Graphics_scroll */ scroll: (x: number, y: number) => Graphics; /** * Blit one area of the screen (x1,y1 w,h) to another (x2,y2 w,h) - *
    `g.blit({
    -   *   x1:0, y1:0,
    -   *   w:32, h:32,
    -   *   x2:100, y2:100,
    -   *   setModified : true // should we set the modified area?
    +   *
    +   * ```
    +   * g.blit({
    +   *   x1:0, y1:0,
    +   *   w:32, h:32,
    +   *   x2:100, y2:100,
    +   *   setModified : true // should we set the modified area?
        * });
    -   * `
    + * ``` + * * Note: This uses repeated pixel reads and writes, so will not work on platforms that * don't support pixel reads. + * * @url http://www.espruino.com/Reference#l_Graphics_blit */ blit: (options: any) => Graphics; /** * Create a Windows BMP file from this Graphics instance, and return it as a String. + * * @url http://www.espruino.com/Reference#l_Graphics_asBMP */ asBMP: () => any; /** * Create a URL of the form `data:image/bmp;base64,...` that can be pasted into the browser. + * * The Espruino Web IDE can detect this data on the console and render the image inline automatically. + * * @url http://www.espruino.com/Reference#l_Graphics_asURL */ asURL: () => any; /** * Output this image as a bitmap URL of the form `data:image/bmp;base64,...`. The Espruino Web IDE will detect this on the console and will render the image inline automatically. + * * This is identical to `console.log(g.asURL())` - it is just a convenient function for easy debugging and producing screenshots of what is currently in the Graphics instance. + * * **Note:** This may not work on some bit depths of Graphics instances. It will also not work for the main Graphics instance * of Bangle.js 1 as the graphics on Bangle.js 1 are stored in write-only memory. + * * @url http://www.espruino.com/Reference#l_Graphics_dump */ dump: () => void; /** * Calculate the square area under a Bezier curve. + * * x0,y0: start point * x1,y1: control point * y2,y2: end point + * * Max 10 points without start point. + * * @url http://www.espruino.com/Reference#l_Graphics_quadraticBezier */ quadraticBezier: (arr: any, options: any) => any; @@ -1224,51 +1472,64 @@ type Graphics = { * * - An object of the form * - *
    `{
    -   *   x: float, // x offset (default 0)
    -   *   y: float, // y offset (default 0)
    -   *   scale: float, // scale factor (default 1)
    -   *   rotate: float, // angle in radians (default 0)
    +   * ```
    +   * {
    +   *   x: float, // x offset (default 0)
    +   *   y: float, // y offset (default 0)
    +   *   scale: float, // scale factor (default 1)
    +   *   rotate: float, // angle in radians (default 0)
        * }
    -   * `
    + * ``` * * - A six-element array of the form `[a,b,c,d,e,f]`, which represents the 2D transformation matrix * - *
    `a c e
    -   * b d f
    -   * 0 0 1
    -   * `
    + * ``` + * a c e + * b d f + * 0 0 1 + * ``` + * * Apply a transformation to an array of vertices. + * * @url http://www.espruino.com/Reference#l_Graphics_transformVertices */ transformVertices: (verts: any, transformation: any) => any; /** * Returns an object of the form: - *
    `{
    -   *   fg : 0xFFFF,  // foreground colour
    -   *   bg : 0,       // background colour
    -   *   fg2 : 0xFFFF,  // accented foreground colour
    -   *   bg2 : 0x0007,  // accented background colour
    -   *   fgH : 0xFFFF,  // highlighted foreground colour
    -   *   bgH : 0x02F7,  // highlighted background colour
    -   *   dark : true,  // Is background dark (eg. foreground should be a light colour)
    +   *
    +   * ```
    +   * {
    +   *   fg : 0xFFFF,  // foreground colour
    +   *   bg : 0,       // background colour
    +   *   fg2 : 0xFFFF,  // accented foreground colour
    +   *   bg2 : 0x0007,  // accented background colour
    +   *   fgH : 0xFFFF,  // highlighted foreground colour
    +   *   bgH : 0x02F7,  // highlighted background colour
    +   *   dark : true,  // Is background dark (eg. foreground should be a light colour)
        * }
    -   * `
    + * ``` + * * These values can then be passed to `g.setColor`/`g.setBgColor` for example `g.setColor(g.theme.fg2)`. When the Graphics * instance is reset, the background color is automatically set to `g.theme.bg` and foreground is set to `g.theme.fg`. + * * On Bangle.js these values can be changed by writing updated values to `theme` in `settings.js` and reloading the app - or they can * be changed temporarily by calling `Graphics.setTheme` + * * @url http://www.espruino.com/Reference#l_Graphics_theme */ theme: any /** * Set the global colour scheme. On Bangle.js, this is reloaded from `settings.json` for each new app loaded. + * * See `Graphics.theme` for the fields that can be provided. For instance you can change * the background to red using: - *
    `g.setTheme({bg:"#f00"});
    -   * `
    + * + * ``` + * g.setTheme({bg:"#f00"}); + * ``` + * * @url http://www.espruino.com/Reference#l_Graphics_setTheme */ setTheme: (theme: any) => Graphics; @@ -1277,15 +1538,18 @@ type Graphics = { /** * A simple VT100 terminal emulator. + * * When data is sent to the `Terminal` object, `Graphics.getInstance()` * is called and if an instance of `Graphics` is found then characters * are written to it. + * * @url http://www.espruino.com/Reference#l__global_Terminal */ declare const Terminal: Serial; /** * Library that initialises a network device that calls into JavaScript + * * @url http://www.espruino.com/Reference#l_NetworkJS_undefined */ @@ -1293,19 +1557,25 @@ declare const Terminal: Serial; * This library implements a telnet console for the Espruino interpreter. It requires a network * connection, e.g. Wifi, and **currently only functions on the ESP8266 and on Linux **. It uses * port 23 on the ESP8266 and port 2323 on Linux. + * * **Note:** To enable on Linux, run `./espruino --telnet` + * * @url http://www.espruino.com/Reference#l_TelnetServer_undefined */ /** * This class helps to convert URLs into Objects of information ready for http.request/get + * * @url http://www.espruino.com/Reference#url */ declare const url: { /** * A utility function to split a URL into parts + * * This is useful in web servers for instance when handling a request. + * * For instance `url.parse("/a?b=c&d=e",true)` returns `{"method":"GET","host":"","path":"/a?b=c&d=e","pathname":"/a","search":"?b=c&d=e","port":80,"query":{"b":"c","d":"e"}}` + * * @url http://www.espruino.com/Reference#l_url_parse */ parse: (urlStr: any, parseQuery: boolean) => any; @@ -1314,13 +1584,17 @@ declare const url: { /** * This library allows you to create TCPIP servers and clients + * * In order to use this, you will need an extra module to get network connectivity. - * This is designed to be a cut-down version of the [Internet](http://nodejs.org/api/net.html">node.js library
    . Please see the socket
    .write(E.toString([0,1,2,3,4,5])); - * `

    + * + * ``` + * socket.write(E.toString([0,1,2,3,4,5])); + * ``` + * * If you need to send something other than bytes, you can use 'Typed Arrays', or * even `DataView`: - *
    `var d = new DataView(new ArrayBuffer(8)); // 8 byte array buffer
    -   * d.setFloat32(0, 765.3532564); // write float at bytes 0-3
    -   * d.setInt8(4, 42); // write int8 at byte 4
    -   * socket.write(E.toString(d.buffer))
    -   * `
    + * + * ``` + * var d = new DataView(new ArrayBuffer(8)); // 8 byte array buffer + * d.setFloat32(0, 765.3532564); // write float at bytes 0-3 + * d.setInt8(4, 42); // write int8 at byte 4 + * socket.write(E.toString(d.buffer)) + * ``` + * * @url http://www.espruino.com/Reference#l_Socket_write */ write: (data: any) => boolean; /** * Close this socket - optional data to append as an argument. + * * See `Socket.write` for more information about the data argument + * * @url http://www.espruino.com/Reference#l_Socket_end */ end: (data: any) => void; @@ -1397,13 +1686,17 @@ type Socket = { /** * This library allows you to create UDP/DATAGRAM servers and clients + * * In order to use this, you will need an extra module to get network connectivity. - * This is designed to be a cut-down version of the [Internet](http://nodejs.org/api/dgram.html">node.js library
    . Please see the node.js library. Please see the void; /** * Completely uninitialise and power down the CC3000, then reconnect to the old access point. + * * @url http://www.espruino.com/Reference#l_WLAN_reconnect */ reconnect: () => void; /** * Get the current IP address + * * @url http://www.espruino.com/Reference#l_WLAN_getIP */ getIP: () => any; /** * Set the current IP address for get an IP from DHCP (if no options object is specified). + * * **Note:** Changes are written to non-volatile memory, but will only take effect after calling `wlan.reconnect()` + * * @url http://www.espruino.com/Reference#l_WLAN_setIP */ setIP: (options: any) => boolean; @@ -1485,18 +1789,22 @@ type WLAN = { /** * Class containing utility functions for the [ESP8266](http://www.espruino.com/EspruinoESP8266) + * * @url http://www.espruino.com/Reference#ESP8266 */ declare const ESP8266: { /** * **DEPRECATED** - please use `Wifi.ping` instead. + * * Perform a network ping request. The parameter can be either a String or a numeric IP address. + * * @url http://www.espruino.com/Reference#l_ESP8266_ping */ ping: (ipAddr: any, pingCallback: any) => void; /** * Perform a hardware reset/reboot of the esp8266. + * * @url http://www.espruino.com/Reference#l_ESP8266_reboot */ reboot: () => void; @@ -1516,30 +1824,35 @@ declare const ESP8266: { /** * Enable or disable the logging of debug information. A value of `true` enables debug logging while a value of `false` disables debug logging. Debug output is sent to UART1 (gpio2). + * * @url http://www.espruino.com/Reference#l_ESP8266_logDebug */ logDebug: (enable: boolean) => void; /** * Set the debug logging mode. It can be disabled (which frees ~1.2KB of heap), enabled in-memory only, or in-memory and output to a UART. + * * @url http://www.espruino.com/Reference#l_ESP8266_setLog */ setLog: (mode: number) => void; /** * Prints the contents of the debug log to the console. + * * @url http://www.espruino.com/Reference#l_ESP8266_printLog */ printLog: () => void; /** * Returns one line from the log or up to 128 characters. + * * @url http://www.espruino.com/Reference#l_ESP8266_readLog */ readLog: () => void; /** * Dumps info about all sockets to the log. This is for troubleshooting the socket implementation. + * * @url http://www.espruino.com/Reference#l_ESP8266_dumpSocketInfo */ dumpSocketInfo: () => void; @@ -1548,7 +1861,9 @@ declare const ESP8266: { * **Note:** This is deprecated. Use `E.setClock(80/160)` * **Note:** * Set the operating frequency of the ESP8266 processor. The default is 160Mhz. + * * **Warning**: changing the cpu frequency affects the timing of some I/O operations, notably of software SPI and I2C, so things may be a bit slower at 80Mhz. + * * @url http://www.espruino.com/Reference#l_ESP8266_setCPUFreq */ setCPUFreq: (freq: any) => void; @@ -1570,6 +1885,7 @@ declare const ESP8266: { /** * **Note:** This is deprecated. Use `require("Flash").getFree()` + * * @url http://www.espruino.com/Reference#l_ESP8266_getFreeFlash */ getFreeFlash: () => any; @@ -1581,6 +1897,7 @@ declare const ESP8266: { /** * **This function is deprecated.** Please use `require("neopixel").write(pin, data)` instead + * * @url http://www.espruino.com/Reference#l_ESP8266_neopixelWrite */ neopixelWrite: (pin: Pin, arrayOfData: any) => void; @@ -1588,14 +1905,22 @@ declare const ESP8266: { /** * Put the ESP8266 into 'deep sleep' for the given number of microseconds, * reducing power consumption drastically. + * * meaning of option values: + * * 0 - the 108th Byte of init parameter decides whether RF calibration will be performed or not. + * * 1 - run RF calibration after waking up. Power consumption is high. + * * 2 - no RF calibration after waking up. Power consumption is low. + * * 4 - no RF after waking up. Power consumption is the lowest. + * * **Note:** unlike normal Espruino boards' 'deep sleep' mode, ESP8266 deep sleep actually turns off the processor. After the given number of microseconds have elapsed, the ESP8266 will restart as if power had been turned off and then back on. *All contents of RAM will be lost*. * Connect GPIO 16 to RST to enable wakeup. + * * **Special:** 0 microseconds cause sleep forever until external wakeup RST pull down occurs. + * * @url http://www.espruino.com/Reference#l_ESP8266_deepSleep */ deepSleep: (micros: any, option: any) => void; @@ -1604,11 +1929,13 @@ declare const ESP8266: { /** * Library for communication with the WIZnet Ethernet module + * * @url http://www.espruino.com/Reference#l_WIZnet_undefined */ /** * An instantiation of an Ethernet network adaptor + * * @url http://www.espruino.com/Reference#Ethernet */ declare function Ethernet(): void; @@ -1616,14 +1943,17 @@ declare function Ethernet(): void; type Ethernet = { /** * Get the current IP address, subnet, gateway and mac address. + * * @url http://www.espruino.com/Reference#l_Ethernet_getIP */ getIP: (options: any) => any; /** * Set the current IP address or get an IP from DHCP (if no options object is specified) + * * If 'mac' is specified as an option, it must be a string of the form `"00:01:02:03:04:05"` * The default mac is 00:08:DC:01:02:03. + * * @url http://www.espruino.com/Reference#l_Ethernet_setIP */ setIP: (options: any, callback: any) => boolean; @@ -1633,18 +1963,21 @@ type Ethernet = { * min 8 and max 12 char, best set before calling `eth.setIP()` * Default is WIZnet010203, 010203 is the default nic as part of the mac. * Best to set the hosname before calling setIP(). + * * @url http://www.espruino.com/Reference#l_Ethernet_setHostname */ setHostname: (hostname: any, callback: any) => boolean; /** * Returns the hostname + * * @url http://www.espruino.com/Reference#l_Ethernet_getHostname */ getHostname: (callback: any) => any; /** * Get the current status of the ethernet device + * * @url http://www.espruino.com/Reference#l_Ethernet_getStatus */ getStatus: (options: any) => any; @@ -1655,6 +1988,7 @@ type Ethernet = { * The Wifi library is designed to control the Wifi interface. It supports functionality * such as connecting to wifi networks, getting network information, starting an access * point, etc. + * * It is available on these devices: * * - [Espruino WiFi](http://www.espruino.com/WiFi#using-wifi) @@ -1663,6 +1997,7 @@ type Ethernet = { * * **Certain features may or may not be implemented on your device** however * we have documented what is available and what isn't. + * * If you're not using one of the devices above, a separate WiFi library is * provided. For instance: * @@ -1671,24 +2006,33 @@ type Ethernet = { * * [Other ways of connecting to the net](http://www.espruino.com/Internet#related-pages) such * as GSM, Ethernet and LTE have their own libraries. + * * You can use the WiFi library as follows: - *
    `var wifi = require("Wifi");
    - * wifi.connect("my-ssid", {password:"my-pwd"}, function(ap){ console.log("connected:", ap); });
    - * `
    + * + * ``` + * var wifi = require("Wifi"); + * wifi.connect("my-ssid", {password:"my-pwd"}, function(ap){ console.log("connected:", ap); }); + * ``` + * * On ESP32/ESP8266 if you want the connection to happen automatically at boot, add `wifi.save();`. * On other platforms, place `wifi.connect` in a function called `onInit`. + * * @url http://www.espruino.com/Reference#l_Wifi_undefined */ /** * This library allows you to create http servers and make http requests - * In order to use this, you will need an extra module to get network connectivity such as the [WIZnet W5500](https://espruino.com//CC3000">TI CC3000
    or node.js library. Please see the number; /** * Return a string containing characters that have been received + * * @url http://www.espruino.com/Reference#l_httpSRq_read */ read: (chars: number) => any; /** * Pipe this to a stream (an object with a 'write' method) + * * @url http://www.espruino.com/Reference#l_httpSRq_pipe */ pipe: (destination: any, options: any) => void; @@ -1759,6 +2111,7 @@ type httpSRq = { /** * The HTTP server response + * * @url http://www.espruino.com/Reference#httpSRs */ declare function httpSRs(): void; @@ -1766,11 +2119,15 @@ declare function httpSRs(): void; type httpSRs = { /** * The headers to send back along with the HTTP response. + * * The default contents are: - *
    `{
    -   *   "Connection": "close"
    -   *  }
    -   * `
    + * + * ``` + * { + * "Connection": "close" + * } + * ``` + * * @url http://www.espruino.com/Reference#l_httpSRs_headers */ headers: any @@ -1779,12 +2136,14 @@ type httpSRs = { * This function writes the `data` argument as a string. Data that is passed in * (including arrays) will be converted to a string with the normal JavaScript * `toString` method. For more information about sending binary data see `Socket.write` + * * @url http://www.espruino.com/Reference#l_httpSRs_write */ write: (data: any) => boolean; /** * See `Socket.write` for more information about the data argument + * * @url http://www.espruino.com/Reference#l_httpSRs_end */ end: (data: any) => void; @@ -1793,15 +2152,19 @@ type httpSRs = { * Send the given status code and headers. If not explicitly called * this will be done automatically the first time data is written * to the response. + * * This cannot be called twice, or after data has already been sent * in the response. + * * @url http://www.espruino.com/Reference#l_httpSRs_writeHead */ writeHead: (statusCode: number, headers: any) => void; /** * Set a value to send in the header of this HTTP response. This updates the `httpSRs.headers` property. + * * Any headers supplied to `writeHead` will overwrite any headers with the same name. + * * @url http://www.espruino.com/Reference#l_httpSRs_setHeader */ setHeader: (name: any, value: any) => void; @@ -1810,6 +2173,7 @@ type httpSRs = { /** * The HTTP client request, returned by `http.request()` and `http.get()`. + * * @url http://www.espruino.com/Reference#httpCRq */ declare function httpCRq(): void; @@ -1819,13 +2183,16 @@ type httpCRq = { * This function writes the `data` argument as a string. Data that is passed in * (including arrays) will be converted to a string with the normal JavaScript * `toString` method. For more information about sending binary data see `Socket.write` + * * @url http://www.espruino.com/Reference#l_httpCRq_write */ write: (data: any) => boolean; /** * Finish this HTTP request - optional data to append as an argument + * * See `Socket.write` for more information about the data argument + * * @url http://www.espruino.com/Reference#l_httpCRq_end */ end: (data: any) => void; @@ -1834,6 +2201,7 @@ type httpCRq = { /** * The HTTP client response, passed to the callback of `http.request()` an `http.get()`. + * * @url http://www.espruino.com/Reference#httpCRs */ declare function httpCRs(): void; @@ -1841,42 +2209,49 @@ declare function httpCRs(): void; type httpCRs = { /** * The headers received along with the HTTP response + * * @url http://www.espruino.com/Reference#l_httpCRs_headers */ headers: any /** * The HTTP response's status code - usually `"200"` if all went well + * * @url http://www.espruino.com/Reference#l_httpCRs_statusCode */ statusCode: any /** * The HTTP response's status message - Usually `"OK"` if all went well + * * @url http://www.espruino.com/Reference#l_httpCRs_statusMessage */ statusMessage: any /** * The HTTP version reported back by the server - usually `"1.1"` + * * @url http://www.espruino.com/Reference#l_httpCRs_httpVersion */ httpVersion: any /** * Return how many bytes are available to read. If there is a 'data' event handler, this will always return 0. + * * @url http://www.espruino.com/Reference#l_httpCRs_available */ available: () => number; /** * Return a string containing characters that have been received + * * @url http://www.espruino.com/Reference#l_httpCRs_read */ read: (chars: number) => any; /** * Pipe this to a stream (an object with a 'write' method) + * * @url http://www.espruino.com/Reference#l_httpCRs_pipe */ pipe: (destination: any, options: any) => void; @@ -1885,40 +2260,51 @@ type httpCRs = { /** * This library provides TV out capability on the Espruino and Espruino Pico. + * * See the [Television](https://espruino.com//Television) page for more information. + * * @url http://www.espruino.com/Reference#l_tv_undefined */ /** - * Simple library for compression/decompression using [LZSS](https://github.com/atomicobject/heatshrink">heatshrink
    , an Unistroke.new(new Uint8Array([x1, y1, x2, y2, x3, y3, ...])), - * stroke2 : Unistroke.new(new Uint8Array([x1, y1, x2, y2, x3, y3, ...])), - * stroke3 : Unistroke.new(new Uint8Array([x1, y1, x2, y2, x3, y3, ...])) + * + * ``` + * var strokes = { + * stroke1 : Unistroke.new(new Uint8Array([x1, y1, x2, y2, x3, y3, ...])), + * stroke2 : Unistroke.new(new Uint8Array([x1, y1, x2, y2, x3, y3, ...])), + * stroke3 : Unistroke.new(new Uint8Array([x1, y1, x2, y2, x3, y3, ...])) * }; - * var r = Unistroke.recognise(strokes,new Uint8Array([x1, y1, x2, y2, x3, y3, ...])) - * print(r); // stroke1/stroke2/stroke3 - * ` + * var r = Unistroke.recognise(strokes,new Uint8Array([x1, y1, x2, y2, x3, y3, ...])) + * print(r); // stroke1/stroke2/stroke3 + * ``` + * * @url http://www.espruino.com/Reference#Unistroke */ declare const Unistroke: { /** * Create a new Unistroke based on XY coordinates + * * @url http://www.espruino.com/Reference#l_Unistroke_new */ new: (xy: any) => any; /** * Recognise based on an object of named strokes, and a list of XY coordinates + * * @url http://www.espruino.com/Reference#l_Unistroke_recognise */ recognise: (strokes: any, xy: any) => any; @@ -1927,235 +2313,300 @@ declare const Unistroke: { /** * The NRF class is for controlling functionality of the Nordic nRF51/nRF52 chips. + * * Most functionality is related to Bluetooth Low Energy, however there are also some functions related to NFC that apply to NRF52-based devices. + * * @url http://www.espruino.com/Reference#NRF */ declare const NRF: { /** * Return an object with information about the security * state of the current peripheral connection: - *
    `{
    -   *   connected       // The connection is active (not disconnected).
    -   *   encrypted       // Communication on this link is encrypted.
    -   *   mitm_protected  // The encrypted communication is also protected against man-in-the-middle attacks.
    -   *   bonded          // The peer is bonded with us
    -   *   connected_addr  // If connected=true, the MAC address of the currently connected device
    +   *
    +   * ```
    +   * {
    +   *   connected       // The connection is active (not disconnected).
    +   *   encrypted       // Communication on this link is encrypted.
    +   *   mitm_protected  // The encrypted communication is also protected against man-in-the-middle attacks.
    +   *   bonded          // The peer is bonded with us
    +   *   connected_addr  // If connected=true, the MAC address of the currently connected device
        * }
    -   * `
    + * ``` + * * If there is no active connection, `{connected:false}` will be returned. + * * See `NRF.setSecurity` for information about negotiating a secure connection. + * * @url http://www.espruino.com/Reference#l_NRF_getSecurityStatus */ getSecurityStatus: () => any; /** * Get this device's default Bluetooth MAC address. + * * For Puck.js, the last 5 characters of this (eg. `ee:ff`) * are used in the device's advertised Bluetooth name. + * * @url http://www.espruino.com/Reference#l_NRF_getAddress */ getAddress: () => any; /** * Change the services and characteristics Espruino advertises. + * * If you want to **change** the value of a characteristic, you need * to use `NRF.updateServices()` instead + * * To expose some information on Characteristic `ABCD` on service `BCDE` you could do: - *
    `NRF.setServices({
    -   *   0xBCDE : {
    -   *     0xABCD : {
    -   *       value : "Hello",
    -   *       readable : true
    +   *
    +   * ```
    +   * NRF.setServices({
    +   *   0xBCDE : {
    +   *     0xABCD : {
    +   *       value : "Hello",
    +   *       readable : true
        *     }
        *   }
    -   * });
    -   * `
    + * }); + * ``` + * * Or to allow the 3 LEDs to be controlled by writing numbers 0 to 7 to a * characteristic, you can do the following. `evt.data` is an ArrayBuffer. - *
    `NRF.setServices({
    -   *   0xBCDE : {
    -   *     0xABCD : {
    +   *
    +   * ```
    +   * NRF.setServices({
    +   *   0xBCDE : {
    +   *     0xABCD : {
        *       writable : true,
    -   *       onWrite : function(evt) {
    -   *         digitalWrite([LED3,LED2,LED1], evt.data[0]);
    +   *       onWrite : function(evt) {
    +   *         digitalWrite([LED3,LED2,LED1], evt.data[0]);
        *       }
        *     }
        *   }
        * });
    -   * `
    + * ``` + * * You can supply many different options: - *
    `NRF.setServices({
    -   *   0xBCDE : {
    -   *     0xABCD : {
    -   *       value : "Hello", // optional
    -   *       maxLen : 5, // optional (otherwise is length of initial value)
    -   *       broadcast : false, // optional, default is false
    -   *       readable : true,   // optional, default is false
    -   *       writable : true,   // optional, default is false
    -   *       notify : true,   // optional, default is false
    -   *       indicate : true,   // optional, default is false
    -   *       description: "My Characteristic",  // optional, default is null,
    -   *       security: { // optional - see NRF.setSecurity
    -   *         read: { // optional
    -   *           encrypted: false, // optional, default is false
    -   *           mitm: false, // optional, default is false
    -   *           lesc: false, // optional, default is false
    -   *           signed: false // optional, default is false
    +   *
    +   * ```
    +   * NRF.setServices({
    +   *   0xBCDE : {
    +   *     0xABCD : {
    +   *       value : "Hello", // optional
    +   *       maxLen : 5, // optional (otherwise is length of initial value)
    +   *       broadcast : false, // optional, default is false
    +   *       readable : true,   // optional, default is false
    +   *       writable : true,   // optional, default is false
    +   *       notify : true,   // optional, default is false
    +   *       indicate : true,   // optional, default is false
    +   *       description: "My Characteristic",  // optional, default is null,
    +   *       security: { // optional - see NRF.setSecurity
    +   *         read: { // optional
    +   *           encrypted: false, // optional, default is false
    +   *           mitm: false, // optional, default is false
    +   *           lesc: false, // optional, default is false
    +   *           signed: false // optional, default is false
        *         },
    -   *         write: { // optional
    -   *           encrypted: true, // optional, default is false
    -   *           mitm: false, // optional, default is false
    -   *           lesc: false, // optional, default is false
    -   *           signed: false // optional, default is false
    +   *         write: { // optional
    +   *           encrypted: true, // optional, default is false
    +   *           mitm: false, // optional, default is false
    +   *           lesc: false, // optional, default is false
    +   *           signed: false // optional, default is false
        *         }
        *       },
    -   *       onWrite : function(evt) { // optional
    -   *         console.log("Got ", evt.data); // an ArrayBuffer
    +   *       onWrite : function(evt) { // optional
    +   *         console.log("Got ", evt.data); // an ArrayBuffer
        *       },
    -   *       onWriteDesc : function(evt) { // optional - called when the 'cccd' descriptor is written
    -   *         // for example this is called when notifications are requested by the client:
    -   *         console.log("Notifications enabled = ", evt.data[0]&1);
    +   *       onWriteDesc : function(evt) { // optional - called when the 'cccd' descriptor is written
    +   *         // for example this is called when notifications are requested by the client:
    +   *         console.log("Notifications enabled = ", evt.data[0]&1);
        *       }
        *     }
    -   *     // more characteristics allowed
    +   *     // more characteristics allowed
        *   }
    -   *   // more services allowed
    +   *   // more services allowed
        * });
    -   * `
    + * ``` + * * **Note:** UUIDs can be integers between `0` and `0xFFFF`, strings of * the form `"ABCD"`, or strings of the form `"ABCDABCD-ABCD-ABCD-ABCD-ABCDABCDABCD"` + * * `options` can be of the form: - *
    `NRF.setServices(undefined, {
    -   *   hid : new Uint8Array(...), // optional, default is undefined. Enable BLE HID support
    -   *   uart : true, // optional, default is true. Enable BLE UART support
    -   *   advertise: [ '180D' ] // optional, list of service UUIDs to advertise
    -   *   ancs : true, // optional, Bangle.js-only, enable Apple ANCS support for notifications
    -   *   ams : true // optional, Bangle.js-only, enable Apple AMS support for media control
    +   *
    +   * ```
    +   * NRF.setServices(undefined, {
    +   *   hid : new Uint8Array(...), // optional, default is undefined. Enable BLE HID support
    +   *   uart : true, // optional, default is true. Enable BLE UART support
    +   *   advertise: [ '180D' ] // optional, list of service UUIDs to advertise
    +   *   ancs : true, // optional, Bangle.js-only, enable Apple ANCS support for notifications
    +   *   ams : true // optional, Bangle.js-only, enable Apple AMS support for media control
        * });
    -   * `
    + * ``` + * * To enable BLE HID, you must set `hid` to an array which is the BLE report * descriptor. The easiest way to do this is to use the `ble_hid_controls` * or `ble_hid_keyboard` modules. + * * **Note:** Just creating a service doesn't mean that the service will * be advertised. It will only be available after a device connects. To * advertise, specify the UUIDs you wish to advertise in the `advertise` * field of the second `options` argument. For example this will create * and advertise a heart rate service: - *
    `NRF.setServices({
    -   *   0x180D: { // heart_rate
    -   *     0x2A37: { // heart_rate_measurement
    -   *       notify: true,
    -   *       value : [0x06, heartrate],
    +   *
    +   * ```
    +   * NRF.setServices({
    +   *   0x180D: { // heart_rate
    +   *     0x2A37: { // heart_rate_measurement
    +   *       notify: true,
    +   *       value : [0x06, heartrate],
        *     }
        *   }
    -   * }, { advertise: [ '180D' ] });
    -   * `
    + * }, { advertise: [ '180D' ] }); + * ``` + * * You may specify 128 bit UUIDs to advertise, however you may get a `DATA_SIZE` * exception because there is insufficient space in the Bluetooth LE advertising * packet for the 128 bit UART UUID as well as the UUID you specified. In this * case you can add `uart:false` after the `advertise` element to disable the * UART, however you then be unable to connect to Puck.js's console via Bluetooth. + * * If you absolutely require two or more 128 bit UUIDs then you will have to * specify your own raw advertising data packets with `NRF.setAdvertising` + * * **Note:** The services on Espruino can only be modified when there is * no device connected to it as it requires a restart of the Bluetooth stack. * **iOS devices will 'cache' the list of services** so apps like * NRF Connect may incorrectly display the old services even after you * have modified them. To fix this, disable and re-enable Bluetooth on your * iOS device, or use an Android device to run NRF Connect. + * * **Note:** Not all combinations of security configuration values are valid, the valid combinations are: encrypted, * encrypted + mitm, lesc, signed, signed + mitm. See `NRF.setSecurity` for more information. + * * @url http://www.espruino.com/Reference#l_NRF_setServices */ setServices: (data: any, options: any) => void; /** * Change the data that Espruino advertises. + * * Data can be of the form `{ UUID : data_as_byte_array }`. The UUID should be * a [Bluetooth Service ID](https://developer.bluetooth.org/gatt/services/Pages/ServicesHome.aspx). + * * For example to return battery level at 95%, do: - *
    `NRF.setAdvertising({
    -   *   0x180F : [95] // Service data 0x180F = 95
    +   *
    +   * ```
    +   * NRF.setAdvertising({
    +   *   0x180F : [95] // Service data 0x180F = 95
        * });
    -   * `
    + * ``` + * * Or you could report the current temperature: - *
    `setInterval(function() {
    +   *
    +   * ```
    +   * setInterval(function() {
        *   NRF.setAdvertising({
    -   *     0x1809 : [Math.round(E.getTemperature())]
    -   *   });
    -   * }, 30000);
    -   * `
    + * 0x1809 : [Math.round(E.getTemperature())] + * }); + * }, 30000); + * ``` + * * If you specify a value for the object key, Service Data is advertised. However * if you specify `undefined`, the Service UUID is advertised: - *
    `NRF.setAdvertising({
    -   *   0x180D : undefined // Advertise service UUID 0x180D (HRM)
    +   *
    +   * ```
    +   * NRF.setAdvertising({
    +   *   0x180D : undefined // Advertise service UUID 0x180D (HRM)
        * });
    -   * `
    + * ``` + * * Service UUIDs can also be supplied in the second argument of * `NRF.setServices`, but those go in the scan response packet. + * * You can also supply the raw advertising data in an array. For example * to advertise as an Eddystone beacon: - *
    `NRF.setAdvertising([0x03,  // Length of Service List
    -   *   0x03,  // Param: Service List
    -   *   0xAA, 0xFE,  // Eddystone ID
    -   *   0x13,  // Length of Service Data
    -   *   0x16,  // Service Data
    -   *   0xAA, 0xFE, // Eddystone ID
    -   *   0x10,  // Frame type: URL
    -   *   0xF8, // Power
    -   *   0x03, // https://
    -   *   'g','o','o','.','g','l','/','B','3','J','0','O','c'],
    -   *     {interval:100});
    -   * `
    + * + * ``` + * NRF.setAdvertising([0x03, // Length of Service List + * 0x03, // Param: Service List + * 0xAA, 0xFE, // Eddystone ID + * 0x13, // Length of Service Data + * 0x16, // Service Data + * 0xAA, 0xFE, // Eddystone ID + * 0x10, // Frame type: URL + * 0xF8, // Power + * 0x03, // https:// + * 'g','o','o','.','g','l','/','B','3','J','0','O','c'], + * {interval:100}); + * ``` + * * (However for Eddystone we'd advise that you use the [Espruino Eddystone library](https://espruino.com//Puck.js+Eddystone)) + * * **Note:** When specifying data as an array, certain advertising options such as * `discoverable` and `showName` won't have any effect. + * * **Note:** The size of Bluetooth LE advertising packets is limited to 31 bytes. If * you want to advertise more data, consider using an array for `data` (See below), or * `NRF.setScanResponse`. + * * You can even specify an array of arrays or objects, in which case each advertising packet * will be used in turn - for instance to make your device advertise battery level and its name * as well as both Eddystone and iBeacon : - *
    `NRF.setAdvertising([
    -   *   {0x180F : [Puck.getBatteryPercentage()]}, // normal advertising, with battery %
    -   *   require("ble_ibeacon").get(...), // iBeacon
    -   *   require("ble_eddystone").get(...), // eddystone
    -   * ], {interval:300});
    -   * `
    + * + * ``` + * NRF.setAdvertising([ + * {0x180F : [Puck.getBatteryPercentage()]}, // normal advertising, with battery % + * require("ble_ibeacon").get(...), // iBeacon + * require("ble_eddystone").get(...), // eddystone + * ], {interval:300}); + * ``` + * * `options` is an object, which can contain: - *
    `{
    -   *   name: "Hello" // The name of the device
    -   *   showName: true/false // include full name, or nothing
    -   *   discoverable: true/false // general discoverable, or limited - default is limited
    -   *   connectable: true/false // whether device is connectable - default is true
    -   *   scannable : true/false // whether device can be scanned for scan response packets - default is true
    -   *   interval: 600 // Advertising interval in msec, between 20 and 10000 (default is 375ms)
    -   *   manufacturer: 0x0590 // IF sending manufacturer data, this is the manufacturer ID
    -   *   manufacturerData: [...] // IF sending manufacturer data, this is an array of data
    -   *   phy: "1mbps/2mbps/coded" // (NRF52840 only) use the long-range coded phy for transmission (1mbps default)
    +   *
    +   * ```
    +   * {
    +   *   name: "Hello" // The name of the device
    +   *   showName: true/false // include full name, or nothing
    +   *   discoverable: true/false // general discoverable, or limited - default is limited
    +   *   connectable: true/false // whether device is connectable - default is true
    +   *   scannable : true/false // whether device can be scanned for scan response packets - default is true
    +   *   interval: 600 // Advertising interval in msec, between 20 and 10000 (default is 375ms)
    +   *   manufacturer: 0x0590 // IF sending manufacturer data, this is the manufacturer ID
    +   *   manufacturerData: [...] // IF sending manufacturer data, this is an array of data
    +   *   phy: "1mbps/2mbps/coded" // (NRF52840 only) use the long-range coded phy for transmission (1mbps default)
        * }
    -   * `
    + * ``` + * * Setting `connectable` and `scannable` to false gives the lowest power consumption * as the BLE radio doesn't have to listen after sending advertising. + * * **NOTE:** Non-`connectable` advertising can't have an advertising interval less than 100ms * according to the BLE spec. + * * So for instance to set the name of Puck.js without advertising any * other data you can just use the command: - *
    `NRF.setAdvertising({},{name:"Hello"});
    -   * `
    + * + * ``` + * NRF.setAdvertising({},{name:"Hello"}); + * ``` + * * You can also specify 'manufacturer data', which is another form of advertising data. * We've registered the Manufacturer ID 0x0590 (as Pur3 Ltd) for use with *Official * Espruino devices* - use it to advertise whatever data you'd like, but we'd recommend * using JSON. + * * For example by not advertising a device name you can send up to 24 bytes of JSON on * Espruino's manufacturer ID: - *
    `var data = {a:1,b:2};
    -   * NRF.setAdvertising({},{
    +   *
    +   * ```
    +   * var data = {a:1,b:2};
    +   * NRF.setAdvertising({},{
        *   showName:false,
    -   *   manufacturer:0x0590,
    -   *   manufacturerData:JSON.stringify(data)
    +   *   manufacturer:0x0590,
    +   *   manufacturerData:JSON.stringify(data)
        * });
    -   * `
    + * ``` + * * If you're using [EspruinoHub](https://github.com/espruino/EspruinoHub) then it will * automatically decode this into the folling MQTT topics: * @@ -2166,12 +2617,14 @@ declare const NRF: { * Note that **you only have 24 characters available for JSON**, so try to use * the shortest field names possible and avoid floating point values that can * be very long when converted to a String. + * * @url http://www.espruino.com/Reference#l_NRF_setAdvertising */ setAdvertising: (data: any, options: any) => void; /** * If a device is connected to Espruino, disconnect from it. + * * @url http://www.espruino.com/Reference#l_NRF_disconnect */ disconnect: () => void; @@ -2180,8 +2633,11 @@ declare const NRF: { * Disable Bluetooth advertising and disconnect from any device that * connected to Puck.js as a peripheral (this won't affect any devices * that Puck.js initiated connections to). + * * This makes Puck.js undiscoverable, so it can't be connected to. + * * Use `NRF.wake()` to wake up and make Puck.js connectable again. + * * @url http://www.espruino.com/Reference#l_NRF_sleep */ sleep: () => void; @@ -2189,7 +2645,9 @@ declare const NRF: { /** * Enable Bluetooth advertising (this is enabled by default), which * allows other devices to discover and connect to Puck.js. + * * Use `NRF.sleep()` to disable advertising. + * * @url http://www.espruino.com/Reference#l_NRF_wake */ wake: () => void; @@ -2197,18 +2655,23 @@ declare const NRF: { /** * Restart the Bluetooth softdevice (if there is currently a BLE connection, * it will queue a restart to be done when the connection closes). + * * You shouldn't need to call this function in normal usage. However, Nordic's * BLE softdevice has some settings that cannot be reset. For example there * are only a certain number of unique UUIDs. Once these are all used the * only option is to restart the softdevice to clear them all out. + * * @url http://www.espruino.com/Reference#l_NRF_restart */ restart: (callback: any) => void; /** * Set this device's default Bluetooth MAC address: - *
    `NRF.setAddress("ff:ee:dd:cc:bb:aa random");
    -   * `
    + * + * ``` + * NRF.setAddress("ff:ee:dd:cc:bb:aa random"); + * ``` + * * Addresses take the form: * * - `"ff:ee:dd:cc:bb:aa"` or `"ff:ee:dd:cc:bb:aa public"` for a public address @@ -2216,16 +2679,20 @@ declare const NRF: { * * This may throw a `INVALID_BLE_ADDR` error if the upper two bits * of the address don't match the address type. + * * To change the address, Espruino must restart the softdevice. It will only do * so when it is disconnected from other devices. + * * @url http://www.espruino.com/Reference#l_NRF_setAddress */ setAddress: (addr: any) => void; /** * Get the battery level in volts (the voltage that the NRF chip is running off of). + * * This is the battery level of the device itself - it has nothing to with any * device that might be connected. + * * @url http://www.espruino.com/Reference#l_NRF_getBattery */ getBattery: () => number; @@ -2233,19 +2700,24 @@ declare const NRF: { /** * This is just like `NRF.setAdvertising`, except instead of advertising * the data, it returns the packet that would be advertised as an array. + * * @url http://www.espruino.com/Reference#l_NRF_getAdvertisingData */ getAdvertisingData: (data: any, options: any) => any; /** * The raw scan response data should be supplied as an array. For example to return "Sample" for the device name: - *
    `NRF.setScanResponse([0x07,  // Length of Data
    -   *   0x09,  // Param: Complete Local Name
    -   *   'S', 'a', 'm', 'p', 'l', 'e']);
    -   * `
    + * + * ``` + * NRF.setScanResponse([0x07, // Length of Data + * 0x09, // Param: Complete Local Name + * 'S', 'a', 'm', 'p', 'l', 'e']); + * ``` + * * **Note:** `NRF.setServices(..., {advertise:[ ... ]})` writes advertised * services into the scan response - so you can't use both `advertise` * and `NRF.setServices` or one will overwrite the other. + * * @url http://www.espruino.com/Reference#l_NRF_setScanResponse */ setScanResponse: (data: any) => void; @@ -2253,55 +2725,70 @@ declare const NRF: { /** * Update values for the services and characteristics Espruino advertises. * Only services and characteristics previously declared using `NRF.setServices` are affected. + * * To update the '0xABCD' characteristic in the '0xBCDE' service: - *
    `NRF.updateServices({
    -   *   0xBCDE : {
    -   *     0xABCD : {
    -   *       value : "World"
    +   *
    +   * ```
    +   * NRF.updateServices({
    +   *   0xBCDE : {
    +   *     0xABCD : {
    +   *       value : "World"
        *     }
        *   }
        * });
    -   * `
    + * ``` + * * You can also use 128 bit UUIDs, for example `"b7920001-3c1b-4b40-869f-3c0db9be80c6"`. + * * To define a service and characteristic and then notify connected clients of a * change to it when a button is pressed: - *
    `NRF.setServices({
    -   *   0xBCDE : {
    -   *     0xABCD : {
    -   *       value : "Hello",
    -   *       maxLen : 20,
    -   *       notify: true
    +   *
    +   * ```
    +   * NRF.setServices({
    +   *   0xBCDE : {
    +   *     0xABCD : {
    +   *       value : "Hello",
    +   *       maxLen : 20,
    +   *       notify: true
        *     }
        *   }
    -   * });
    -   * setWatch(function() {
    -   *   NRF.updateServices({
    -   *     0xBCDE : {
    -   *       0xABCD : {
    -   *         value : "World!",
    -   *         notify: true
    +   * });
    +   * setWatch(function() {
    +   *   NRF.updateServices({
    +   *     0xBCDE : {
    +   *       0xABCD : {
    +   *         value : "World!",
    +   *         notify: true
        *       }
        *     }
    -   *   });
    -   * }, BTN, { repeat:true, edge:"rising", debounce: 50 });
    -   * `
    + * }); + * }, BTN, { repeat:true, edge:"rising", debounce: 50 }); + * ``` + * * This only works if the characteristic was created with `notify: true` using `NRF.setServices`, * otherwise the characteristic will be updated but no notification will be sent. + * * Also note that `maxLen` was specified. If it wasn't then the maximum length of * the characteristic would have been 5 - the length of `"Hello"`. + * * To indicate (i.e. notify with ACK) connected clients of a change to the '0xABCD' characteristic in the '0xBCDE' service: - *
    `NRF.updateServices({
    -   *   0xBCDE : {
    -   *     0xABCD : {
    -   *       value : "World",
    -   *       indicate: true
    +   *
    +   * ```
    +   * NRF.updateServices({
    +   *   0xBCDE : {
    +   *     0xABCD : {
    +   *       value : "World",
    +   *       indicate: true
        *     }
        *   }
    -   * });
    -   * `
    + * }); + * ``` + * * This only works if the characteristic was created with `indicate: true` using `NRF.setServices`, * otherwise the characteristic will be updated but no notification will be sent. + * * **Note:** See `NRF.setServices` for more information + * * @url http://www.espruino.com/Reference#l_NRF_updateServices */ updateServices: (data: any) => void; @@ -2310,72 +2797,89 @@ declare const NRF: { * Start/stop listening for BLE advertising packets within range. Returns a * `BluetoothDevice` for each advertsing packet. **By default this is not an active scan, so * Scan Response advertising data is not included (see below)** - *
    `// Start scanning
    -   * packets=10;
    -   * NRF.setScan(function(d) {
    +   *
    +   * ```
    +   * // Start scanning
    +   * packets=10;
    +   * NRF.setScan(function(d) {
        *   packets--;
    -   *   if (packets<=0)
    -   *     NRF.setScan(); // stop scanning
    -   *   else
    -   *     console.log(d); // print packet info
    +   *   if (packets<=0)
    +   *     NRF.setScan(); // stop scanning
    +   *   else
    +   *     console.log(d); // print packet info
        * });
    -   * `
    + * ``` + * * Each `BluetoothDevice` will look a bit like: - *
    `BluetoothDevice {
    -   *   "id": "aa:bb:cc:dd:ee:ff", // address
    -   *   "rssi": -89,               // signal strength
    -   *   "services": [ "128bit-uuid", ... ],     // zero or more service UUIDs
    -   *   "data": new Uint8Array([ ... ]).buffer, // ArrayBuffer of returned data
    -   *   "serviceData" : { "0123" : [ 1 ] }, // if service data is in 'data', it's extracted here
    -   *   "manufacturer" : 0x1234, // if manufacturer data is in 'data', the 16 bit manufacturer ID is extracted here
    -   *   "manufacturerData" : [...], // if manufacturer data is in 'data', the data is extracted here
    -   *   "name": "DeviceName"       // the advertised device name
    +   *
    +   * ```
    +   * BluetoothDevice {
    +   *   "id": "aa:bb:cc:dd:ee:ff", // address
    +   *   "rssi": -89,               // signal strength
    +   *   "services": [ "128bit-uuid", ... ],     // zero or more service UUIDs
    +   *   "data": new Uint8Array([ ... ]).buffer, // ArrayBuffer of returned data
    +   *   "serviceData" : { "0123" : [ 1 ] }, // if service data is in 'data', it's extracted here
    +   *   "manufacturer" : 0x1234, // if manufacturer data is in 'data', the 16 bit manufacturer ID is extracted here
    +   *   "manufacturerData" : [...], // if manufacturer data is in 'data', the data is extracted here
    +   *   "name": "DeviceName"       // the advertised device name
        *  }
    -   * `
    + * ``` + * * You can also supply a set of filters (as described in `NRF.requestDevice`) as a second argument, which will * allow you to filter the devices you get a callback for. This helps * to cut down on the time spent processing JavaScript code in areas with * a lot of Bluetooth advertisements. For example to find only devices * with the manufacturer data `0x0590` (Espruino's ID) you could do: - *
    `NRF.setScan(function(d) {
    -   *   console.log(d.manufacturerData);
    -   * }, { filters: [{ manufacturerData:{0x0590:{}} }] });
    -   * `
    + * + * ``` + * NRF.setScan(function(d) { + * console.log(d.manufacturerData); + * }, { filters: [{ manufacturerData:{0x0590:{}} }] }); + * ``` + * * You can also specify `active:true` in the second argument to perform * active scanning (this requests scan response packets) from any * devices it finds. + * * **Note:** Using a filter in `setScan` filters each advertising packet individually. As * a result, if you filter based on a service UUID and a device advertises with multiple packets * (or a scan response when `active:true`) only the packets matching the filter are returned. To * aggregate multiple packets you can use `NRF.findDevices`. + * * **Note:** BLE advertising packets can arrive quickly - faster than you'll * be able to print them to the console. It's best only to print a few, or * to use a function like `NRF.findDevices(..)` which will collate a list * of available devices. + * * **Note:** Using setScan turns the radio's receive mode on constantly. This * can draw a *lot* of power (12mA or so), so you should use it sparingly or * you can run your battery down quickly. + * * @url http://www.espruino.com/Reference#l_NRF_setScan */ setScan: (callback: any, options: any) => void; /** * This function can be used to quickly filter through Bluetooth devices. + * * For instance if you wish to scan for multiple different types of device at the same time * then you could use `NRF.findDevices` with all the filters you're interested in. When scanning * is finished you can then use `NRF.filterDevices` to pick out just the devices of interest. - *
    `// the two types of device we're interested in
    -   * var filter1 = [{serviceData:{"fe95":{}}}];
    -   * var filter2 = [{namePrefix:"Pixl.js"}];
    -   * // the following filter will return both types of device
    +   *
    +   * ```
    +   * // the two types of device we're interested in
    +   * var filter1 = [{serviceData:{"fe95":{}}}];
    +   * var filter2 = [{namePrefix:"Pixl.js"}];
    +   * // the following filter will return both types of device
        * var allFilters = filter1.concat(filter2);
    -   * // now scan for both types of device, and filter them out afterwards
    -   * NRF.findDevices(function(devices) {
    -   *   var devices1 = NRF.filterDevices(devices, filter1);
    -   *   var devices2 = NRF.filterDevices(devices, filter2);
    -   *   // ...
    +   * // now scan for both types of device, and filter them out afterwards
    +   * NRF.findDevices(function(devices) {
    +   *   var devices1 = NRF.filterDevices(devices, filter1);
    +   *   var devices2 = NRF.filterDevices(devices, filter2);
    +   *   // ...
        * }, {filters : allFilters});
    -   * `
    + * ``` + * * @url http://www.espruino.com/Reference#l_NRF_filterDevices */ filterDevices: (devices: any, filters: any) => any; @@ -2383,45 +2887,59 @@ declare const NRF: { /** * Utility function to return a list of BLE devices detected in range. Behind the scenes, * this uses `NRF.setScan(...)` and collates the results. - *
    `NRF.findDevices(function(devices) {
    -   *   console.log(devices);
    -   * }, 1000);
    -   * `
    + * + * ``` + * NRF.findDevices(function(devices) { + * console.log(devices); + * }, 1000); + * ``` + * * prints something like: - *
    `[
    +   *
    +   * ```
    +   * [
        *   BluetoothDevice {
    -   *     "id": "e7:e0:57:ad:36:a2 random",
    -   *     "rssi": -45,
    -   *     "services": [ "4567" ],
    -   *     "serviceData" : { "0123" : [ 1 ] },
    -   *     "manufacturerData" : [...],
    -   *     "data": new ArrayBuffer([ ... ]),
    -   *     "name": "Puck.js 36a2"
    +   *     "id": "e7:e0:57:ad:36:a2 random",
    +   *     "rssi": -45,
    +   *     "services": [ "4567" ],
    +   *     "serviceData" : { "0123" : [ 1 ] },
    +   *     "manufacturerData" : [...],
    +   *     "data": new ArrayBuffer([ ... ]),
    +   *     "name": "Puck.js 36a2"
        *    },
        *   BluetoothDevice {
    -   *     "id": "c0:52:3f:50:42:c9 random",
    -   *     "rssi": -65,
    -   *     "data": new ArrayBuffer([ ... ]),
    -   *     "name": "Puck.js 8f57"
    +   *     "id": "c0:52:3f:50:42:c9 random",
    +   *     "rssi": -65,
    +   *     "data": new ArrayBuffer([ ... ]),
    +   *     "name": "Puck.js 8f57"
        *    }
        *  ]
    -   * `
    + * ``` + * * For more information on the structure returned, see `NRF.setScan`. + * * If you want to scan only for specific devices you can replace the timeout with an object * of the form `{filters: ..., timeout : ..., active: bool}` using the filters * described in `NRF.requestDevice`. For example to search for devices with Espruino's `manufacturerData`: - *
    `NRF.findDevices(function(devices) {
    +   *
    +   * ```
    +   * NRF.findDevices(function(devices) {
        *   ...
    -   * }, {timeout : 2000, filters : [{ manufacturerData:{0x0590:{}} }] });
    -   * `
    + * }, {timeout : 2000, filters : [{ manufacturerData:{0x0590:{}} }] }); + * ``` + * * You could then use [`BluetoothDevice.gatt.connect(...)`](https://espruino.com//Reference#l_BluetoothRemoteGATTServer_connect) on * the device returned to make a connection. + * * You can also use [`NRF.connect(...)`](https://espruino.com//Reference#l_NRF_connect) on just the `id` string returned, which * may be useful if you always want to connect to a specific device. + * * **Note:** Using findDevices turns the radio's receive mode on for 2000ms (or however long you specify). This * can draw a *lot* of power (12mA or so), so you should use it sparingly or you can run your battery down quickly. + * * **Note:** The 'data' field contains the data of *the last packet received*. There may have been more * packets. To get data for each packet individually use `NRF.setScan` instead. + * * @url http://www.espruino.com/Reference#l_NRF_findDevices */ findDevices: (callback: any, options: any) => void; @@ -2429,20 +2947,25 @@ declare const NRF: { /** * Start/stop listening for RSSI values on the currently active connection * (where This device is a peripheral and is being connected to by a 'central' device) - *
    `// Start scanning
    -   * NRF.setRSSIHandler(function(rssi) {
    -   *   console.log(rssi); // prints -85 (or similar)
    +   *
    +   * ```
    +   * // Start scanning
    +   * NRF.setRSSIHandler(function(rssi) {
    +   *   console.log(rssi); // prints -85 (or similar)
        * });
    -   * // Stop Scanning
    -   * NRF.setRSSIHandler();
    -   * `
    + * // Stop Scanning + * NRF.setRSSIHandler(); + * ``` + * * RSSI is the 'Received Signal Strength Indication' in dBm + * * @url http://www.espruino.com/Reference#l_NRF_setRSSIHandler */ setRSSIHandler: (callback: any) => void; /** * Set the BLE radio transmit power. The default TX power is 0 dBm, and + * * @url http://www.espruino.com/Reference#l_NRF_setTxPower */ setTxPower: (power: number) => void; @@ -2451,6 +2974,7 @@ declare const NRF: { * **THIS IS DEPRECATED** - please use `NRF.setConnectionInterval` for * peripheral and `NRF.connect(addr, options)`/`BluetoothRemoteGATTServer.connect(options)` * for central connections. + * * This sets the connection parameters - these affect the transfer speed and * power usage when the device is connected. * @@ -2460,132 +2984,169 @@ declare const NRF: { * When low power connection is enabled, transfers of data over Bluetooth * will be very slow, however power usage while connected will be drastically * decreased. + * * This will only take effect after the connection is disconnected and * re-established. + * * @url http://www.espruino.com/Reference#l_NRF_setLowPowerConnection */ setLowPowerConnection: (lowPower: boolean) => void; /** * Enables NFC and starts advertising the given URL. For example: - *
    `NRF.nfcURL("http://espruino.com");
    -   * `
    + * + * ``` + * NRF.nfcURL("http://espruino.com"); + * ``` + * * @url http://www.espruino.com/Reference#l_NRF_nfcURL */ nfcURL: (url: any) => void; /** * Enables NFC and with an out of band 16 byte pairing key. + * * For example the following will enable out of band pairing on BLE * such that the device will pair when you tap the phone against it: - *
    `var bleKey = [0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF, 0x99, 0x88, 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11, 0x00];
    -   * NRF.on('security',s=>print("security",JSON.stringify(s)));
    -   * NRF.nfcPair(bleKey);
    -   * NRF.setSecurity({oob:bleKey, mitm:true});
    -   * `
    + * + * ``` + * var bleKey = [0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF, 0x99, 0x88, 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11, 0x00]; + * NRF.on('security',s=>print("security",JSON.stringify(s))); + * NRF.nfcPair(bleKey); + * NRF.setSecurity({oob:bleKey, mitm:true}); + * ``` + * * @url http://www.espruino.com/Reference#l_NRF_nfcPair */ nfcPair: (key: any) => void; /** * Enables NFC with a record that will launch the given android app. + * * For example: - *
    `NRF.nfcAndroidApp("no.nordicsemi.android.nrftoolbox")
    -   * `
    + * + * ``` + * NRF.nfcAndroidApp("no.nordicsemi.android.nrftoolbox") + * ``` + * * @url http://www.espruino.com/Reference#l_NRF_nfcAndroidApp */ nfcAndroidApp: (app: any) => void; /** * Enables NFC and starts advertising with Raw data. For example: - *
    `NRF.nfcRaw(new Uint8Array([193, 1, 0, 0, 0, 13, 85, 3, 101, 115, 112, 114, 117, 105, 110, 111, 46, 99, 111, 109]));
    -   * // same as NRF.nfcURL("http://espruino.com");
    -   * `
    + * + * ``` + * NRF.nfcRaw(new Uint8Array([193, 1, 0, 0, 0, 13, 85, 3, 101, 115, 112, 114, 117, 105, 110, 111, 46, 99, 111, 109])); + * // same as NRF.nfcURL("http://espruino.com"); + * ``` + * * @url http://www.espruino.com/Reference#l_NRF_nfcRaw */ nfcRaw: (payload: any) => void; /** * **Advanced NFC Functionality.** If you just want to advertise a URL, use `NRF.nfcURL` instead. + * * Enables NFC and starts advertising. `NFCrx` events will be * fired when data is received. - *
    `NRF.nfcStart();
    -   * `
    + * + * ``` + * NRF.nfcStart(); + * ``` + * * @url http://www.espruino.com/Reference#l_NRF_nfcStart */ nfcStart: (payload: any) => any; /** * **Advanced NFC Functionality.** If you just want to advertise a URL, use `NRF.nfcURL` instead. + * * Disables NFC. - *
    `NRF.nfcStop();
    -   * `
    + * + * ``` + * NRF.nfcStop(); + * ``` + * * @url http://www.espruino.com/Reference#l_NRF_nfcStop */ nfcStop: () => void; /** * **Advanced NFC Functionality.** If you just want to advertise a URL, use `NRF.nfcURL` instead. + * * Acknowledges the last frame and optionally transmits a response. * If payload is an array, then a array.length byte nfc frame is sent. * If payload is a int, then a 4bit ACK/NACK is sent. * **Note:** `nfcSend` should always be called after an `NFCrx` event. - *
    `NRF.nfcSend(new Uint8Array([0x01, 0x02, ...]));
    -   * // or
    -   * NRF.nfcSend(0x0A);
    -   * // or
    -   * NRF.nfcSend();
    -   * `
    + * + * ``` + * NRF.nfcSend(new Uint8Array([0x01, 0x02, ...])); + * // or + * NRF.nfcSend(0x0A); + * // or + * NRF.nfcSend(); + * ``` + * * @url http://www.espruino.com/Reference#l_NRF_nfcSend */ nfcSend: (payload: any) => void; /** * Send a USB HID report. HID must first be enabled with `NRF.setServices({}, {hid: hid_report})` + * * @url http://www.espruino.com/Reference#l_NRF_sendHIDReport */ sendHIDReport: (data: any, callback: any) => void; /** * Check if Apple Notification Center Service (ANCS) is currently active on the BLE connection + * * @url http://www.espruino.com/Reference#l_NRF_ancsIsActive */ ancsIsActive: () => boolean; /** * Send an ANCS action for a specific Notification UID. Corresponds to posaction/negaction in the 'ANCS' event that was received + * * @url http://www.espruino.com/Reference#l_NRF_ancsAction */ ancsAction: (uid: number, positive: boolean) => void; /** * Get ANCS info for a notification, eg: + * * @url http://www.espruino.com/Reference#l_NRF_ancsGetNotificationInfo */ ancsGetNotificationInfo: (uid: number) => Promise; /** * Get ANCS info for an app (add id is available via `ancsGetNotificationInfo`) + * * Promise returns: - *
    `{
    -   *   "uid" : int,
    -   *   "appId" : string,
    -   *   "title" : string,
    -   *   "subtitle" : string,
    -   *   "message" : string,
    -   *   "messageSize" : string,
    -   *   "date" : string,
    -   *   "posAction" : string,
    -   *   "negAction" : string,
    -   *   "name" : string,
    +   *
    +   * ```
    +   * {
    +   *   "uid" : int,
    +   *   "appId" : string,
    +   *   "title" : string,
    +   *   "subtitle" : string,
    +   *   "message" : string,
    +   *   "messageSize" : string,
    +   *   "date" : string,
    +   *   "posAction" : string,
    +   *   "negAction" : string,
    +   *   "name" : string,
        * }
    -   * `
    + * ``` + * * @url http://www.espruino.com/Reference#l_NRF_ancsGetAppInfo */ ancsGetAppInfo: (id: any) => Promise; /** * Check if Apple Media Service (AMS) is currently active on the BLE connection + * * @url http://www.espruino.com/Reference#l_NRF_amsIsActive */ amsIsActive: () => boolean; @@ -2595,12 +3156,12 @@ declare const NRF: { * "playbackinfo" returns a concatenation of three comma-separated values: * * - PlaybackState: a string that represents the integer value of the playback state: + * * - PlaybackStatePaused = 0 * - PlaybackStatePlaying = 1 * - PlaybackStateRewinding = 2 * - PlaybackStateFastForwarding = 3 * - * * - PlaybackRate: a string that represents the floating point value of the playback rate. * - ElapsedTime: a string that represents the floating point value of the elapsed time of the current track, in seconds * @@ -2610,13 +3171,16 @@ declare const NRF: { /** * Get Apple Media Service (AMS) info for the currently-playing track + * * @url http://www.espruino.com/Reference#l_NRF_amsGetTrackInfo */ amsGetTrackInfo: (id: any) => Promise; /** * Send an AMS command to an Apple Media Service device to control music playback + * * Command is one of play, pause, playpause, next, prev, volup, voldown, repeat, shuffle, skipforward, skipback, like, dislike, bookmark + * * @url http://www.espruino.com/Reference#l_NRF_amsCommand */ amsCommand: (id: any) => void; @@ -2624,6 +3188,7 @@ declare const NRF: { /** * Search for available devices matching the given filters. Since we have no UI here, * Espruino will pick the FIRST device it finds, or it'll call `catch`. + * * `options` can have the following fields: * * - `filters` - a list of filters that a device must match before it is returned (see below) @@ -2635,6 +3200,7 @@ declare const NRF: { * - `extended` - (NRF52840 only) support receiving extended-length advertising packets (default=true if phy isn't `"1mbps"`) * * **NOTE:** `timeout` and `active` are not part of the Web Bluetooth standard. + * * The following filter types are implemented: * * - `services` - list of services as strings (all of which must match). 128 bit services must be in the form '01230123-0123-0123-0123-012301230123' @@ -2644,44 +3210,54 @@ declare const NRF: { * - `serviceData` - an object containing service characteristics which must all match (`serviceData:{"1809":{}}`). Matching of actual service data is not supported yet. * - `manufacturerData` - an object containing manufacturer UUIDs which must all match (`manufacturerData:{0x0590:{}}`). Matching of actual manufacturer data is not supported yet. * - *
    `NRF.requestDevice({ filters: [{ namePrefix: 'Puck.js' }] }).then(function(device) { ... });
    -   * // or
    -   * NRF.requestDevice({ filters: [{ services: ['1823'] }] }).then(function(device) { ... });
    -   * // or
    -   * NRF.requestDevice({ filters: [{ manufacturerData:{0x0590:{}} }] }).then(function(device) { ... });
    -   * `
    + * ``` + * NRF.requestDevice({ filters: [{ namePrefix: 'Puck.js' }] }).then(function(device) { ... }); + * // or + * NRF.requestDevice({ filters: [{ services: ['1823'] }] }).then(function(device) { ... }); + * // or + * NRF.requestDevice({ filters: [{ manufacturerData:{0x0590:{}} }] }).then(function(device) { ... }); + * ``` + * * As a full example, to send data to another Puck.js to turn an LED on: - *
    `var gatt;
    -   * NRF.requestDevice({ filters: [{ namePrefix: 'Puck.js' }] }).then(function(device) {
    -   *   return device.gatt.connect();
    -   * }).then(function(g) {
    +   *
    +   * ```
    +   * var gatt;
    +   * NRF.requestDevice({ filters: [{ namePrefix: 'Puck.js' }] }).then(function(device) {
    +   *   return device.gatt.connect();
    +   * }).then(function(g) {
        *   gatt = g;
    -   *   return gatt.getPrimaryService("6e400001-b5a3-f393-e0a9-e50e24dcca9e");
    -   * }).then(function(service) {
    -   *   return service.getCharacteristic("6e400002-b5a3-f393-e0a9-e50e24dcca9e");
    -   * }).then(function(characteristic) {
    -   *   return characteristic.writeValue("LED1.set()\n");
    -   * }).then(function() {
    +   *   return gatt.getPrimaryService("6e400001-b5a3-f393-e0a9-e50e24dcca9e");
    +   * }).then(function(service) {
    +   *   return service.getCharacteristic("6e400002-b5a3-f393-e0a9-e50e24dcca9e");
    +   * }).then(function(characteristic) {
    +   *   return characteristic.writeValue("LED1.set()\n");
    +   * }).then(function() {
        *   gatt.disconnect();
    -   *   console.log("Done!");
    +   *   console.log("Done!");
        * });
    -   * `
    + * ``` + * * Or slightly more concisely, using ES6 arrow functions: - *
    `var gatt;
    -   * NRF.requestDevice({ filters: [{ namePrefix: 'Puck.js' }]}).then(
    -   *   device => device.gatt.connect()).then(
    -   *   g => (gatt=g).getPrimaryService("6e400001-b5a3-f393-e0a9-e50e24dcca9e")).then(
    -   *   service => service.getCharacteristic("6e400002-b5a3-f393-e0a9-e50e24dcca9e")).then(
    -   *   characteristic => characteristic.writeValue("LED1.reset()\n")).then(
    -   *   () => { gatt.disconnect(); console.log("Done!"); } );
    -   * `
    + * + * ``` + * var gatt; + * NRF.requestDevice({ filters: [{ namePrefix: 'Puck.js' }]}).then( + * device => device.gatt.connect()).then( + * g => (gatt=g).getPrimaryService("6e400001-b5a3-f393-e0a9-e50e24dcca9e")).then( + * service => service.getCharacteristic("6e400002-b5a3-f393-e0a9-e50e24dcca9e")).then( + * characteristic => characteristic.writeValue("LED1.reset()\n")).then( + * () => { gatt.disconnect(); console.log("Done!"); } ); + * ``` + * * Note that you have to keep track of the `gatt` variable so that you can * disconnect the Bluetooth connection when you're done. + * * **Note:** Using a filter in `NRF.requestDevice` filters each advertising packet individually. As * soon as a matching advertisement is received, `NRF.requestDevice` resolves the promise and stops * scanning. This means that if you filter based on a service UUID and a device advertises with multiple packets * (or a scan response when `active:true`) only the packet matching the filter is returned - you may not * get the device's name is that was in a separate packet. To aggregate multiple packets you can use `NRF.findDevices`. + * * @url http://www.espruino.com/Reference#l_NRF_requestDevice */ requestDevice: (options: any) => Promise; @@ -2689,31 +3265,39 @@ declare const NRF: { /** * Connect to a BLE device by MAC address. Returns a promise, * the argument of which is the `BluetoothRemoteGATTServer` connection. - *
    `NRF.connect("aa:bb:cc:dd:ee").then(function(server) {
    -   *   // ...
    +   *
    +   * ```
    +   * NRF.connect("aa:bb:cc:dd:ee").then(function(server) {
    +   *   // ...
        * });
    -   * `
    + * ``` + * * This has the same effect as calling `BluetoothDevice.gatt.connect` on a `BluetoothDevice` requested * using `NRF.requestDevice`. It just allows you to specify the address directly (without having to scan). + * * You can use it as follows - this would connect to another Puck device and turn its LED on: - *
    `var gatt;
    -   * NRF.connect("aa:bb:cc:dd:ee random").then(function(g) {
    +   *
    +   * ```
    +   * var gatt;
    +   * NRF.connect("aa:bb:cc:dd:ee random").then(function(g) {
        *   gatt = g;
    -   *   return gatt.getPrimaryService("6e400001-b5a3-f393-e0a9-e50e24dcca9e");
    -   * }).then(function(service) {
    -   *   return service.getCharacteristic("6e400002-b5a3-f393-e0a9-e50e24dcca9e");
    -   * }).then(function(characteristic) {
    -   *   return characteristic.writeValue("LED1.set()\n");
    -   * }).then(function() {
    +   *   return gatt.getPrimaryService("6e400001-b5a3-f393-e0a9-e50e24dcca9e");
    +   * }).then(function(service) {
    +   *   return service.getCharacteristic("6e400002-b5a3-f393-e0a9-e50e24dcca9e");
    +   * }).then(function(characteristic) {
    +   *   return characteristic.writeValue("LED1.set()\n");
    +   * }).then(function() {
        *   gatt.disconnect();
    -   *   console.log("Done!");
    +   *   console.log("Done!");
        * });
    -   * `
    + * ``` + * * **Note:** Espruino Bluetooth devices use a type of BLE address known as 'random static', * which is different to a 'public' address. To connect to an Espruino device you'll need * to use an address string of the form `"aa:bb:cc:dd:ee random"` rather than just * `"aa:bb:cc:dd:ee"`. If you scan for devices with `NRF.findDevices`/`NRF.setScan` then * addresses are already reported in the correct format. + * * @url http://www.espruino.com/Reference#l_NRF_connect */ connect: (mac: any, options: any) => Promise; @@ -2721,10 +3305,13 @@ declare const NRF: { /** * If set to true, whenever a device bonds it will be added to the * whitelist. + * * When set to false, the whitelist is cleared and newly bonded * devices will not be added to the whitelist. + * * **Note:** This is remembered between `reset()`s but isn't * remembered after power-on (you'll have to add it to `onInit()`. + * * @url http://www.espruino.com/Reference#l_NRF_setWhitelist */ setWhitelist: (whitelisting: boolean) => void; @@ -2733,10 +3320,12 @@ declare const NRF: { * When connected, Bluetooth LE devices communicate at a set interval. * Lowering the interval (eg. more packets/second) means a lower delay when * sending data, higher bandwidth, but also more power consumption. + * * By default, when connected as a peripheral Espruino automatically adjusts the * connection interval. When connected it's as fast as possible (7.5ms) but when idle * for over a minute it drops to 200ms. On continued activity (>1 BLE operation) the * interval is raised to 7.5ms again. + * * The options for `interval` are: * * - `undefined` / `"auto"` : (default) automatically adjust connection interval @@ -2745,10 +3334,13 @@ declare const NRF: { * * This configuration is not remembered during a `save()` - you will have to * re-set it via `onInit`. + * * **Note:** If connecting to another device (as Central), you can use * an extra argument to `NRF.connect` or `BluetoothRemoteGATTServer.connect` * to specify a connection interval. + * * **Note:** This overwrites any changes imposed by the deprecated `NRF.setLowPowerConnection` + * * @url http://www.espruino.com/Reference#l_NRF_setConnectionInterval */ setConnectionInterval: (interval: any) => void; @@ -2756,76 +3348,88 @@ declare const NRF: { /** * Sets the security options used when connecting/pairing. This applies to both central * *and* peripheral mode. - *
    `NRF.setSecurity({
    -   *   display : bool  // default false, can this device display a passkey
    +   *
    +   * ```
    +   * NRF.setSecurity({
    +   *   display : bool  // default false, can this device display a passkey
        *                   // - sent via the `BluetoothDevice.passkey` event
    -   *   keyboard : bool // default false, can this device enter a passkey
    +   *   keyboard : bool // default false, can this device enter a passkey
        *                   // - request sent via the `BluetoothDevice.passkeyRequest` event
    -   *   bond : bool // default true, Perform bonding
    -   *   mitm : bool // default false, Man In The Middle protection
    -   *   lesc : bool // default false, LE Secure Connections
    -   *   passkey : // default "", or a 6 digit passkey to use
    -   *   oob : [0..15] // if specified, Out Of Band pairing is enabled and
    -   *                 // the 16 byte pairing code supplied here is used
    -   *   encryptUart : bool // default false (unless oob or passkey specified)
    +   *   bond : bool // default true, Perform bonding
    +   *   mitm : bool // default false, Man In The Middle protection
    +   *   lesc : bool // default false, LE Secure Connections
    +   *   passkey : // default "", or a 6 digit passkey to use
    +   *   oob : [0..15] // if specified, Out Of Band pairing is enabled and
    +   *                 // the 16 byte pairing code supplied here is used
    +   *   encryptUart : bool // default false (unless oob or passkey specified)
        *                      // This sets the BLE UART service such that it
    -   *                      // is encrypted and can only be used from a bonded connection
    +   *                      // is encrypted and can only be used from a bonded connection
        * });
    -   * `
    + * ``` + * * **NOTE:** Some combinations of arguments will cause an error. For example * supplying a passkey without `display:1` is not allowed. If `display:1` is set * you do not require a physical display, the user just needs to know * the passkey you supplied. + * * For instance, to require pairing and to specify a passkey, use: - *
    `NRF.setSecurity({passkey:"123456", mitm:1, display:1});
    -   * `
    + * + * ``` + * NRF.setSecurity({passkey:"123456", mitm:1, display:1}); + * ``` + * * However, while most devices will request a passkey for pairing at * this point it is still possible for a device to connect without * requiring one (eg. using the 'NRF Connect' app). + * * To force a passkey you need to protect each characteristic * you define with `NRF.setSecurity`. For instance the following * code will *require* that the passkey `123456` is entered * before the characteristic `9d020002-bf5f-1d1a-b52a-fe52091d5b12` * can be read. - *
    `NRF.setSecurity({passkey:"123456", mitm:1, display:1});
    +   *
    +   * ```
    +   * NRF.setSecurity({passkey:"123456", mitm:1, display:1});
        * NRF.setServices({
        *   "9d020001-bf5f-1d1a-b52a-fe52091d5b12" : {
        *     "9d020002-bf5f-1d1a-b52a-fe52091d5b12" : {
    -   *       // readable always
    -   *       value : "Not Secret"
    +   *       // readable always
    +   *       value : "Not Secret"
        *     },
        *     "9d020003-bf5f-1d1a-b52a-fe52091d5b12" : {
    -   *       // readable only once bonded
    -   *       value : "Secret",
    -   *       readable : true,
    -   *       security: {
    -   *         read: {
    -   *           mitm: true,
    -   *           encrypted: true
    +   *       // readable only once bonded
    +   *       value : "Secret",
    +   *       readable : true,
    +   *       security: {
    +   *         read: {
    +   *           mitm: true,
    +   *           encrypted: true
        *         }
        *       }
        *     },
        *     "9d020004-bf5f-1d1a-b52a-fe52091d5b12" : {
    -   *       // readable always
    -   *       // writable only once bonded
    -   *       value : "Readable",
    -   *       readable : true,
    -   *       writable : true,
    -   *       onWrite : function(evt) {
    +   *       // readable always
    +   *       // writable only once bonded
    +   *       value : "Readable",
    +   *       readable : true,
    +   *       writable : true,
    +   *       onWrite : function(evt) {
        *         console.log("Wrote ", evt.data);
        *       },
    -   *       security: {
    -   *         write: {
    -   *           mitm: true,
    -   *           encrypted: true
    +   *       security: {
    +   *         write: {
    +   *           mitm: true,
    +   *           encrypted: true
        *         }
        *       }
        *     }
        *   }
        * });
    -   * `
    + * ``` + * * **Note:** If `passkey` or `oob` is specified, the Nordic UART service (if enabled) * will automatically be set to require encryption, but otherwise it is open. + * * @url http://www.espruino.com/Reference#l_NRF_setSecurity */ setSecurity: (options: any) => void; @@ -2839,6 +3443,7 @@ declare const NRF: { /** * The Bluetooth Serial port - used when data is sent or received over Bluetooth Smart on nRF51/nRF52 chips. + * * @url http://www.espruino.com/Reference#l__global_Bluetooth */ declare const Bluetooth: Serial & { @@ -2851,22 +3456,26 @@ declare const Bluetooth: Serial & { /** * A Web Bluetooth-style device - you can request one using `NRF.requestDevice(address)` + * * For example: - *
    `var gatt;
    - * NRF.requestDevice({ filters: [{ name: 'Puck.js abcd' }] }).then(function(device) {
    - *   console.log("found device");
    - *   return device.gatt.connect();
    - * }).then(function(g) {
    + *
    + * ```
    + * var gatt;
    + * NRF.requestDevice({ filters: [{ name: 'Puck.js abcd' }] }).then(function(device) {
    + *   console.log("found device");
    + *   return device.gatt.connect();
    + * }).then(function(g) {
      *   gatt = g;
    - *   console.log("connected");
    - *   return gatt.startBonding();
    - * }).then(function() {
    - *   console.log("bonded", gatt.getSecurityStatus());
    + *   console.log("connected");
    + *   return gatt.startBonding();
    + * }).then(function() {
    + *   console.log("bonded", gatt.getSecurityStatus());
      *   gatt.disconnect();
    - * }).catch(function(e) {
    - *   console.log("ERROR",e);
    + * }).catch(function(e) {
    + *   console.log("ERROR",e);
      * });
    - * `
    + * ``` + * * @url http://www.espruino.com/Reference#BluetoothDevice */ declare function BluetoothDevice(): void; @@ -2884,8 +3493,10 @@ type BluetoothDevice = { /** * To be used as a response when the event `BluetoothDevice.sendPasskey` has been received. + * * **This is not part of the Web Bluetooth Specification.** It has been added * specifically for Espruino. + * * @url http://www.espruino.com/Reference#l_BluetoothDevice_sendPasskey */ sendPasskey: (passkey: any) => void; @@ -2895,7 +3506,9 @@ type BluetoothDevice = { /** * Web Bluetooth-style GATT server - get this using `NRF.connect(address)` * or `NRF.requestDevice(options)` and `response.gatt.connect` + * * [https://webbluetoothcg.github.io/web-bluetooth/#bluetoothremotegattserver](https://webbluetoothcg.github.io/web-bluetooth/#bluetoothremotegattserver) + * * @url http://www.espruino.com/Reference#BluetoothRemoteGATTServer */ declare function BluetoothRemoteGATTServer(): void; @@ -2904,26 +3517,37 @@ type BluetoothRemoteGATTServer = { /** * Connect to a BLE device - returns a promise, * the argument of which is the `BluetoothRemoteGATTServer` connection. + * * See [`NRF.requestDevice`](https://espruino.com//Reference#l_NRF_requestDevice) for usage examples. + * * `options` is an optional object containing: - *
    `{
    -   *    minInterval // min connection interval in milliseconds, 7.5 ms to 4 s
    -   *    maxInterval // max connection interval in milliseconds, 7.5 ms to 4 s
    +   *
    +   * ```
    +   * {
    +   *    minInterval // min connection interval in milliseconds, 7.5 ms to 4 s
    +   *    maxInterval // max connection interval in milliseconds, 7.5 ms to 4 s
        * }
    -   * `
    + * ``` + * * By default the interval is 20-200ms (or 500-1000ms if `NRF.setLowPowerConnection(true)` was called. * During connection Espruino negotiates with the other device to find a common interval that can be * used. + * * For instance calling: - *
    `NRF.requestDevice({ filters: [{ namePrefix: 'Pixl.js' }] }).then(function(device) {
    -   *   return device.gatt.connect({minInterval:7.5, maxInterval:7.5});
    -   * }).then(function(g) {
    -   * `
    + * + * ``` + * NRF.requestDevice({ filters: [{ namePrefix: 'Pixl.js' }] }).then(function(device) { + * return device.gatt.connect({minInterval:7.5, maxInterval:7.5}); + * }).then(function(g) { + * ``` + * * will force the connection to use the fastest connection interval possible (as long as the device * at the other end supports it). + * * **Note:** The Web Bluetooth spec states that if a device hasn't advertised its name, when connected * to a device the central (in this case Espruino) should automatically retrieve the name from the * corresponding characteristic (`0x2a00` on service `0x1800`). Espruino does not automatically do this. + * * @url http://www.espruino.com/Reference#l_BluetoothRemoteGATTServer_connect */ connect: (options: any) => Promise; @@ -2942,10 +3566,12 @@ type BluetoothRemoteGATTServer = { * Disconnect from a previously connected BLE device connected with * `BluetoothRemoteGATTServer.connect` - this does not disconnect from something that has * connected to the Espruino. + * * **Note:** While `.disconnect` is standard Web Bluetooth, in the spec it * returns undefined not a `Promise` for implementation reasons. In Espruino * we return a `Promise` to make it easier to detect when Espruino is free * to connect to something else. + * * @url http://www.espruino.com/Reference#l_BluetoothRemoteGATTServer_disconnect */ disconnect: () => Promise; @@ -2953,23 +3579,27 @@ type BluetoothRemoteGATTServer = { /** * Start negotiating bonding (secure communications) with the connected device, * and return a Promise that is completed on success or failure. - *
    `var gatt;
    -   * NRF.requestDevice({ filters: [{ name: 'Puck.js abcd' }] }).then(function(device) {
    -   *   console.log("found device");
    -   *   return device.gatt.connect();
    -   * }).then(function(g) {
    +   *
    +   * ```
    +   * var gatt;
    +   * NRF.requestDevice({ filters: [{ name: 'Puck.js abcd' }] }).then(function(device) {
    +   *   console.log("found device");
    +   *   return device.gatt.connect();
    +   * }).then(function(g) {
        *   gatt = g;
    -   *   console.log("connected");
    -   *   return gatt.startBonding();
    -   * }).then(function() {
    -   *   console.log("bonded", gatt.getSecurityStatus());
    +   *   console.log("connected");
    +   *   return gatt.startBonding();
    +   * }).then(function() {
    +   *   console.log("bonded", gatt.getSecurityStatus());
        *   gatt.disconnect();
    -   * }).catch(function(e) {
    -   *   console.log("ERROR",e);
    +   * }).catch(function(e) {
    +   *   console.log("ERROR",e);
        * });
    -   * `
    + * ``` + * * **This is not part of the Web Bluetooth Specification.** It has been added * specifically for Espruino. + * * @url http://www.espruino.com/Reference#l_BluetoothRemoteGATTServer_startBonding */ startBonding: (forceRePair: boolean) => Promise; @@ -2977,23 +3607,29 @@ type BluetoothRemoteGATTServer = { /** * Return an object with information about the security * state of the current connection: - *
    `{
    -   *   connected       // The connection is active (not disconnected).
    -   *   encrypted       // Communication on this link is encrypted.
    -   *   mitm_protected  // The encrypted communication is also protected against man-in-the-middle attacks.
    -   *   bonded          // The peer is bonded with us
    +   *
    +   * ```
    +   * {
    +   *   connected       // The connection is active (not disconnected).
    +   *   encrypted       // Communication on this link is encrypted.
    +   *   mitm_protected  // The encrypted communication is also protected against man-in-the-middle attacks.
    +   *   bonded          // The peer is bonded with us
        * }
    -   * `
    + * ``` + * * See `BluetoothRemoteGATTServer.startBonding` for information about * negotiating a secure connection. + * * **This is not part of the Web Bluetooth Specification.** It has been added * specifically for Puck.js. + * * @url http://www.espruino.com/Reference#l_BluetoothRemoteGATTServer_getSecurityStatus */ getSecurityStatus: () => any; /** * See `NRF.connect` for usage examples. + * * @url http://www.espruino.com/Reference#l_BluetoothRemoteGATTServer_getPrimaryService */ getPrimaryService: (service: any) => Promise; @@ -3005,14 +3641,18 @@ type BluetoothRemoteGATTServer = { /** * Start/stop listening for RSSI values on the active GATT connection - *
    `// Start listening for RSSI value updates
    -   * gattServer.setRSSIHandler(function(rssi) {
    -   *   console.log(rssi); // prints -85 (or similar)
    +   *
    +   * ```
    +   * // Start listening for RSSI value updates
    +   * gattServer.setRSSIHandler(function(rssi) {
    +   *   console.log(rssi); // prints -85 (or similar)
        * });
    -   * // Stop listening
    +   * // Stop listening
        * gattServer.setRSSIHandler();
    -   * `
    + * ``` + * * RSSI is the 'Received Signal Strength Indication' in dBm + * * @url http://www.espruino.com/Reference#l_BluetoothRemoteGATTServer_setRSSIHandler */ setRSSIHandler: (callback: any) => void; @@ -3021,7 +3661,9 @@ type BluetoothRemoteGATTServer = { /** * Web Bluetooth-style GATT service - get this using `BluetoothRemoteGATTServer.getPrimaryService(s)` + * * [https://webbluetoothcg.github.io/web-bluetooth/#bluetoothremotegattservice](https://webbluetoothcg.github.io/web-bluetooth/#bluetoothremotegattservice) + * * @url http://www.espruino.com/Reference#BluetoothRemoteGATTService */ declare function BluetoothRemoteGATTService(): void; @@ -3034,6 +3676,7 @@ type BluetoothRemoteGATTService = { /** * See `NRF.connect` for usage examples. + * * @url http://www.espruino.com/Reference#l_BluetoothRemoteGATTService_getCharacteristic */ getCharacteristic: (characteristic: any) => Promise; @@ -3047,7 +3690,9 @@ type BluetoothRemoteGATTService = { /** * Web Bluetooth-style GATT characteristic - get this using `BluetoothRemoteGATTService.getCharacteristic(s)` + * * [https://webbluetoothcg.github.io/web-bluetooth/#bluetoothremotegattcharacteristic](https://webbluetoothcg.github.io/web-bluetooth/#bluetoothremotegattcharacteristic) + * * @url http://www.espruino.com/Reference#BluetoothRemoteGATTCharacteristic */ declare function BluetoothRemoteGATTCharacteristic(): void; @@ -3060,43 +3705,49 @@ type BluetoothRemoteGATTCharacteristic = { /** * Write a characteristic's value - *
    `var device;
    -   * NRF.connect(device_address).then(function(d) {
    +   *
    +   * ```
    +   * var device;
    +   * NRF.connect(device_address).then(function(d) {
        *   device = d;
    -   *   return d.getPrimaryService("service_uuid");
    -   * }).then(function(s) {
    -   *   console.log("Service ",s);
    -   *   return s.getCharacteristic("characteristic_uuid");
    -   * }).then(function(c) {
    -   *   return c.writeValue("Hello");
    -   * }).then(function(d) {
    +   *   return d.getPrimaryService("service_uuid");
    +   * }).then(function(s) {
    +   *   console.log("Service ",s);
    +   *   return s.getCharacteristic("characteristic_uuid");
    +   * }).then(function(c) {
    +   *   return c.writeValue("Hello");
    +   * }).then(function(d) {
        *   device.disconnect();
    -   * }).catch(function() {
    -   *   console.log("Something's broken.");
    +   * }).catch(function() {
    +   *   console.log("Something's broken.");
        * });
    -   * `
    + * ``` + * * @url http://www.espruino.com/Reference#l_BluetoothRemoteGATTCharacteristic_writeValue */ writeValue: (data: any) => Promise; /** * Read a characteristic's value, return a promise containing a `DataView` - *
    `var device;
    -   * NRF.connect(device_address).then(function(d) {
    +   *
    +   * ```
    +   * var device;
    +   * NRF.connect(device_address).then(function(d) {
        *   device = d;
    -   *   return d.getPrimaryService("service_uuid");
    -   * }).then(function(s) {
    -   *   console.log("Service ",s);
    -   *   return s.getCharacteristic("characteristic_uuid");
    -   * }).then(function(c) {
    -   *   return c.readValue();
    -   * }).then(function(d) {
    -   *   console.log("Got:", JSON.stringify(d.buffer));
    +   *   return d.getPrimaryService("service_uuid");
    +   * }).then(function(s) {
    +   *   console.log("Service ",s);
    +   *   return s.getCharacteristic("characteristic_uuid");
    +   * }).then(function(c) {
    +   *   return c.readValue();
    +   * }).then(function(d) {
    +   *   console.log("Got:", JSON.stringify(d.buffer));
        *   device.disconnect();
    -   * }).catch(function() {
    -   *   console.log("Something's broken.");
    +   * }).catch(function() {
    +   *   console.log("Something's broken.");
        * });
    -   * `
    + * ``` + * * @url http://www.espruino.com/Reference#l_BluetoothRemoteGATTCharacteristic_readValue */ readValue: () => Promise; @@ -3104,47 +3755,54 @@ type BluetoothRemoteGATTCharacteristic = { /** * Starts notifications - whenever this characteristic's value changes, a `characteristicvaluechanged` event is fired * and `characteristic.value` will then contain the new value as a `DataView`. - *
    `var device;
    -   * NRF.connect(device_address).then(function(d) {
    +   *
    +   * ```
    +   * var device;
    +   * NRF.connect(device_address).then(function(d) {
        *   device = d;
    -   *   return d.getPrimaryService("service_uuid");
    -   * }).then(function(s) {
    -   *   console.log("Service ",s);
    -   *   return s.getCharacteristic("characteristic_uuid");
    -   * }).then(function(c) {
    -   *   c.on('characteristicvaluechanged', function(event) {
    -   *     console.log("-> ",event.target.value); // this is a DataView
    +   *   return d.getPrimaryService("service_uuid");
    +   * }).then(function(s) {
    +   *   console.log("Service ",s);
    +   *   return s.getCharacteristic("characteristic_uuid");
    +   * }).then(function(c) {
    +   *   c.on('characteristicvaluechanged', function(event) {
    +   *     console.log("-> ",event.target.value); // this is a DataView
        *   });
    -   *   return c.startNotifications();
    -   * }).then(function(d) {
    -   *   console.log("Waiting for notifications");
    -   * }).catch(function() {
    -   *   console.log("Something's broken.");
    +   *   return c.startNotifications();
    +   * }).then(function(d) {
    +   *   console.log("Waiting for notifications");
    +   * }).catch(function() {
    +   *   console.log("Something's broken.");
        * });
    -   * `
    + * ``` + * * For example, to listen to the output of another Puck.js's Nordic * Serial port service, you can use: - *
    `var gatt;
    -   * NRF.connect("pu:ck:js:ad:dr:es random").then(function(g) {
    +   *
    +   * ```
    +   * var gatt;
    +   * NRF.connect("pu:ck:js:ad:dr:es random").then(function(g) {
        *   gatt = g;
    -   *   return gatt.getPrimaryService("6e400001-b5a3-f393-e0a9-e50e24dcca9e");
    -   * }).then(function(service) {
    -   *   return service.getCharacteristic("6e400003-b5a3-f393-e0a9-e50e24dcca9e");
    -   * }).then(function(characteristic) {
    -   *   characteristic.on('characteristicvaluechanged', function(event) {
    -   *     console.log("RX: "+JSON.stringify(event.target.value.buffer));
    +   *   return gatt.getPrimaryService("6e400001-b5a3-f393-e0a9-e50e24dcca9e");
    +   * }).then(function(service) {
    +   *   return service.getCharacteristic("6e400003-b5a3-f393-e0a9-e50e24dcca9e");
    +   * }).then(function(characteristic) {
    +   *   characteristic.on('characteristicvaluechanged', function(event) {
    +   *     console.log("RX: "+JSON.stringify(event.target.value.buffer));
        *   });
    -   *   return characteristic.startNotifications();
    -   * }).then(function() {
    -   *   console.log("Done!");
    +   *   return characteristic.startNotifications();
    +   * }).then(function() {
    +   *   console.log("Done!");
        * });
    -   * `
    + * ``` + * * @url http://www.espruino.com/Reference#l_BluetoothRemoteGATTCharacteristic_startNotifications */ startNotifications: () => Promise; /** * Stop notifications (that were requested with `BluetoothRemoteGATTCharacteristic.startNotifications`) + * * @url http://www.espruino.com/Reference#l_BluetoothRemoteGATTCharacteristic_stopNotifications */ stopNotifications: () => Promise; @@ -3153,22 +3811,29 @@ type BluetoothRemoteGATTCharacteristic = { /** * Class containing utility functions for the [Bangle.js Smart Watch](http://www.espruino.com/Bangle.js) + * * @url http://www.espruino.com/Reference#Bangle */ declare const Bangle: { /** * This function can be used to turn Bangle.js's LCD off or on. + * * This function resets the Bangle's 'activity timer' (like * pressing a button or the screen would) so after a time period * of inactivity set by `Bangle.setLCDTimeout` the screen will * turn off. + * * If you want to keep the screen on permanently (until apps * are changed) you can do: - *
    `Bangle.setLCDTimeout(0); // turn off the timeout
    -   * Bangle.setLCDPower(1); // keep screen on
    -   * `
    + * + * ``` + * Bangle.setLCDTimeout(0); // turn off the timeout + * Bangle.setLCDPower(1); // keep screen on + * ``` + * * **When on full, the LCD draws roughly 40mA.** You can adjust * When brightness using `Bange.setLCDBrightness`. + * * @url http://www.espruino.com/Reference#l_Bangle_setLCDPower */ setLCDPower: (isOn: boolean) => void; @@ -3176,9 +3841,11 @@ declare const Bangle: { /** * This function can be used to adjust the brightness of Bangle.js's display, and * hence prolong its battery life. + * * Due to hardware design constraints, software PWM has to be used which * means that the display may flicker slightly when Bluetooth is active * and the display is not at full power. + * * **Power consumption** * * - 0 = 7mA @@ -3194,6 +3861,7 @@ declare const Bangle: { /** * This function can be used to change the way graphics is handled on Bangle.js. + * * Available options for `Bangle.setLCDMode` are: * * - `Bangle.setLCDMode()` or `Bangle.setLCDMode("direct")` (the default) - The drawable area is 240x240 16 bit. Unbuffered, so draw calls take effect immediately. Terminal and vertical scrolling work (horizontal scrolling doesn't). @@ -3202,13 +3870,16 @@ declare const Bangle: { * - `Bangle.setLCDMode("80x80")` - The drawable area is 80x80 8 bit, `g.getPixel`, terminal, and full scrolling work. Uses an offscreen buffer stored on Bangle.js, `g.flip()` must be called for draw operations to take effect. * * You can also call `Bangle.setLCDMode()` to return to normal, unbuffered `"direct"` mode. + * * @url http://www.espruino.com/Reference#l_Bangle_setLCDMode */ setLCDMode: (mode: any) => void; /** * The current LCD mode. + * * See `Bangle.setLCDMode` for examples. + * * @url http://www.espruino.com/Reference#l_Bangle_getLCDMode */ getLCDMode: () => any; @@ -3217,15 +3888,20 @@ declare const Bangle: { * This can be used to move the displayed memory area up or down temporarily. It's * used for displaying notifications while keeping the main display contents * intact. + * * @url http://www.espruino.com/Reference#l_Bangle_setLCDOffset */ setLCDOffset: (y: number) => void; /** * This function can be used to turn Bangle.js's LCD power saving on or off. + * * With power saving off, the display will remain in the state you set it with `Bangle.setLCDPower`. + * * With power saving on, the display will turn on if a button is pressed, the watch is turned face up, or the screen is updated (see `Bangle.setOptions` for configuration). It'll turn off automatically after the given timeout. + * * **Note:** This function also sets the Backlight and Lock timeout (the time at which the touchscreen/buttons start being ignored). To set both separately, use `Bangle.setOptions` + * * @url http://www.espruino.com/Reference#l_Bangle_setLCDTimeout */ setLCDTimeout: (isOn: number) => void; @@ -3233,8 +3909,10 @@ declare const Bangle: { /** * Set how often the watch should poll for new acceleration/gyro data and kick the Watchdog timer. It isn't * recommended that you make this interval much larger than 1000ms, but values up to 4000ms are allowed. + * * Calling this will set `Bangle.setOptions({powerSave: false})` - disabling the dynamic adjustment of * poll interval to save battery power when Bangle.js is stationary. + * * @url http://www.espruino.com/Reference#l_Bangle_setPollInterval */ setPollInterval: (interval: number) => void; @@ -3267,18 +3945,21 @@ declare const Bangle: { * - `seaLevelPressure` (Bangle.js 2) Normally 1013.25 millibars - this is used for calculating altitude with the pressure sensor * * Where accelerations are used they are in internal units, where `8192 = 1g` + * * @url http://www.espruino.com/Reference#l_Bangle_setOptions */ setOptions: (options: any) => void; /** * Return the current state of options as set by `Bangle.setOptions` + * * @url http://www.espruino.com/Reference#l_Bangle_getOptions */ getOptions: () => any; /** * Also see the `Bangle.lcdPower` event + * * @url http://www.espruino.com/Reference#l_Bangle_isLCDOn */ isLCDOn: () => boolean; @@ -3286,12 +3967,14 @@ declare const Bangle: { /** * This function can be used to lock or unlock Bangle.js * (eg whether buttons and touchscreen work or not) + * * @url http://www.espruino.com/Reference#l_Bangle_setLocked */ setLocked: (isLocked: boolean) => void; /** * Also see the `Bangle.lock` event + * * @url http://www.espruino.com/Reference#l_Bangle_isLocked */ isLocked: () => boolean; @@ -3303,67 +3986,91 @@ declare const Bangle: { /** * Writes a command directly to the ST7735 LCD controller + * * @url http://www.espruino.com/Reference#l_Bangle_lcdWr */ lcdWr: (cmd: number, data: any) => void; /** * Set the power to the Heart rate monitor + * * When on, data is output via the `HRM` event on `Bangle`: - *
    `Bangle.setHRMPower(true, "myapp");
    -   * Bangle.on('HRM',print);
    -   * `
    + * + * ``` + * Bangle.setHRMPower(true, "myapp"); + * Bangle.on('HRM',print); + * ``` + * * *When on, the Heart rate monitor draws roughly 5mA* + * * @url http://www.espruino.com/Reference#l_Bangle_setHRMPower */ setHRMPower: (isOn: boolean, appID: any) => boolean; /** * Is the Heart rate monitor powered? + * * Set power with `Bangle.setHRMPower(...);` + * * @url http://www.espruino.com/Reference#l_Bangle_isHRMOn */ isHRMOn: () => boolean; /** * Set the power to the GPS. + * * When on, data is output via the `GPS` event on `Bangle`: - *
    `Bangle.setGPSPower(true, "myapp");
    -   * Bangle.on('GPS',print);
    -   * `
    + * + * ``` + * Bangle.setGPSPower(true, "myapp"); + * Bangle.on('GPS',print); + * ``` + * * *When on, the GPS draws roughly 20mA* + * * @url http://www.espruino.com/Reference#l_Bangle_setGPSPower */ setGPSPower: (isOn: boolean, appID: any) => boolean; /** * Is the GPS powered? + * * Set power with `Bangle.setGPSPower(...);` + * * @url http://www.espruino.com/Reference#l_Bangle_isGPSOn */ isGPSOn: () => boolean; /** * Get the last available GPS fix info (or `undefined` if GPS is off). + * * The fix info received is the same as you'd get from the `Bangle.GPS` event. + * * @url http://www.espruino.com/Reference#l_Bangle_getGPSFix */ getGPSFix: () => any; /** * Set the power to the Compass + * * When on, data is output via the `mag` event on `Bangle`: - *
    `Bangle.setCompassPower(true, "myapp");
    -   * Bangle.on('mag',print);
    -   * `
    + * + * ``` + * Bangle.setCompassPower(true, "myapp"); + * Bangle.on('mag',print); + * ``` + * * *When on, the compass draws roughly 2mA* + * * @url http://www.espruino.com/Reference#l_Bangle_setCompassPower */ setCompassPower: (isOn: boolean, appID: any) => boolean; /** * Is the compass powered? + * * Set power with `Bangle.setCompassPower(...);` + * * @url http://www.espruino.com/Reference#l_Bangle_isCompassOn */ isCompassOn: () => boolean; @@ -3371,6 +4078,7 @@ declare const Bangle: { /** * Resets the compass minimum/maximum values. Can be used if the compass isn't * providing a reliable heading any more. + * * @url http://www.espruino.com/Reference#l_Bangle_resetCompass */ resetCompass: () => void; @@ -3378,32 +4086,39 @@ declare const Bangle: { /** * Set the power to the barometer IC. Once enbled, `Bangle.pressure` events * are fired each time a new barometer reading is available. + * * When on, the barometer draws roughly 50uA + * * @url http://www.espruino.com/Reference#l_Bangle_setBarometerPower */ setBarometerPower: (isOn: boolean, appID: any) => boolean; /** * Is the Barometer powered? + * * Set power with `Bangle.setBarometerPower(...);` + * * @url http://www.espruino.com/Reference#l_Bangle_isBarometerOn */ isBarometerOn: () => boolean; /** * Returns the current amount of steps recorded by the step counter + * * @url http://www.espruino.com/Reference#l_Bangle_getStepCount */ getStepCount: () => number; /** * Sets the current value of the step counter + * * @url http://www.espruino.com/Reference#l_Bangle_setStepCount */ setStepCount: (count: number) => void; /** * Get the most recent Magnetometer/Compass reading. Data is in the same format as the `Bangle.on('mag',` event. + * * Returns an `{x,y,z,dx,dy,dz,heading}` object * * - `x/y/z` raw x,y,z magnetometer readings @@ -3412,6 +4127,7 @@ declare const Bangle: { * * To get this event you must turn the compass on * with `Bangle.setCompassPower(1)`. + * * @url http://www.espruino.com/Reference#l_Bangle_getCompass */ getCompass: () => any; @@ -3452,67 +4168,79 @@ declare const Bangle: { * Feature flag - If true, this Bangle.js firmware reads `setting.json` and * modifies beep & buzz behaviour accordingly (the bootloader * doesn't need to do it). + * * @url http://www.espruino.com/Reference#l_Bangle_F_BEEPSET */ F_BEEPSET: boolean /** * Reads debug info + * * @url http://www.espruino.com/Reference#l_Bangle_dbg */ dbg: () => any; /** * Writes a register on the accelerometer + * * @url http://www.espruino.com/Reference#l_Bangle_accelWr */ accelWr: (reg: number, data: number) => void; /** * Reads a register from the accelerometer + * * **Note:** On Espruino 2v06 and before this function only returns a number (`cnt` is ignored). + * * @url http://www.espruino.com/Reference#l_Bangle_accelRd */ accelRd: (reg: number, cnt: number) => any; /** * Writes a register on the barometer IC + * * @url http://www.espruino.com/Reference#l_Bangle_barometerWr */ barometerWr: (reg: number, data: number) => void; /** * Reads a register from the barometer IC + * * @url http://www.espruino.com/Reference#l_Bangle_barometerRd */ barometerRd: (reg: number, cnt: number) => any; /** * Writes a register on the Magnetometer/Compass + * * @url http://www.espruino.com/Reference#l_Bangle_compassWr */ compassWr: (reg: number, data: number) => void; /** * Read a register on the Magnetometer/Compass + * * @url http://www.espruino.com/Reference#l_Bangle_compassRd */ compassRd: (reg: number, cnt: number) => any; /** * Writes a register on the Heart rate monitor + * * @url http://www.espruino.com/Reference#l_Bangle_hrmWr */ hrmWr: (reg: number, data: number) => void; /** * Read a register on the Heart rate monitor + * * @url http://www.espruino.com/Reference#l_Bangle_hrmRd */ hrmRd: (reg: number, cnt: number) => any; /** * Changes a pin state on the IO expander + * * @url http://www.espruino.com/Reference#l_Bangle_ioWr */ ioWr: (mask: number, isOn: number) => void; @@ -3520,15 +4248,20 @@ declare const Bangle: { /** * Read temperature, pressure and altitude data. A promise is returned * which will be resolved with `{temperature, pressure, altitude}`. + * * If the Barometer has been turned on with `Bangle.setBarometerPower` then this will * return almost immediately with the reading. If the Barometer is off, conversions take * between 500-750ms. + * * Altitude assumes a sea-level pressure of 1013.25 hPa - *
    `Bangle.getPressure().then(d=>{
    -   *   console.log(d);
    -   *   // {temperature, pressure, altitude}
    +   *
    +   * ```
    +   * Bangle.getPressure().then(d=>{
    +   *   console.log(d);
    +   *   // {temperature, pressure, altitude}
        * });
    -   * `
    + * ``` + * * @url http://www.espruino.com/Reference#l_Bangle_getPressure */ getPressure: () => any; @@ -3537,26 +4270,31 @@ declare const Bangle: { * Perform a Spherical [Web Mercator projection](https://en.wikipedia.org/wiki/Web_Mercator_projection) * of latitude and longitude into `x` and `y` coordinates, which are roughly * equivalent to meters from `{lat:0,lon:0}`. + * * This is the formula used for most online mapping and is a good way * to compare GPS coordinates to work out the distance between them. + * * @url http://www.espruino.com/Reference#l_Bangle_project */ project: (latlong: any) => any; /** * Use the piezo speaker to Beep for a certain time period and frequency + * * @url http://www.espruino.com/Reference#l_Bangle_beep */ beep: (time: number, freq: number) => Promise; /** * Use the vibration motor to buzz for a certain time period + * * @url http://www.espruino.com/Reference#l_Bangle_buzz */ buzz: (time: number, strength: number) => Promise; /** * Turn Bangle.js off. It can only be woken by pressing BTN1. + * * @url http://www.espruino.com/Reference#l_Bangle_off */ off: () => void; @@ -3564,11 +4302,13 @@ declare const Bangle: { /** * Turn Bangle.js (mostly) off, but keep the CPU in sleep * mode until BTN1 is pressed to preserve the RTC (current time). + * * @url http://www.espruino.com/Reference#l_Bangle_softOff */ softOff: () => void; /** + * * * - On platforms with an LCD of >=8bpp this is 222 x 104 x 2 bits * - Otherwise it's 119 x 56 x 1 bits @@ -3580,8 +4320,10 @@ declare const Bangle: { /** * Load all widgets from flash Storage. Call this once at the beginning * of your application if you want any on-screen widgets to be loaded. + * * They will be loaded into a global `WIDGETS` array, and * can be rendered with `Bangle.drawWidgets`. + * * @url http://www.espruino.com/Reference#l_Bangle_loadWidgets */ loadWidgets: () => void; @@ -3594,6 +4336,7 @@ declare const Bangle: { /** * Load the Bangle.js app launcher, which will allow the user * to select an application to launch. + * * @url http://www.espruino.com/Reference#l_Bangle_showLauncher */ showLauncher: () => void; @@ -3606,9 +4349,11 @@ declare const Bangle: { /** * Erase all storage and reload it with the default * contents. + * * This is only available on Bangle.js 2.0. On Bangle.js 1.0 * you need to use `Install Default Apps` under the `More...` tab * of [http://banglejs.com/apps](http://banglejs.com/apps) + * * @url http://www.espruino.com/Reference#l_Bangle_factoryReset */ factoryReset: () => void; @@ -3616,6 +4361,7 @@ declare const Bangle: { /** * Returns the rectangle on the screen that is currently * reserved for the app. + * * @url http://www.espruino.com/Reference#l_Bangle_appRect */ appRect: any @@ -3624,13 +4370,16 @@ declare const Bangle: { /** * This library allows you to write to Neopixel/WS281x/APA10x/SK6812 LED strips + * * These use a high speed single-wire protocol which needs platform-specific * implementation on some devices - hence this library to simplify things. + * * @url http://www.espruino.com/Reference#l_neopixel_undefined */ /** * Create a software OneWire implementation on the given pin + * * @url http://www.espruino.com/Reference#l_OneWire_OneWire */ declare function OneWire(pin: Pin): any; @@ -3638,36 +4387,42 @@ declare function OneWire(pin: Pin): any; type OneWire = { /** * Perform a reset cycle + * * @url http://www.espruino.com/Reference#l_OneWire_reset */ reset: () => boolean; /** * Select a ROM - always performs a reset first + * * @url http://www.espruino.com/Reference#l_OneWire_select */ select: (rom: any) => void; /** * Skip a ROM + * * @url http://www.espruino.com/Reference#l_OneWire_skip */ skip: () => void; /** * Write one or more bytes + * * @url http://www.espruino.com/Reference#l_OneWire_write */ write: (data: any, power: boolean) => void; /** * Read a byte + * * @url http://www.espruino.com/Reference#l_OneWire_read */ read: (count: any) => any; /** * Search for devices + * * @url http://www.espruino.com/Reference#l_OneWire_search */ search: (command: number) => any; @@ -3690,6 +4445,7 @@ type OneWire = { * * If you want to access arrays of differing types of data * you may also find `DataView` useful. + * * @url http://www.espruino.com/Reference#ArrayBufferView */ declare function EspruinoArrayBufferView(): void; @@ -3697,110 +4453,130 @@ declare function EspruinoArrayBufferView(): void; type EspruinoArrayBufferView = { /** * The buffer this view references + * * @url http://www.espruino.com/Reference#l_ArrayBufferView_buffer */ buffer: any /** * The length, in bytes, of the `ArrayBufferView` + * * @url http://www.espruino.com/Reference#l_ArrayBufferView_byteLength */ byteLength: number /** * The offset, in bytes, to the first byte of the view within the backing `ArrayBuffer` + * * @url http://www.espruino.com/Reference#l_ArrayBufferView_byteOffset */ byteOffset: number /** * Copy the contents of `array` into this one, mapping `this[x+offset]=array[x];` + * * @url http://www.espruino.com/Reference#l_ArrayBufferView_set */ set: (arr: any, offset: number) => void; /** * Return an array which is made from the following: `A.map(function) = [function(A[0]), function(A[1]), ...]` + * * **Note:** This returns an `ArrayBuffer` of the same type it was called on. To get an `Array`, use `Array.map`, eg. `[].map.call(myArray, x=>x+1)` + * * @url http://www.espruino.com/Reference#l_ArrayBufferView_map */ map: (fn: any, thisArg: any) => EspruinoArrayBufferView; /** * Returns a smaller part of this array which references the same data (it doesn't copy it). + * * @url http://www.espruino.com/Reference#l_ArrayBufferView_subarray */ subarray: (begin: number, end: any) => EspruinoArrayBufferView; /** * Return the index of the value in the array, or `-1` + * * @url http://www.espruino.com/Reference#l_ArrayBufferView_indexOf */ indexOf: (value: any, startIndex: number) => any; /** * Return `true` if the array includes the value, `false` otherwise + * * @url http://www.espruino.com/Reference#l_ArrayBufferView_includes */ includes: (value: any, startIndex: number) => boolean; /** * Join all elements of this array together into one string, using 'separator' between them. eg. `[1,2,3].join(' ')=='1 2 3'` + * * @url http://www.espruino.com/Reference#l_ArrayBufferView_join */ join: (separator: any) => any; /** * Do an in-place quicksort of the array + * * @url http://www.espruino.com/Reference#l_ArrayBufferView_sort */ sort: (variable: any) => EspruinoArrayBufferView; /** * Executes a provided function once per array element. + * * @url http://www.espruino.com/Reference#l_ArrayBufferView_forEach */ forEach: (fn: any, thisArg: any) => void; /** * Execute `previousValue=initialValue` and then `previousValue = callback(previousValue, currentValue, index, array)` for each element in the array, and finally return previousValue. + * * @url http://www.espruino.com/Reference#l_ArrayBufferView_reduce */ reduce: (callback: any, initialValue: any) => any; /** * Fill this array with the given value, for every index `>= start` and `< end` + * * @url http://www.espruino.com/Reference#l_ArrayBufferView_fill */ fill: (value: any, start: number, end: any) => EspruinoArrayBufferView; /** * Return an array which contains only those elements for which the callback function returns 'true' + * * @url http://www.espruino.com/Reference#l_ArrayBufferView_filter */ filter: (fn: any, thisArg: any) => any; /** * Return the array element where `function` returns `true`, or `undefined` if it doesn't returns `true` for any element. + * * @url http://www.espruino.com/Reference#l_ArrayBufferView_find */ find: (fn: any) => any; /** * Return the array element's index where `function` returns `true`, or `-1` if it doesn't returns `true` for any element. + * * @url http://www.espruino.com/Reference#l_ArrayBufferView_findIndex */ findIndex: (fn: any) => any; /** * Reverse the contents of this `ArrayBufferView` in-place + * * @url http://www.espruino.com/Reference#l_ArrayBufferView_reverse */ reverse: () => EspruinoArrayBufferView; /** * Return a copy of a portion of this array (in a new array). + * * **Note:** This currently returns a normal `Array`, not an `ArrayBuffer` + * * @url http://www.espruino.com/Reference#l_ArrayBufferView_slice */ slice: (start: number, end: any) => any[]; @@ -3809,6 +4585,7 @@ type EspruinoArrayBufferView = { /** * Create a typed array based on the given input. Either an existing Array Buffer, an Integer as a Length, or a simple array. If an `ArrayBufferView` (eg. `Uint8Array` rather than `ArrayBuffer`) is given, it will be completely copied rather than referenced. + * * @url http://www.espruino.com/Reference#l_Uint24Array_Uint24Array */ declare function Uint24Array(arr: any, byteOffset: number, length: number): EspruinoArrayBufferView; @@ -3818,13 +4595,17 @@ type Uint24Array = { /** * Create a software SPI port. This has limited functionality (no baud rate), but it can work on any pins. + * * Use `SPI.setup` to configure this port. + * * @url http://www.espruino.com/Reference#l_SPI_SPI */ declare const SPI: { /** * Try and find an SPI hardware device that will work on this pin (eg. `SPI1`) + * * May return undefined if no device can be found. + * * @url http://www.espruino.com/Reference#l_SPI_find */ find: (pin: Pin) => any; @@ -3834,50 +4615,67 @@ declare const SPI: { type SPI = { /** * Set up this SPI port as an SPI Master. + * * Options can contain the following (defaults are shown where relevant): - *
    `{
    +   *
    +   * ```
    +   * {
        *   sck:pin,
        *   miso:pin,
        *   mosi:pin,
    -   *   baud:integer=100000, // ignored on software SPI
    -   *   mode:integer=0, // between 0 and 3
    -   *   order:string='msb' // can be 'msb' or 'lsb'
    -   *   bits:8 // only available for software SPI
    +   *   baud:integer=100000, // ignored on software SPI
    +   *   mode:integer=0, // between 0 and 3
    +   *   order:string='msb' // can be 'msb' or 'lsb'
    +   *   bits:8 // only available for software SPI
        * }
    -   * `
    + * ``` + * * If `sck`,`miso` and `mosi` are left out, they will automatically be chosen. However if one or more is specified then the unspecified pins will not be set up. + * * You can find out which pins to use by looking at [your board's reference page](#boards) and searching for pins with the `SPI` marker. Some boards such as those based on `nRF52` chips can have SPI on any pins, so don't have specific markings. + * * The SPI `mode` is between 0 and 3 - see [http://en.wikipedia.org/wiki/Serial_Peripheral_Interface_Bus#Clock_polarity_and_phase](http://en.wikipedia.org/wiki/Serial_Peripheral_Interface_Bus#Clock_polarity_and_phase) + * * On STM32F1-based parts, you cannot mix AF and non-AF pins (SPI pins are usually grouped on the chip - and you can't mix pins from two groups). Espruino will not warn you about this. + * * @url http://www.espruino.com/Reference#l_SPI_setup */ setup: (options: any) => void; /** * Send data down SPI, and return the result. Sending an integer will return an integer, a String will return a String, and anything else will return a Uint8Array. + * * Sending multiple bytes in one call to send is preferable as they can then be transmitted end to end. Using multiple calls to send() will result in significantly slower transmission speeds. + * * For maximum speeds, please pass either Strings or Typed Arrays as arguments. Note that you can even pass arrays of arrays, like `[1,[2,3,4],5]` + * * @url http://www.espruino.com/Reference#l_SPI_send */ send: (data: any, nss_pin: Pin) => any; /** * Write a character or array of characters to SPI - without reading the result back. + * * For maximum speeds, please pass either Strings or Typed Arrays as arguments. + * * @url http://www.espruino.com/Reference#l_SPI_write */ write: (data: any) => void; /** * Send data down SPI, using 4 bits for each 'real' bit (MSB first). This can be useful for faking one-wire style protocols + * * Sending multiple bytes in one call to send is preferable as they can then be transmitted end to end. Using multiple calls to send() will result in significantly slower transmission speeds. + * * @url http://www.espruino.com/Reference#l_SPI_send4bit */ send4bit: (data: any, bit0: number, bit1: number, nss_pin: Pin) => void; /** * Send data down SPI, using 8 bits for each 'real' bit (MSB first). This can be useful for faking one-wire style protocols + * * Sending multiple bytes in one call to send is preferable as they can then be transmitted end to end. Using multiple calls to send() will result in significantly slower transmission speeds. + * * @url http://www.espruino.com/Reference#l_SPI_send8bit */ send8bit: (data: any, bit0: number, bit1: number, nss_pin: Pin) => void; @@ -3886,31 +4684,38 @@ type SPI = { /** * The first SPI port + * * @url http://www.espruino.com/Reference#l__global_SPI1 */ declare const SPI1: SPI; /** * The second SPI port + * * @url http://www.espruino.com/Reference#l__global_SPI2 */ declare const SPI2: SPI; /** * The third SPI port + * * @url http://www.espruino.com/Reference#l__global_SPI3 */ declare const SPI3: SPI; /** * Create a software I2C port. This has limited functionality (no baud rate), but it can work on any pins. + * * Use `I2C.setup` to configure this port. + * * @url http://www.espruino.com/Reference#l_I2C_I2C */ declare const I2C: { /** * Try and find an I2C hardware device that will work on this pin (eg. `I2C1`) + * * May return undefined if no device can be found. + * * @url http://www.espruino.com/Reference#l_I2C_find */ find: (pin: Pin) => any; @@ -3920,19 +4725,23 @@ declare const I2C: { type I2C = { /** * Set up this I2C port + * * If not specified in options, the default pins are used (usually the lowest numbered pins on the lowest port that supports this peripheral) + * * @url http://www.espruino.com/Reference#l_I2C_setup */ setup: (options: any) => void; /** * Transmit to the slave device with the given address. This is like Arduino's beginTransmission, write, and endTransmission rolled up into one. + * * @url http://www.espruino.com/Reference#l_I2C_writeTo */ writeTo: (address: any, data: any) => void; /** * Request bytes from the given slave device, and return them as a Uint8Array (packed array of bytes). This is like using Arduino Wire's requestFrom, available and read functions. Sends a STOP + * * @url http://www.espruino.com/Reference#l_I2C_readFrom */ readFrom: (address: any, quantity: number) => Uint8Array; @@ -3941,25 +4750,30 @@ type I2C = { /** * The first I2C port + * * @url http://www.espruino.com/Reference#l__global_I2C1 */ declare const I2C1: I2C; /** * The second I2C port + * * @url http://www.espruino.com/Reference#l__global_I2C2 */ declare const I2C2: I2C; /** * The third I2C port + * * @url http://www.espruino.com/Reference#l__global_I2C3 */ declare const I2C3: I2C; /** * Create a waveform class. This allows high speed input and output of waveforms. It has an internal variable called `buffer` (as well as `buffer2` when double-buffered - see `options` below) which contains the data to input/output. + * * When double-buffered, a 'buffer' event will be emitted each time a buffer is finished with (the argument is that buffer). When the recording stops, a 'finish' event will be emitted (with the first argument as the buffer). + * * @url http://www.espruino.com/Reference#l_Waveform_Waveform */ declare function Waveform(samples: number, options: any): any; @@ -3967,18 +4781,21 @@ declare function Waveform(samples: number, options: any): any; type Waveform = { /** * Will start outputting the waveform on the given pin - the pin must have previously been initialised with analogWrite. If not repeating, it'll emit a `finish` event when it is done. + * * @url http://www.espruino.com/Reference#l_Waveform_startOutput */ startOutput: (output: Pin, freq: number, options: any) => void; /** * Will start inputting the waveform on the given pin that supports analog. If not repeating, it'll emit a `finish` event when it is done. + * * @url http://www.espruino.com/Reference#l_Waveform_startInput */ startInput: (output: Pin, freq: number, options: any) => void; /** * Stop a waveform that is currently outputting + * * @url http://www.espruino.com/Reference#l_Waveform_stop */ stop: () => void; @@ -3987,6 +4804,7 @@ type Waveform = { /** * Creates a pin from the given argument (or returns undefined if no argument) + * * @url http://www.espruino.com/Reference#l_Pin_Pin */ declare function Pin(value: any): any; @@ -3994,74 +4812,93 @@ declare function Pin(value: any): any; type Pin = { /** * Returns the input state of the pin as a boolean. + * * **Note:** if you didn't call `pinMode` beforehand then this function will also reset the pin's state to `"input"` + * * @url http://www.espruino.com/Reference#l_Pin_read */ read: () => boolean; /** * Sets the output state of the pin to a 1 + * * **Note:** if you didn't call `pinMode` beforehand then this function will also reset the pin's state to `"output"` + * * @url http://www.espruino.com/Reference#l_Pin_set */ set: () => void; /** * Sets the output state of the pin to a 0 + * * **Note:** if you didn't call `pinMode` beforehand then this function will also reset the pin's state to `"output"` + * * @url http://www.espruino.com/Reference#l_Pin_reset */ reset: () => void; /** * Sets the output state of the pin to the parameter given + * * **Note:** if you didn't call `pinMode` beforehand then this function will also reset the pin's state to `"output"` + * * @url http://www.espruino.com/Reference#l_Pin_write */ write: (value: boolean) => void; /** * Sets the output state of the pin to the parameter given at the specified time. + * * **Note:** this **doesn't** change the mode of the pin to an output. To do that, you need to use `pin.write(0)` or `pinMode(pin, 'output')` first. + * * @url http://www.espruino.com/Reference#l_Pin_writeAtTime */ writeAtTime: (value: boolean, time: number) => void; /** * Return the current mode of the given pin. See `pinMode` for more information. + * * @url http://www.espruino.com/Reference#l_Pin_getMode */ getMode: () => any; /** * Set the mode of the given pin. See [`pinMode`](#l__global_pinMode) for more information on pin modes. + * * @url http://www.espruino.com/Reference#l_Pin_mode */ mode: (mode: any) => void; /** * Toggles the state of the pin from off to on, or from on to off. + * * **Note:** This method doesn't currently work on the ESP8266 port of Espruino. + * * **Note:** if you didn't call `pinMode` beforehand then this function will also reset the pin's state to `"output"` + * * @url http://www.espruino.com/Reference#l_Pin_toggle */ toggle: () => boolean; /** * Get information about this pin and its capabilities. Of the form: - *
    `{
    -   *   "port"      : "A", // the Pin's port on the chip
    -   *   "num"       : 12, // the Pin's number
    -   *   "in_addr"   : 0x..., // (if available) the address of the pin's input address in bit-banded memory (can be used with peek)
    -   *   "out_addr"  : 0x..., // (if available) the address of the pin's output address in bit-banded memory (can be used with poke)
    -   *   "analog"    : { ADCs : [1], channel : 12 }, // If analog input is available
    -   *   "functions" : {
    -   *     "TIM1":{type:"CH1, af:0},
    -   *     "I2C3":{type:"SCL", af:1}
    +   *
    +   * ```
    +   * {
    +   *   "port"      : "A", // the Pin's port on the chip
    +   *   "num"       : 12, // the Pin's number
    +   *   "in_addr"   : 0x..., // (if available) the address of the pin's input address in bit-banded memory (can be used with peek)
    +   *   "out_addr"  : 0x..., // (if available) the address of the pin's output address in bit-banded memory (can be used with poke)
    +   *   "analog"    : { ADCs : [1], channel : 12 }, // If analog input is available
    +   *   "functions" : {
    +   *     "TIM1":{type:"CH1, af:0},
    +   *     "I2C3":{type:"SCL", af:1}
        *   }
        * }
    -   * `
    + * ``` + * * Will return undefined if pin is not valid. + * * @url http://www.espruino.com/Reference#l_Pin_getInfo */ getInfo: () => any; @@ -4070,13 +4907,17 @@ type Pin = { /** * Create a software Serial port. This has limited functionality (only low baud rates), but it can work on any pins. + * * Use `Serial.setup` to configure this port. + * * @url http://www.espruino.com/Reference#l_Serial_Serial */ declare const Serial: { /** * Try and find a USART (Serial) hardware device that will work on this pin (eg. `Serial1`) + * * May return undefined if no device can be found. + * * @url http://www.espruino.com/Reference#l_Serial_find */ find: (pin: Pin) => any; @@ -4086,58 +4927,78 @@ declare const Serial: { type Serial = { /** * Set this Serial port as the port for the JavaScript console (REPL). + * * Unless `force` is set to true, changes in the connection state of the board * (for instance plugging in USB) will cause the console to change. + * * See `E.setConsole` for a more flexible version of this function. + * * @url http://www.espruino.com/Reference#l_Serial_setConsole */ setConsole: (force: boolean) => void; /** * Setup this Serial port with the given baud rate and options. + * * eg. - *
    `Serial1.setup(9600,{rx:a_pin, tx:a_pin});
    -   * `
    + * + * ``` + * Serial1.setup(9600,{rx:a_pin, tx:a_pin}); + * ``` + * * The second argument can contain: - *
    `{
    -   *   rx:pin,                           // Receive pin (data in to Espruino)
    -   *   tx:pin,                           // Transmit pin (data out of Espruino)
    -   *   ck:pin,                           // (default none) Clock Pin
    -   *   cts:pin,                          // (default none) Clear to Send Pin
    -   *   bytesize:8,                       // (default 8)How many data bits - 7 or 8
    -   *   parity:null/'none'/'o'/'odd'/'e'/'even',
    -   *                                     // (default none) Parity bit
    -   *   stopbits:1,                       // (default 1) Number of stop bits to use
    -   *   flow:null/undefined/'none'/'xon', // (default none) software flow control
    -   *   path:null/undefined/string        // Linux Only - the path to the Serial device to use
    -   *   errors:false                      // (default false) whether to forward framing/parity errors
    +   *
    +   * ```
    +   * {
    +   *   rx:pin,                           // Receive pin (data in to Espruino)
    +   *   tx:pin,                           // Transmit pin (data out of Espruino)
    +   *   ck:pin,                           // (default none) Clock Pin
    +   *   cts:pin,                          // (default none) Clear to Send Pin
    +   *   bytesize:8,                       // (default 8)How many data bits - 7 or 8
    +   *   parity:null/'none'/'o'/'odd'/'e'/'even',
    +   *                                     // (default none) Parity bit
    +   *   stopbits:1,                       // (default 1) Number of stop bits to use
    +   *   flow:null/undefined/'none'/'xon', // (default none) software flow control
    +   *   path:null/undefined/string        // Linux Only - the path to the Serial device to use
    +   *   errors:false                      // (default false) whether to forward framing/parity errors
        * }
    -   * `
    + * ``` + * * You can find out which pins to use by looking at [your board's reference page](#boards) * and searching for pins with the `UART`/`USART` markers. + * * If not specified in options, the default pins are used for rx and tx * (usually the lowest numbered pins on the lowest port that supports * this peripheral). `ck` and `cts` are not used unless specified. + * * Note that even after changing the RX and TX pins, if you have called setup * before then the previous RX and TX pins will still be connected to the Serial * port as well - until you set them to something else using `digitalWrite` or * `pinMode`. + * * Flow control can be xOn/xOff (`flow:'xon'`) or hardware flow control * (receive only) if `cts` is specified. If `cts` is set to a pin, the * pin's value will be 0 when Espruino is ready for data and 1 when it isn't. + * * By default, framing or parity errors don't create `framing` or `parity` events * on the `Serial` object because storing these errors uses up additional * storage in the queue. If you're intending to receive a lot of malformed * data then the queue might overflow `E.getErrorFlags()` would return `FIFO_FULL`. * However if you need to respond to `framing` or `parity` errors then * you'll need to use `errors:true` when initialising serial. + * * On Linux builds there is no default Serial device, so you must specify * a path to a device - for instance: `Serial1.setup(9600,{path:"/dev/ttyACM0"})` + * * You can also set up 'software serial' using code like: - *
    `var s = new Serial();
    -   * s.setup(9600,{rx:a_pin, tx:a_pin});
    -   * `
    + * + * ``` + * var s = new Serial(); + * s.setup(9600,{rx:a_pin, tx:a_pin}); + * ``` + * * However software serial doesn't use `ck`, `cts`, `parity`, `flow` or `errors` parts of the initialisation object. + * * @url http://www.espruino.com/Reference#l_Serial_setup */ setup: (baudrate: any, options: any) => void; @@ -4145,27 +5006,34 @@ type Serial = { /** * If the serial (or software serial) device was set up, * uninitialise it. + * * @url http://www.espruino.com/Reference#l_Serial_unsetup */ unsetup: () => void; /** * Print a string to the serial port - without a line feed + * * **Note:** This function replaces any occurances of `\n` in the string with `\r\n`. To avoid this, use `Serial.write`. + * * @url http://www.espruino.com/Reference#l_Serial_print */ print: (string: any) => void; /** * Print a line to the serial port with a newline (`\r\n`) at the end of it. + * * **Note:** This function converts data to a string first, eg `Serial.print([1,2,3])` is equivalent to `Serial.print("1,2,3"). If you'd like to write raw bytes, use `Serial.write`. + * * @url http://www.espruino.com/Reference#l_Serial_println */ println: (string: any) => void; /** * Write a character or array of data to the serial port + * * This method writes unmodified data, eg `Serial.write([1,2,3])` is equivalent to `Serial.write("\1\2\3")`. If you'd like data converted to a string first, use `Serial.print`. + * * @url http://www.espruino.com/Reference#l_Serial_write */ write: (data: any) => void; @@ -4173,30 +5041,37 @@ type Serial = { /** * Add data to this device as if it came directly from the input - it will be * returned via `serial.on('data', ...)`; - *
    `Serial1.on('data', function(d) { print("Got",d); });
    -   * Serial1.inject('Hello World');
    -   * // prints "Got Hel","Got lo World" (characters can be split over multiple callbacks)
    -   * `
    + * + * ``` + * Serial1.on('data', function(d) { print("Got",d); }); + * Serial1.inject('Hello World'); + * // prints "Got Hel","Got lo World" (characters can be split over multiple callbacks) + * ``` + * * This is most useful if you wish to send characters to Espruino's * REPL (console) while it is on another device. + * * @url http://www.espruino.com/Reference#l_Serial_inject */ inject: (data: any) => void; /** * Return how many bytes are available to read. If there is already a listener for data, this will always return 0. + * * @url http://www.espruino.com/Reference#l_Serial_available */ available: () => number; /** * Return a string containing characters that have been received + * * @url http://www.espruino.com/Reference#l_Serial_read */ read: (chars: number) => any; /** * Pipe this USART to a stream (an object with a 'write' method) + * * @url http://www.espruino.com/Reference#l_Serial_pipe */ pipe: (destination: any, options: any) => void; @@ -4205,60 +5080,70 @@ type Serial = { /** * The USB Serial port + * * @url http://www.espruino.com/Reference#l__global_USB */ declare const USB: Serial; /** * The first Serial (USART) port + * * @url http://www.espruino.com/Reference#l__global_Serial1 */ declare const Serial1: Serial; /** * The second Serial (USART) port + * * @url http://www.espruino.com/Reference#l__global_Serial2 */ declare const Serial2: Serial; /** * The third Serial (USART) port + * * @url http://www.espruino.com/Reference#l__global_Serial3 */ declare const Serial3: Serial; /** * The fourth Serial (USART) port + * * @url http://www.espruino.com/Reference#l__global_Serial4 */ declare const Serial4: Serial; /** * The fifth Serial (USART) port + * * @url http://www.espruino.com/Reference#l__global_Serial5 */ declare const Serial5: Serial; /** * The sixth Serial (USART) port + * * @url http://www.espruino.com/Reference#l__global_Serial6 */ declare const Serial6: Serial; /** * A loopback serial device. Data sent to `LoopbackA` comes out of `LoopbackB` and vice versa + * * @url http://www.espruino.com/Reference#l__global_LoopbackA */ declare const LoopbackA: Serial; /** * A loopback serial device. Data sent to `LoopbackA` comes out of `LoopbackB` and vice versa + * * @url http://www.espruino.com/Reference#l__global_LoopbackB */ declare const LoopbackB: Serial; /** * A telnet serial device that maps to the built-in telnet console server (devices that have built-in wifi only). + * * @url http://www.espruino.com/Reference#l__global_Telnet */ declare const Telnet: any; @@ -4266,8 +5151,10 @@ declare const Telnet: any; /** * This module allows you to read and write part of the nonvolatile flash * memory of your device using a filesystem-like API. + * * Also see the `Flash` library, which provides a low level, more dangerous way * to access all parts of your flash memory. + * * The `Storage` library provides two distinct types of file: * * - `require("Storage").write(...)`/`require("Storage").read(...)`/etc create simple @@ -4278,51 +5165,60 @@ declare const Telnet: any; * * You must read a file using the same method you used to write it - eg. you can't create a * file with `require("Storage").open(...)` and then read it with `require("Storage").read(...)`. + * * **Note:** In firmware 2v05 and later, the maximum length for filenames * is 28 characters. However in 2v04 and earlier the max length is 8. + * * @url http://www.espruino.com/Reference#l_Storage_undefined */ /** * These objects are created from `require("Storage").open` * and allow Storage items to be read/written. + * * The `Storage` library writes into Flash memory (which * can only be erased in chunks), and unlike a normal filesystem * it allocates files in one long contiguous area to allow them * to be accessed easily from Espruino. + * * This presents a challenge for `StorageFile` which allows you * to append to a file, so instead `StorageFile` stores files * in chunks. It uses the last character of the filename * to denote the chunk number (eg `"foobar\1"`, `"foobar\2"`, etc). + * * This means that while `StorageFile` files exist in the same * area as those from `Storage`, they should be * read using `Storage.open` (and not `Storage.read`). - *
    `f = s.open("foobar","w");
    - * f.write("Hell");
    - * f.write("o World\n");
    - * f.write("Hello\n");
    - * f.write("World 2\n");
    - * // there's no need to call 'close'
    - * // then
    - * f = s.open("foobar","r");
    - * f.read(13) // "Hello World\nH"
    - * f.read(13) // "ello\nWorld 2\n"
    - * f.read(13) // "Hello World 3"
    - * f.read(13) // "\n"
    - * f.read(13) // undefined
    - * // or
    - * f = s.open("foobar","r");
    - * f.readLine() // "Hello World\n"
    - * f.readLine() // "Hello\n"
    - * f.readLine() // "World 2\n"
    - * f.readLine() // "Hello World 3\n"
    - * f.readLine() // undefined
    - * // now get rid of file
    - * f.erase();
    - * `
    + * + * ``` + * f = s.open("foobar","w"); + * f.write("Hell"); + * f.write("o World\n"); + * f.write("Hello\n"); + * f.write("World 2\n"); + * // there's no need to call 'close' + * // then + * f = s.open("foobar","r"); + * f.read(13) // "Hello World\nH" + * f.read(13) // "ello\nWorld 2\n" + * f.read(13) // "Hello World 3" + * f.read(13) // "\n" + * f.read(13) // undefined + * // or + * f = s.open("foobar","r"); + * f.readLine() // "Hello World\n" + * f.readLine() // "Hello\n" + * f.readLine() // "World 2\n" + * f.readLine() // "Hello World 3\n" + * f.readLine() // undefined + * // now get rid of file + * f.erase(); + * ``` + * * **Note:** `StorageFile` uses the fact that all bits of erased flash memory * are 1 to detect the end of a file. As such you should not write character * code 255 (`"\xFF"`) to these files. + * * @url http://www.espruino.com/Reference#StorageFile */ declare function StorageFile(): void; @@ -4330,34 +5226,41 @@ declare function StorageFile(): void; type StorageFile = { /** * Read 'len' bytes of data from the file, and return a String containing those bytes. + * * If the end of the file is reached, the String may be smaller than the amount of bytes * requested, or if the file is already at the end, `undefined` is returned. + * * @url http://www.espruino.com/Reference#l_StorageFile_read */ read: (len: number) => string; /** * Read a line of data from the file (up to and including `"\n"`) + * * @url http://www.espruino.com/Reference#l_StorageFile_readLine */ readLine: () => string; /** * Return the length of the current file. + * * This requires Espruino to read the file from scratch, * which is not a fast operation. + * * @url http://www.espruino.com/Reference#l_StorageFile_getLength */ getLength: () => number; /** * Append the given data to a file. You should not attempt to append `"\xFF"` (character code 255). + * * @url http://www.espruino.com/Reference#l_StorageFile_write */ write: (data: any) => void; /** * Erase this file + * * @url http://www.espruino.com/Reference#l_StorageFile_erase */ erase: () => void; @@ -4366,29 +5269,34 @@ type StorageFile = { /** * Built-in class that caches the modules used by the `require` command + * * @url http://www.espruino.com/Reference#Modules */ declare const Modules: { /** * Return an array of module names that have been cached + * * @url http://www.espruino.com/Reference#l_Modules_getCached */ getCached: () => any; /** * Remove the given module from the list of cached modules + * * @url http://www.espruino.com/Reference#l_Modules_removeCached */ removeCached: (id: any) => void; /** * Remove all cached modules + * * @url http://www.espruino.com/Reference#l_Modules_removeAllCached */ removeAllCached: () => void; /** * Add the given module to the cache + * * @url http://www.espruino.com/Reference#l_Modules_addCached */ addCached: (id: any, sourcecode: any) => void; @@ -4397,54 +5305,69 @@ declare const Modules: { /** * This module allows you to read and write the nonvolatile flash memory of your device. + * * Also see the `Storage` library, which provides a safer file-like * interface to nonvolatile storage. + * * It should be used with extreme caution, as it is easy to overwrite parts of Flash * memory belonging to Espruino or even its bootloader. If you damage the bootloader * then you may need external hardware such as a USB-TTL converter to restore it. For * more information on restoring the bootloader see `Advanced Reflashing` in your * board's reference pages. + * * To see which areas of memory you can and can't overwrite, look at the values * reported by `process.memory()`. + * * **Note:** On Nordic platforms there are checks in place to help you avoid * 'bricking' your device be damaging the bootloader. You can disable these with `E.setFlags({unsafeFlash:1})` + * * @url http://www.espruino.com/Reference#l_Flash_undefined */ /** * This is the built-in JavaScript class for Espruino utility functions. + * * @url http://www.espruino.com/Reference#E */ declare const E: { /** * Setup the filesystem so that subsequent calls to `E.openFile` and `require('fs').*` will use an SD card on the supplied SPI device and pin. + * * It can even work using software SPI - for instance: - *
    `// DI/CMD = C7
    -   * // DO/DAT0 = C8
    -   * // CK/CLK = C9
    -   * // CD/CS/DAT3 = C6
    +   *
    +   * ```
    +   * // DI/CMD = C7
    +   * // DO/DAT0 = C8
    +   * // CK/CLK = C9
    +   * // CD/CS/DAT3 = C6
        * var spi = new SPI();
        * spi.setup({mosi:C7, miso:C8, sck:C9});
        * E.connectSDCard(spi, C6);
    -   * console.log(require("fs").readdirSync());
    -   * `
    + * console.log(require("fs").readdirSync()); + * ``` + * * See [the page on File IO](http://www.espruino.com/File+IO) for more information. + * * **Note:** We'd strongly suggest you add a pullup resistor from CD/CS pin to 3.3v. It is * good practise to avoid accidental writes before Espruino is initialised, and some cards * will not work reliably without one. + * * **Note:** If you want to remove an SD card after you have started using it, you *must* call `E.unmountSD()` or you may cause damage to the card. + * * @url http://www.espruino.com/Reference#l_E_connectSDCard */ connectSDCard: (spi: any, csPin: Pin) => void; /** * Unmount the SD card, so it can be removed. If you remove the SD card without calling this you may cause corruption, and you will be unable to access another SD card until you reset Espruino or call `E.unmountSD()`. + * * @url http://www.espruino.com/Reference#l_E_unmountSD */ unmountSD: () => void; /** * Open a file + * * @url http://www.espruino.com/Reference#l_E_openFile */ openFile: (path: any, mode: any) => EspruinoFile; @@ -4452,20 +5375,26 @@ declare const E: { /** * Change the paramters used for the flash filesystem. * The default address is the last 1Mb of 4Mb Flash, 0x300000, with total size of 1Mb. + * * Before first use the media needs to be formatted. - *
    `fs=require("fs");
    -   * try {
    -   *   fs.readdirSync();
    -   *  } catch (e) { //'Uncaught Error: Unable to mount media : NO_FILESYSTEM'
    -   *   console.log('Formatting FS - only need to do once');
    -   *   E.flashFatFS({ format: true });
    +   *
    +   * ```
    +   * fs=require("fs");
    +   * try {
    +   *   fs.readdirSync();
    +   *  } catch (e) { //'Uncaught Error: Unable to mount media : NO_FILESYSTEM'
    +   *   console.log('Formatting FS - only need to do once');
    +   *   E.flashFatFS({ format: true });
        * }
    -   * fs.writeFileSync("bang.txt", "This is the way the world ends\nnot with a bang but a whimper.\n");
    -   * fs.readdirSync();
    -   * `
    + * fs.writeFileSync("bang.txt", "This is the way the world ends\nnot with a bang but a whimper.\n"); + * fs.readdirSync(); + * ``` + * * This will create a drive of 100 * 4096 bytes at 0x300000. Be careful with the selection of flash addresses as you can overwrite firmware! * You only need to format once, as each will erase the content. + * * `E.flashFatFS({ addr:0x300000,sectors:100,format:true });` + * * @url http://www.espruino.com/Reference#l_E_flashFatFS */ flashFatFS: (options: any) => boolean; @@ -4477,15 +5406,22 @@ declare const E: { /** * A utility function for displaying a full screen message on the screen. + * * Draws to the screen and returns immediately. - *
    `E.showMessage("These are\nLots of\nLines","My Title")
    -   * `
    + * + * ``` + * E.showMessage("These are\nLots of\nLines","My Title") + * ``` + * * or to display an image as well as text: - *
    `E.showMessage("Lots of text will wrap automatically",{
    -   *   title:"Warning",
    -   *   img:atob("FBQBAfgAf+Af/4P//D+fx/n+f5/v+f//n//5//+f//n////3//5/n+P//D//wf/4B/4AH4A=")
    +   *
    +   * ```
    +   * E.showMessage("Lots of text will wrap automatically",{
    +   *   title:"Warning",
    +   *   img:atob("FBQBAfgAf+Af/4P//D+fx/n+f5/v+f//n//5//+f//n////3//5/n+P//D//wf/4B/4AH4A=")
        * })
    -   * `
    + * ``` + * * @url http://www.espruino.com/Reference#l_E_showMessage */ showMessage: (message: any, options: any) => void; @@ -4497,16 +5433,21 @@ declare const E: { /** * Displays a full screen prompt on the screen, with a single 'Ok' button. + * * When the button is pressed the promise is resolved. - *
    `E.showAlert("Hello").then(function() {
    -   *   print("Ok pressed");
    +   *
    +   * ```
    +   * E.showAlert("Hello").then(function() {
    +   *   print("Ok pressed");
        * });
    -   * // or
    -   * E.showAlert("These are\nLots of\nLines","My Title").then(function() {
    -   *   print("Ok pressed");
    +   * // or
    +   * E.showAlert("These are\nLots of\nLines","My Title").then(function() {
    +   *   print("Ok pressed");
        * });
    -   * `
    + * ``` + * * To remove the window, call `E.showAlert()` with no arguments. + * * @url http://www.espruino.com/Reference#l_E_showAlert */ showAlert: (message: any, options: any) => any; @@ -4518,53 +5459,69 @@ declare const E: { /** * Use the microcontroller's internal thermistor to work out the temperature. + * * On Puck.js v2.0 this will use the on-board PCT2075TP temperature sensor, but on other devices it may not be desperately well calibrated. + * * While this is implemented on Espruino boards, it may not be implemented on other devices. If so it'll return NaN. + * * **Note:** This is not entirely accurate and varies by a few degrees from chip to chip. It measures the **die temperature**, so when connected to USB it could be reading 10 over degrees C above ambient temperature. When running from battery with `setDeepSleep(true)` it is much more accurate though. + * * @url http://www.espruino.com/Reference#l_E_getTemperature */ getTemperature: () => number; /** * Check the internal voltage reference. To work out an actual voltage of an input pin, you can use `analogRead(pin)*E.getAnalogVRef()` + * * **Note:** This value is calculated by reading the voltage on an internal voltage reference with the ADC. * It will be slightly noisy, so if you need this for accurate measurements we'd recommend that you call * this function several times and average the results. + * * While this is implemented on Espruino boards, it may not be implemented on other devices. If so it'll return NaN. + * * @url http://www.espruino.com/Reference#l_E_getAnalogVRef */ getAnalogVRef: () => number; /** * ADVANCED: This is a great way to crash Espruino if you're not sure what you are doing + * * Create a native function that executes the code at the given address. Eg. `E.nativeCall(0x08012345,'double (double,double)')(1.1, 2.2)` + * * If you're executing a thumb function, you'll almost certainly need to set the bottom bit of the address to 1. + * * Note it's not guaranteed that the call signature you provide can be used - there are limits on the number of arguments allowed. + * * When supplying `data`, if it is a 'flat string' then it will be used directly, otherwise it'll be converted to a flat string and used. + * * @url http://www.espruino.com/Reference#l_E_nativeCall */ nativeCall: (addr: number, sig: any, data: any) => any; /** * Clip a number to be between min and max (inclusive) + * * @url http://www.espruino.com/Reference#l_E_clip */ clip: (x: number, min: number, max: number) => number; /** * Sum the contents of the given Array, String or ArrayBuffer and return the result + * * @url http://www.espruino.com/Reference#l_E_sum */ sum: (arr: any) => number; /** * Work out the variance of the contents of the given Array, String or ArrayBuffer and return the result. This is equivalent to `v=0;for (i in arr) v+=Math.pow(mean-arr[i],2)` + * * @url http://www.espruino.com/Reference#l_E_variance */ variance: (arr: any, mean: number) => number; /** * Convolve arr1 with arr2. This is equivalent to `v=0;for (i in arr1) v+=arr1[i] * arr2[(i+offset) % arr2.length]` + * * @url http://www.espruino.com/Reference#l_E_convolve */ convolve: (arr1: any, arr2: any, offset: number) => number; @@ -4573,33 +5530,44 @@ declare const E: { * Performs a Fast Fourier Transform (FFT) in 32 bit floats on the supplied data and writes it back into the * original arrays. Note that if only one array is supplied, the data written back is the modulus of the complex * result `sqrt(r*r+i*i)`. + * * In order to perform the FFT, there has to be enough room on the stack to allocate two arrays of 32 bit * floating point numbers - this will limit the maximum size of FFT possible to around 1024 items on * most platforms. + * * **Note:** on the Original Espruino board, FFTs are performed in 64bit arithmetic as there isn't * space to include the 32 bit maths routines (2x more RAM is required). + * * @url http://www.espruino.com/Reference#l_E_FFT */ FFT: (arrReal: any, arrImage: any, inverse: boolean) => void; /** * Enable the watchdog timer. This will reset Espruino if it isn't able to return to the idle loop within the timeout. + * * If `isAuto` is false, you must call `E.kickWatchdog()` yourself every so often or the chip will reset. - *
    `E.enableWatchdog(0.5); // automatic mode                                                        
    -   * while(1); // Espruino will reboot because it has not been idle for 0.5 sec
    -   * `
    - *
    `E.enableWatchdog(1, false);
    -   * setInterval(function() {
    -   *   if (everything_ok)
    -   *     E.kickWatchdog();
    -   * }, 500);
    -   * // Espruino will now reset if everything_ok is false,
    -   * // or if the interval fails to be called 
    -   * `
    + * + * ``` + * E.enableWatchdog(0.5); // automatic mode + * while(1); // Espruino will reboot because it has not been idle for 0.5 sec + * ``` + * + * ``` + * E.enableWatchdog(1, false); + * setInterval(function() { + * if (everything_ok) + * E.kickWatchdog(); + * }, 500); + * // Espruino will now reset if everything_ok is false, + * // or if the interval fails to be called + * ``` + * * **NOTE:** This is only implemented on STM32 and nRF5x devices (all official Espruino boards). + * * **NOTE:** On STM32 (Pico, WiFi, Original) with `setDeepSleep(1)` you need to * explicitly wake Espruino up with an interval of less than the watchdog timeout or the watchdog will fire and * the board will reboot. You can do this with `setInterval("", time_in_milliseconds)`. + * * @url http://www.espruino.com/Reference#l_E_enableWatchdog */ enableWatchdog: (timeout: number, isAuto: any) => void; @@ -4607,19 +5575,28 @@ declare const E: { /** * Kicks a Watchdog timer set up with `E.enableWatchdog(..., false)`. See * `E.enableWatchdog` for more information. + * * **NOTE:** This is only implemented on STM32 and nRF5x devices (all official Espruino boards). + * * @url http://www.espruino.com/Reference#l_E_kickWatchdog */ kickWatchdog: () => void; /** * Get and reset the error flags. Returns an array that can contain: + * * `'FIFO_FULL'`: The receive FIFO filled up and data was lost. This could be state transitions for setWatch, or received characters. + * * `'BUFFER_FULL'`: A buffer for a stream filled up and characters were lost. This can happen to any stream - Serial,HTTP,etc. + * * `'CALLBACK'`: A callback (`setWatch`, `setInterval`, `on('data',...)`) caused an error and so was removed. + * * `'LOW_MEMORY'`: Memory is running low - Espruino had to run a garbage collection pass or remove some of the command history + * * `'MEMORY'`: Espruino ran out of memory and was unable to allocate some data that it needed. + * * `'UART_OVERFLOW'` : A UART received data but it was not read in time and was lost + * * @url http://www.espruino.com/Reference#l_E_getErrorFlags */ getErrorFlags: () => any; @@ -4638,7 +5615,9 @@ declare const E: { /** * Set the Espruino interpreter flags that control the way it handles your JavaScript code. + * * Run `E.getFlags()` and check its description for a list of available flags and their values. + * * @url http://www.espruino.com/Reference#l_E_setFlags */ setFlags: (flags: any) => void; @@ -4650,7 +5629,9 @@ declare const E: { /** * Create an ArrayBuffer from the given string. This is done via a reference, not a copy - so it is very fast and memory efficient. + * * Note that this is an ArrayBuffer, not a Uint8Array. To get one of those, do: `new Uint8Array(E.toArrayBuffer('....'))`. + * * @url http://www.espruino.com/Reference#l_E_toArrayBuffer */ toArrayBuffer: (str: any) => EspruinoArrayBufferView; @@ -4663,21 +5644,23 @@ declare const E: { * - `Array` -> Call itself on each element * - `ArrayBuffer` or Typed Array -> use the lowest 8 bits of each element * - `Object`: + * * - `{data:..., count: int}` -> call itself `object.count` times, on `object.data` * - `{callback : function}` -> call the given function, call itself on return value * - * - * * For example: - *
    `E.toUint8Array([1,2,3])
    -   * =new Uint8Array([1, 2, 3])
    -   * E.toUint8Array([1,{data:2,count:3},3])
    -   * =new Uint8Array([1, 2, 2, 2, 3])
    -   * E.toUint8Array("Hello")
    -   * =new Uint8Array([72, 101, 108, 108, 111])
    -   * E.toUint8Array(["hi",{callback:function() { return [1,2,3] }}])
    -   * =new Uint8Array([104, 105, 1, 2, 3])
    -   * `
    + * + * ``` + * E.toUint8Array([1,2,3]) + * =new Uint8Array([1, 2, 3]) + * E.toUint8Array([1,{data:2,count:3},3]) + * =new Uint8Array([1, 2, 2, 2, 3]) + * E.toUint8Array("Hello") + * =new Uint8Array([72, 101, 108, 108, 111]) + * E.toUint8Array(["hi",{callback:function() { return [1,2,3] }}]) + * =new Uint8Array([104, 105, 1, 2, 3]) + * ``` + * * @url http://www.espruino.com/Reference#l_E_toUint8Array */ toUint8Array: (args: any) => Uint8Array; @@ -4686,8 +5669,10 @@ declare const E: { * This performs the same basic function as `JSON.stringify`, * however `JSON.stringify` adds extra characters to conform * to the JSON spec which aren't required if outputting JS. + * * `E.toJS` will also stringify JS functions, whereas * `JSON.stringify` ignores them. + * * For example: * * - `JSON.stringify({a:1,b:2}) == '{"a":1,"b":2}'` @@ -4697,8 +5682,10 @@ declare const E: { * reliably parsed by `JSON.parse` - however they are * valid JS so will work with `eval` (but this has security * implications if you don't trust the source of the string). + * * On the desktop [JSON5 parsers](https://github.com/json5/json5) * will parse the strings produced by `E.toJS` without trouble. + * * @url http://www.espruino.com/Reference#l_E_toJS */ toJS: (arg: any) => string; @@ -4708,8 +5695,10 @@ declare const E: { * a specific memory address. It can be used in order to use sections of * Flash memory directly in Espruino (for example to execute code straight * from flash memory with `eval(E.memoryArea( ... ))`) + * * **Note:** This is only tested on STM32-based platforms (Espruino Original * and Espruino Pico) at the moment. + * * @url http://www.espruino.com/Reference#l_E_memoryArea */ memoryArea: (addr: number, len: number) => string; @@ -4718,13 +5707,18 @@ declare const E: { * This writes JavaScript code into Espruino's flash memory, to be executed on * startup. It differs from `save()` in that `save()` saves the whole state of * the interpreter, whereas this just saves JS code that is executed at boot. + * * Code will be executed before `onInit()` and `E.on('init', ...)`. + * * If `alwaysExec` is `true`, the code will be executed even after a call to * `reset()`. This is useful if you're making something that you want to * program, but you want some code that is always built in (for instance * setting up a display or keyboard). + * * To remove boot code that has been saved previously, use `E.setBootCode("")` + * * **Note:** this removes any code that was previously saved with `save()` + * * @url http://www.espruino.com/Reference#l_E_setBootCode */ setBootCode: (code: any, alwaysExec: boolean) => void; @@ -4732,9 +5726,12 @@ declare const E: { /** * This sets the clock frequency of Espruino's processor. It will return `0` if * it is unimplemented or the clock speed cannot be changed. + * * **Note:** On pretty much all boards, UART, SPI, I2C, PWM, etc will change * frequency and will need setting up again in order to work. - *

    STM32F4

    + * + * # STM32F4 + * * Options is of the form `{ M: int, N: int, P: int, Q: int }` - see the 'Clocks' * section of the microcontroller's reference manual for what these mean. * @@ -4751,11 +5748,15 @@ declare const E: { * `{M:8, N:336, P:8, Q:7, PCLK:1, PCLK2:2}` to halve the system clock speed * while keeping the peripherals running at the same speed (omitting PCLK1/2 * will lead to the peripherals changing speed too). + * * On STM32F4 boards (eg. Espruino Pico), the USB clock needs to be kept at 48Mhz * or USB will fail to work. You'll also experience USB instability if the processor * clock falls much below 48Mhz. - *

    ESP8266

    + * + * # ESP8266 + * * Just specify an integer value, either 80 or 160 (for 80 or 160Mhz) + * * @url http://www.espruino.com/Reference#l_E_setClock */ setClock: (options: any) => number; @@ -4764,52 +5765,66 @@ declare const E: { * Changes the device that the JS console (otherwise known as the REPL) * is attached to. If the console is on a device, that * device can be used for programming Espruino. + * * Rather than calling `Serial.setConsole` you can call * `E.setConsole("DeviceName")`. + * * This is particularly useful if you just want to * remove the console. `E.setConsole(null)` will * make the console completely inaccessible. + * * `device` may be `"Serial1"`,`"USB"`,`"Bluetooth"`,`"Telnet"`,`"Terminal"`, * any other *hardware* `Serial` device, or `null` to disable the console completely. + * * `options` is of the form: - *
    `{
    -   *   force : bool // default false, force the console onto this device so it does not move
    -   *                //   if false, changes in connection state (eg USB/Bluetooth) can move
    -   *                //   the console automatically.
    +   *
    +   * ```
    +   * {
    +   *   force : bool // default false, force the console onto this device so it does not move
    +   *                //   if false, changes in connection state (eg USB/Bluetooth) can move
    +   *                //   the console automatically.
        * }
    -   * `
    + * ``` + * * @url http://www.espruino.com/Reference#l_E_setConsole */ setConsole: (device: any, options: any) => void; /** * Returns the current console device - see `E.setConsole` for more information. + * * @url http://www.espruino.com/Reference#l_E_getConsole */ getConsole: () => any; /** * Reverse the 8 bits in a byte, swapping MSB and LSB. + * * For example, `E.reverseByte(0b10010000) == 0b00001001`. + * * Note that you can reverse all the bytes in an array with: `arr = arr.map(E.reverseByte)` + * * @url http://www.espruino.com/Reference#l_E_reverseByte */ reverseByte: (x: number) => number; /** * Output the current list of Utility Timer Tasks - for debugging only + * * @url http://www.espruino.com/Reference#l_E_dumpTimers */ dumpTimers: () => void; /** * Dump any locked variables that aren't referenced from `global` - for debugging memory leaks only. + * * @url http://www.espruino.com/Reference#l_E_dumpLockedVars */ dumpLockedVars: () => void; /** * Dump any locked variables that aren't referenced from `global` - for debugging memory leaks only. + * * @url http://www.espruino.com/Reference#l_E_dumpFreeList */ dumpFreeList: () => void; @@ -4830,12 +5845,14 @@ declare const E: { * Dumps a comma-separated list of all allocated variables * along with the variables they link to. Can be used * to visualise where memory is used. + * * @url http://www.espruino.com/Reference#l_E_dumpVariables */ dumpVariables: () => void; /** * BETA: defragment memory! + * * @url http://www.espruino.com/Reference#l_E_defrag */ defrag: () => void; @@ -4844,27 +5861,35 @@ declare const E: { * Return the number of variable blocks used by the supplied variable. This is * useful if you're running out of memory and you want to be able to see what * is taking up most of the available space. + * * If `depth>0` and the variable can be recursed into, an array listing all property * names (including internal Espruino names) and their sizes is returned. If * `depth>1` there is also a `more` field that inspects the objects's children's * children. + * * For instance `E.getSizeOf(function(a,b) { })` returns `5`. + * * But `E.getSizeOf(function(a,b) { }, 1)` returns: - *
    ` [
    +   *
    +   * ```
    +   *  [
        *   {
    -   *     "name": "a",
    -   *     "size": 1 },
    +   *     "name": "a",
    +   *     "size": 1 },
        *   {
    -   *     "name": "b",
    -   *     "size": 1 },
    +   *     "name": "b",
    +   *     "size": 1 },
        *   {
    -   *     "name": "\xFFcod",
    -   *     "size": 2 }
    +   *     "name": "\xFFcod",
    +   *     "size": 2 }
        *  ]
    -   * `
    + * ``` + * * In this case setting depth to `2` will make no difference as there are * no more children to traverse. + * * See [http://www.espruino.com/Internals](http://www.espruino.com/Internals) for more information + * * @url http://www.espruino.com/Reference#l_E_getSizeOf */ getSizeOf: (v: any, depth: number) => any; @@ -4873,10 +5898,13 @@ declare const E: { * Return the address in memory of the given variable. This can then * be used with `peek` and `poke` functions. However, changing data in * JS variables directly (flatAddress=false) will most likely result in a crash. + * * This functions exists to allow embedded targets to set up * peripherals such as DMA so that they write directly to * JS variables. + * * See [http://www.espruino.com/Internals](http://www.espruino.com/Internals) for more information + * * @url http://www.espruino.com/Reference#l_E_getAddressOf */ getAddressOf: (v: any, flatAddress: boolean) => number; @@ -4885,49 +5913,59 @@ declare const E: { * Take each element of the `from` array, look it up in `map` (or call `map(value,index)` * if it is a function), and write it into the corresponding * element in the `to` array. + * * You can use an array to map: - *
    `var a = new Uint8Array([1,2,3,1,2,3]);
    -   * var lut = new Uint8Array([128,129,130,131]);
    -   * E.mapInPlace(a, a, lut);
    -   * // a = [129, 130, 131, 129, 130, 131]
    -   * `
    + * + * ``` + * var a = new Uint8Array([1,2,3,1,2,3]); + * var lut = new Uint8Array([128,129,130,131]); + * E.mapInPlace(a, a, lut); + * // a = [129, 130, 131, 129, 130, 131] + * ``` + * * Or `undefined` to pass straight through, or a function to do a normal 'mapping': - *
    `var a = new Uint8Array([0x12,0x34,0x56,0x78]);
    -   * var b = new Uint8Array(8);
    -   * E.mapInPlace(a, b, undefined); // straight through
    -   * // b = [0x12,0x34,0x56,0x78,0,0,0,0]
    -   * E.mapInPlace(a, b, (value,index)=>index); // write the index in the first 4 (because a.length==4)
    -   * // b = [0,1,2,3,4,0,0,0]
    -   * E.mapInPlace(a, b, undefined, 4); // 4 bits from 8 bit input -> 2x as many outputs, msb-first
    -   * // b = [1, 2, 3, 4, 5, 6, 7, 8]
    -   *  E.mapInPlace(a, b, undefined, -4); // 4 bits from 8 bit input -> 2x as many outputs, lsb-first
    -   * // b = [2, 1, 4, 3, 6, 5, 8, 7]
    -   * E.mapInPlace(a, b, a=>a+2, 4);
    -   * // b = [3, 4, 5, 6, 7, 8, 9, 10]
    -   * var b = new Uint16Array(4);
    -   * E.mapInPlace(a, b, undefined, 12); // 12 bits from 8 bit input, msb-first
    -   * // b = [0x123, 0x456, 0x780, 0]
    -   * E.mapInPlace(a, b, undefined, -12); // 12 bits from 8 bit input, lsb-first
    -   * // b = [0x412, 0x563, 0x078, 0]
    -   * `
    + * + * ``` + * var a = new Uint8Array([0x12,0x34,0x56,0x78]); + * var b = new Uint8Array(8); + * E.mapInPlace(a, b, undefined); // straight through + * // b = [0x12,0x34,0x56,0x78,0,0,0,0] + * E.mapInPlace(a, b, (value,index)=>index); // write the index in the first 4 (because a.length==4) + * // b = [0,1,2,3,4,0,0,0] + * E.mapInPlace(a, b, undefined, 4); // 4 bits from 8 bit input -> 2x as many outputs, msb-first + * // b = [1, 2, 3, 4, 5, 6, 7, 8] + * E.mapInPlace(a, b, undefined, -4); // 4 bits from 8 bit input -> 2x as many outputs, lsb-first + * // b = [2, 1, 4, 3, 6, 5, 8, 7] + * E.mapInPlace(a, b, a=>a+2, 4); + * // b = [3, 4, 5, 6, 7, 8, 9, 10] + * var b = new Uint16Array(4); + * E.mapInPlace(a, b, undefined, 12); // 12 bits from 8 bit input, msb-first + * // b = [0x123, 0x456, 0x780, 0] + * E.mapInPlace(a, b, undefined, -12); // 12 bits from 8 bit input, lsb-first + * // b = [0x412, 0x563, 0x078, 0] + * ``` + * * @url http://www.espruino.com/Reference#l_E_mapInPlace */ mapInPlace: (from: any, to: any, map: any, bits: number) => void; /** * Search in an Object, Array, or Function + * * @url http://www.espruino.com/Reference#l_E_lookupNoCase */ lookupNoCase: (haystack: any, needle: any, returnKey: boolean) => any; /** * Get the current interpreter state in a text form such that it can be copied to a new device + * * @url http://www.espruino.com/Reference#l_E_dumpStr */ dumpStr: () => string; /** * Set the seed for the random number generator used by `Math.random()`. + * * @url http://www.espruino.com/Reference#l_E_srand */ srand: (v: number) => void; @@ -4937,6 +5975,7 @@ declare const E: { * method reads from the internal voltage reference several times, xoring and * rotating to try and make a relatively random value from the noise in the * signal. + * * @url http://www.espruino.com/Reference#l_E_hwRand */ hwRand: () => number; @@ -4944,16 +5983,20 @@ declare const E: { /** * Perform a standard 32 bit CRC (Cyclic redundancy check) on the supplied data (one byte at a time) * and return the result as an unsigned integer. + * * @url http://www.espruino.com/Reference#l_E_CRC32 */ CRC32: (data: any) => any; /** * Convert hue, saturation and brightness to red, green and blue (packed into an integer if `asArray==false` or an array if `asArray==true`). + * * This replaces `Graphics.setColorHSB` and `Graphics.setBgColorHSB`. On devices with 24 bit colour it can * be used as: `Graphics.setColor(E.HSBtoRGB(h, s, b))` + * * You can quickly set RGB items in an Array or Typed Array using `array.set(E.HSBtoRGB(h, s, b,true), offset)`, * which can be useful with arrays used with `require("neopixel").write`. + * * @url http://www.espruino.com/Reference#l_E_HSBtoRGB */ HSBtoRGB: (hue: number, sat: number, bri: number, asArray: boolean) => any; @@ -4962,13 +6005,17 @@ declare const E: { * Set a password on the console (REPL). When powered on, Espruino will * then demand a password before the console can be used. If you want to * lock the console immediately after this you can call `E.lockConsole()` + * * To remove the password, call this function with no arguments. + * * **Note:** There is no protection against multiple password attempts, so someone * could conceivably try every password in a dictionary. + * * **Note:** This password is stored in memory in plain text. If someone is able * to execute arbitrary JavaScript code on the device (eg, you use `eval` on input * from unknown sources) or read the device's firmware then they may be able to * obtain it. + * * @url http://www.espruino.com/Reference#l_E_setPassword */ setPassword: (password: any) => void; @@ -4976,22 +6023,28 @@ declare const E: { /** * If a password has been set with `E.setPassword()`, this will lock the console * so the password needs to be entered to unlock it. + * * @url http://www.espruino.com/Reference#l_E_lockConsole */ lockConsole: () => void; /** * Set the time zone to be used with `Date` objects. + * * For example `E.setTimeZone(1)` will be GMT+0100 + * * Note that `E.setTimeZone()` will have no effect when daylight savings time rules have been set with `E.setDST()`. The * timezone value will be stored, but never used so long as DST settings are in effect. + * * Time can be set with `setTime`. + * * @url http://www.espruino.com/Reference#l_E_setTimeZone */ setTimeZone: (zone: number) => void; /** * Set the daylight savings time parameters to be used with `Date` objects. + * * The parameters are * * - dstOffset: The number of minutes daylight savings time adds to the clock (usually 60) - set to 0 to disable DST @@ -5011,10 +6064,14 @@ declare const E: { * "DST starts on the last Sunday of March (plus 0 days) at 03:00". Since it's the last Sunday, we have startDowNumber = 4, and since * it's Sunday, we have startDow = 0. That it is March gives us startMonth = 2, and that the offset is zero days, we have * startDayOffset = 0. The time that DST starts gives us startTimeOfDay = 3*60. + * * "DST ends on the Friday before the second Sunday in November at 02:00" would give us endDowNumber=1, endDow=0, endMonth=10, endDayOffset=-2 and endTimeOfDay=120. + * * Using Ukraine as an example, we have a time which is 2 hours ahead of GMT in winter (EET) and 3 hours in summer (EEST). DST starts at 03:00 EET on the last Sunday in March, * and ends at 04:00 EEST on the last Sunday in October. So someone in Ukraine might call `E.setDST(60,120,4,0,2,0,180,4,0,9,0,240);` + * * Note that when DST parameters are set (i.e. when `dstOffset` is not zero), `E.setTimeZone()` has no effect. + * * @url http://www.espruino.com/Reference#l_E_setDST */ setDST: (params: any) => void; @@ -5022,32 +6079,41 @@ declare const E: { /** * Create an object where every field accesses a specific 32 bit address in the microcontroller's memory. This * is perfect for accessing on-chip peripherals. - *
    `// for NRF52 based chips
    -   * var GPIO = E.memoryMap(0x50000000,{OUT:0x504, OUTSET:0x508, OUTCLR:0x50C, IN:0x510, DIR:0x514, DIRSET:0x518, DIRCLR:0x51C});
    -   * GPIO.DIRSET = 1; // set GPIO0 to output
    -   * GPIO.OUT ^= 1; // toggle the output state of GPIO0
    -   * `
    + * + * ``` + * // for NRF52 based chips + * var GPIO = E.memoryMap(0x50000000,{OUT:0x504, OUTSET:0x508, OUTCLR:0x50C, IN:0x510, DIR:0x514, DIRSET:0x518, DIRCLR:0x51C}); + * GPIO.DIRSET = 1; // set GPIO0 to output + * GPIO.OUT ^= 1; // toggle the output state of GPIO0 + * ``` + * * @url http://www.espruino.com/Reference#l_E_memoryMap */ memoryMap: (baseAddress: any, registers: any) => any; /** * Provide assembly to Espruino. + * * **This function is not part of Espruino**. Instead, it is detected * by the Espruino IDE (or command-line tools) at upload time and is * replaced with machine code and an `E.nativeCall` call. + * * See [the documentation on the Assembler](http://www.espruino.com/Assembler) for more information. + * * @url http://www.espruino.com/Reference#l_E_asm */ asm: (callspec: any, assemblycode: any) => void; /** * Provides the ability to write C code inside your JavaScript file. + * * **This function is not part of Espruino**. Instead, it is detected * by the Espruino IDE (or command-line tools) at upload time, is sent * to our web service to be compiled, and is replaced with machine code * and an `E.nativeCall` call. + * * See [the documentation on Inline C](http://www.espruino.com/InlineC) for more information and examples. + * * @url http://www.espruino.com/Reference#l_E_compiledC */ compiledC: (code: any) => void; @@ -5055,9 +6121,11 @@ declare const E: { /** * Forces a hard reboot of the microcontroller - as close as possible * to if the reset pin had been toggled. + * * **Note:** This is different to `reset()`, which performs a software * reset of Espruino (resetting the interpreter and pin states, but not * all the hardware) + * * @url http://www.espruino.com/Reference#l_E_reboot */ reboot: () => void; @@ -5066,6 +6134,7 @@ declare const E: { * USB HID will only take effect next time you unplug and re-plug your Espruino. If you're * disconnecting it from power you'll have to make sure you have `save()`d after calling * this function. + * * @url http://www.espruino.com/Reference#l_E_setUSBHID */ setUSBHID: (opts: any) => void; @@ -5078,10 +6147,12 @@ declare const E: { /** * In devices that come with batteries, this function returns * the battery charge percentage as an integer between 0 and 100. + * * **Note:** this is an estimation only, based on battery voltage. * The temperature of the battery (as well as the load being drawn * from it at the time `E.getBattery` is called) will affect the * readings. + * * @url http://www.espruino.com/Reference#l_E_getBattery */ getBattery: () => number; @@ -5089,35 +6160,48 @@ declare const E: { /** * Sets the RTC's prescaler's maximum value. This is the counter that counts up on each oscillation of the low * speed oscillator. When the prescaler counts to the value supplied, one second is deemed to have passed. + * * By default this is set to the oscillator's average speed as specified in the datasheet, and usually that is * fine. However on early [Espruino Pico](https://espruino.com//Pico) boards the STM32F4's internal oscillator could vary by as * much as 15% from the value in the datasheet. In that case you may want to alter this value to reflect the * true RTC speed for more accurate timekeeping. + * * To change the RTC's prescaler value to a computed value based on comparing against the high speed oscillator, * just run the following command, making sure it's done a few seconds after the board starts up: - *
    `E.setRTCPrescaler(E.getRTCPrescaler(true));
    -   * `
    + * + * ``` + * E.setRTCPrescaler(E.getRTCPrescaler(true)); + * ``` + * * When changing the RTC prescaler, the RTC 'follower' counters are reset and it can take a second or two before * readings from getTime are stable again. + * * To test, you can connect an input pin to a known frequency square wave and then use `setWatch`. If you don't * have a frequency source handy, you can check against the high speed oscillator: - *
    `// connect pin B3 to B4
    -   * analogWrite(B3, 0.5, {freq:0.5});
    -   * setWatch(function(e) {
    -   *   print(e.time - e.lastTime);
    +   *
    +   * ```
    +   * // connect pin B3 to B4
    +   * analogWrite(B3, 0.5, {freq:0.5});
    +   * setWatch(function(e) {
    +   *   print(e.time - e.lastTime);
        * }, B4, {repeat:true});
    -   * `
    + * ``` + * * **Note:** This is only used on official Espruino boards containing an STM32 microcontroller. Other boards * (even those using an STM32) don't use the RTC and so this has no effect. + * * @url http://www.espruino.com/Reference#l_E_setRTCPrescaler */ setRTCPrescaler: (prescaler: number) => void; /** * Gets the RTC's current prescaler value if `calibrate` is undefined or false. + * * If `calibrate` is true, the low speed oscillator's speed is calibrated against the high speed * oscillator (usually +/- 20 ppm) and a suggested value to be fed into `E.setRTCPrescaler(...)` is returned. + * * See `E.setRTCPrescaler` for more information. + * * @url http://www.espruino.com/Reference#l_E_getRTCPrescaler */ getRTCPrescaler: (calibrate: boolean) => number; @@ -5133,12 +6217,15 @@ declare const E: { * - Or finally if nothing else matches, the character is ignored * * For instance: - *
    `let unicodeRemap = {
    -   *   0x20ac:"\u0080", // Euro symbol
    -   *   0x2026:"\u0085", // Ellipsis
    +   *
    +   * ```
    +   * let unicodeRemap = {
    +   *   0x20ac:"\u0080", // Euro symbol
    +   *   0x2026:"\u0085", // Ellipsis
        * };
    -   * E.decodeUTF8("UTF-8 Euro: \u00e2\u0082\u00ac", unicodeRemap, '[?]') == "UTF-8 Euro: \u0080"
    -   * `
    + * E.decodeUTF8("UTF-8 Euro: \u00e2\u0082\u00ac", unicodeRemap, '[?]') == "UTF-8 Euro: \u0080" + * ``` + * * @url http://www.espruino.com/Reference#l_E_decodeUTF8 */ decodeUTF8: (str: any, lookup: any, replaceFn: any) => any; @@ -5147,6 +6234,7 @@ declare const E: { /** * Creates an InternalError object + * * @url http://www.espruino.com/Reference#l_InternalError_InternalError */ declare function InternalError(message: any): any; @@ -5156,6 +6244,7 @@ type InternalError = { /** * This is the built-in class for the Arduino-style pin namings on ST Nucleo boards + * * @url http://www.espruino.com/Reference#Nucleo */ declare const Nucleo: { @@ -5273,6 +6362,7 @@ declare const Nucleo: { /** * This is a built-in class to allow you to use the ESP8266 NodeMCU boards's pin namings to access pins. It is only available on ESP8266-based boards. + * * @url http://www.espruino.com/Reference#NodeMCU */ declare const NodeMCU: { @@ -5340,6 +6430,7 @@ declare const NodeMCU: { /** * Class containing utility functions for the [ESP32](http://www.espruino.com/ESP32) + * * @url http://www.espruino.com/Reference#ESP32 */ declare const ESP32: { @@ -5350,12 +6441,14 @@ declare const ESP32: { /** * Perform a hardware reset/reboot of the ESP32. + * * @url http://www.espruino.com/Reference#l_ESP32_reboot */ reboot: () => void; /** * Put device in deepsleep state for "us" microseconds. + * * @url http://www.espruino.com/Reference#l_ESP32_deepSleep */ deepSleep: (us: number) => void; @@ -5381,6 +6474,7 @@ declare const ESP32: { /** * Switches Bluetooth off/on, removes saved code from Flash, resets the board, * and on restart creates jsVars depending on available heap (actual additional 1800) + * * @url http://www.espruino.com/Reference#l_ESP32_enableBLE */ enableBLE: (enable: boolean) => void; @@ -5388,6 +6482,7 @@ declare const ESP32: { /** * Switches Wifi off/on, removes saved code from Flash, resets the board, * and on restart creates jsVars depending on available heap (actual additional 3900) + * * @url http://www.espruino.com/Reference#l_ESP32_enableWifi */ enableWifi: (enable: boolean) => void; @@ -5396,6 +6491,7 @@ declare const ESP32: { /** * Creates a Queue Object + * * @url http://www.espruino.com/Reference#l_Queue_Queue */ declare function Queue(queueName: any): any; @@ -5403,18 +6499,21 @@ declare function Queue(queueName: any): any; type Queue = { /** * reads one character from queue, if available + * * @url http://www.espruino.com/Reference#l_Queue_read */ read: () => void; /** * Writes one character to queue + * * @url http://www.espruino.com/Reference#l_Queue_writeChar */ writeChar: (char: any) => void; /** * logs list of queues + * * @url http://www.espruino.com/Reference#l_Queue_log */ log: () => void; @@ -5423,6 +6522,7 @@ type Queue = { /** * Creates a Task Object + * * @url http://www.espruino.com/Reference#l_Task_Task */ declare function Task(taskName: any): any; @@ -5430,30 +6530,35 @@ declare function Task(taskName: any): any; type Task = { /** * Suspend task, be careful not to suspend Espruino task itself + * * @url http://www.espruino.com/Reference#l_Task_suspend */ suspend: () => void; /** * Resumes a suspended task + * * @url http://www.espruino.com/Reference#l_Task_resume */ resume: () => void; /** * returns name of actual task + * * @url http://www.espruino.com/Reference#l_Task_getCurrent */ getCurrent: () => any; /** * Sends a binary notify to task + * * @url http://www.espruino.com/Reference#l_Task_notify */ notify: () => void; /** * logs list of tasks + * * @url http://www.espruino.com/Reference#l_Task_log */ log: () => void; @@ -5462,6 +6567,7 @@ type Task = { /** * Creates a Timer Object + * * @url http://www.espruino.com/Reference#l_Timer_Timer */ declare function Timer(timerName: any, group: number, index: number, isrIndex: number): any; @@ -5469,18 +6575,21 @@ declare function Timer(timerName: any, group: number, index: number, isrIndex: n type Timer = { /** * Starts a timer + * * @url http://www.espruino.com/Reference#l_Timer_start */ start: (duration: number) => void; /** * Reschedules a timer, needs to be started at least once + * * @url http://www.espruino.com/Reference#l_Timer_reschedule */ reschedule: (duration: number) => void; /** * logs list of timers + * * @url http://www.espruino.com/Reference#l_Timer_log */ log: () => void; @@ -5489,7 +6598,9 @@ type Timer = { /** * **Note:** This function is only available on the [BBC micro:bit](https://espruino.com//MicroBit) board + * * Show an image on the in-built 5x5 LED screen. + * * Image can be: * * - A number where each bit represents a pixel (so 25 bits). eg. `5` or `0x1FFFFFF` @@ -5498,156 +6609,190 @@ type Timer = { * - An array of 4 bytes (more will be ignored), eg `show([1,2,3,0])` * * For instance the following works for images: - *
    `show("#   #"+
    - *      "  #  "+
    - *      "  #  "+
    - *      "#   #"+
    - *      " ### ")
    - * `
    + * + * ``` + * show("# #"+ + * " # "+ + * " # "+ + * "# #"+ + * " ### ") + * ``` + * * This means you can also use Espruino's graphics library: - *
    `var g = Graphics.createArrayBuffer(5,5,1)
    - * g.drawString("E",0,0)
    - * show(g.buffer)
    - * `
    + * + * ``` + * var g = Graphics.createArrayBuffer(5,5,1) + * g.drawString("E",0,0) + * show(g.buffer) + * ``` + * * @url http://www.espruino.com/Reference#l__global_show */ declare function show(image: any): void; /** * **Note:** This function is only available on the [BBC micro:bit](https://espruino.com//MicroBit) board + * * Get the current acceleration of the micro:bit from the on-board accelerometer + * * **This is deprecated.** Please use `Microbit.accel` instead. + * * @url http://www.espruino.com/Reference#l__global_acceleration */ declare function acceleration(): any; /** * **Note:** This function is only available on the [BBC micro:bit](https://espruino.com//MicroBit) board + * * Get the current compass position for the micro:bit from the on-board magnetometer + * * **This is deprecated.** Please use `Microbit.mag` instead. + * * @url http://www.espruino.com/Reference#l__global_compass */ declare function compass(): any; /** * The pin connected to the 'A' button. Reads as `1` when pressed, `0` when not + * * @url http://www.espruino.com/Reference#l__global_BTNA */ declare const BTNA: Pin; /** * The pin connected to the 'B' button. Reads as `1` when pressed, `0` when not + * * @url http://www.espruino.com/Reference#l__global_BTNB */ declare const BTNB: Pin; /** * The pin connected to the up button. Reads as `1` when pressed, `0` when not + * * @url http://www.espruino.com/Reference#l__global_BTNU */ declare const BTNU: Pin; /** * The pin connected to the down button. Reads as `1` when pressed, `0` when not + * * @url http://www.espruino.com/Reference#l__global_BTND */ declare const BTND: Pin; /** * The pin connected to the left button. Reads as `1` when pressed, `0` when not + * * @url http://www.espruino.com/Reference#l__global_BTNL */ declare const BTNL: Pin; /** * The pin connected to the right button. Reads as `1` when pressed, `0` when not + * * @url http://www.espruino.com/Reference#l__global_BTNR */ declare const BTNR: Pin; /** * The pin connected to Corner #1 + * * @url http://www.espruino.com/Reference#l__global_CORNER1 */ declare const CORNER1: Pin; /** * The pin connected to Corner #2 + * * @url http://www.espruino.com/Reference#l__global_CORNER2 */ declare const CORNER2: Pin; /** * The pin connected to Corner #3 + * * @url http://www.espruino.com/Reference#l__global_CORNER3 */ declare const CORNER3: Pin; /** * The pin connected to Corner #4 + * * @url http://www.espruino.com/Reference#l__global_CORNER4 */ declare const CORNER4: Pin; /** * The pin connected to Corner #5 + * * @url http://www.espruino.com/Reference#l__global_CORNER5 */ declare const CORNER5: Pin; /** * The pin connected to Corner #6 + * * @url http://www.espruino.com/Reference#l__global_CORNER6 */ declare const CORNER6: Pin; /** * On Puck.js V2 (not v1.0) this is the pin that controls the FET, for high-powered outputs. + * * @url http://www.espruino.com/Reference#l__global_FET */ declare const FET: Pin; /** * The pin marked SDA on the Arduino pin footprint. This is connected directly to pin A4. + * * @url http://www.espruino.com/Reference#l__global_SDA */ declare const SDA: Pin; /** * The pin marked SDA on the Arduino pin footprint. This is connected directly to pin A5. + * * @url http://www.espruino.com/Reference#l__global_SCL */ declare const SCL: Pin; /** * The Bangle.js's vibration motor. + * * @url http://www.espruino.com/Reference#l__global_VIBRATE */ declare const VIBRATE: Pin; /** * On most Espruino board there are LEDs, in which case `LED` will be an actual Pin. + * * On Bangle.js there are no LEDs, so to remain compatible with example code that might * expect an LED, this is an object that behaves like a pin, but which just displays * a circle on the display + * * @url http://www.espruino.com/Reference#l__global_LED */ declare const LED: any; /** * On most Espruino board there are LEDs, in which case `LED1` will be an actual Pin. + * * On Bangle.js there are no LEDs, so to remain compatible with example code that might * expect an LED, this is an object that behaves like a pin, but which just displays * a circle on the display + * * @url http://www.espruino.com/Reference#l__global_LED1 */ declare const LED1: any; /** * On most Espruino board there are LEDs, in which case `LED2` will be an actual Pin. + * * On Bangle.js there are no LEDs, so to remain compatible with example code that might * expect an LED, this is an object that behaves like a pin, but which just displays * a circle on the display + * * @url http://www.espruino.com/Reference#l__global_LED2 */ declare const LED2: any; @@ -5704,32 +6849,41 @@ declare const LOW: number; /** * A variable containing the arguments given to the function: - *
    `function hello() {
    - *   console.log(arguments.length, JSON.stringify(arguments));
    + *
    + * ```
    + * function hello() {
    + *   console.log(arguments.length, JSON.stringify(arguments));
      * }
    - * hello()        // 0 []
    - * hello("Test")  // 1 ["Test"]
    - * hello(1,2,3)   // 3 [1,2,3]
    - * `
    + * hello() // 0 [] + * hello("Test") // 1 ["Test"] + * hello(1,2,3) // 3 [1,2,3] + * ``` + * * **Note:** Due to the way Espruino works this is doesn't behave exactly * the same as in normal JavaScript. The length of the arguments array * will never be less than the number of arguments specified in the * function declaration: `(function(a){ return arguments.length; })() == 1`. * Normal JavaScript interpreters would return `0` in the above case. + * * @url http://www.espruino.com/Reference#l__global_arguments */ declare const arguments: any; /** * Load the given module, and return the exported functions and variables. + * * For example: - *
    `var s = require("Storage");
    - * s.write("test", "hello world");
    - * print(s.read("test"));
    - * // prints "hello world"
    - * `
    + * + * ``` + * var s = require("Storage"); + * s.write("test", "hello world"); + * print(s.read("test")); + * // prints "hello world" + * ``` + * * Check out [the page on Modules](https://espruino.com//Modules) for an explanation * of what modules are and how you can use them. + * * @url http://www.espruino.com/Reference#l__global_require */ declare function require(moduleName: T): Modules[T]; @@ -5737,51 +6891,62 @@ declare function require>(moduleName: T /** * Read 8 bits of memory at the given location - DANGEROUS! + * * @url http://www.espruino.com/Reference#l__global_peek8 */ declare function peek8(addr: number, count: number): any; /** * Write 8 bits of memory at the given location - VERY DANGEROUS! + * * @url http://www.espruino.com/Reference#l__global_poke8 */ declare function poke8(addr: number, value: any): void; /** * Read 16 bits of memory at the given location - DANGEROUS! + * * @url http://www.espruino.com/Reference#l__global_peek16 */ declare function peek16(addr: number, count: number): any; /** * Write 16 bits of memory at the given location - VERY DANGEROUS! + * * @url http://www.espruino.com/Reference#l__global_poke16 */ declare function poke16(addr: number, value: any): void; /** * Read 32 bits of memory at the given location - DANGEROUS! + * * @url http://www.espruino.com/Reference#l__global_peek32 */ declare function peek32(addr: number, count: number): any; /** * Write 32 bits of memory at the given location - VERY DANGEROUS! + * * @url http://www.espruino.com/Reference#l__global_poke32 */ declare function poke32(addr: number, value: any): void; /** * Get the analog value of the given pin + * * This is different to Arduino which only returns an integer between 0 and 1023 + * * However only pins connected to an ADC will work (see the datasheet) + * * **Note:** if you didn't call `pinMode` beforehand then this function will also reset pin's state to `"analog"` + * * @url http://www.espruino.com/Reference#l__global_analogRead */ declare function analogRead(pin: Pin): number; /** * Set the analog Value of a pin. It will be output using PWM. + * * Objects can contain: * * - `freq` - pulse frequency in Hz, eg. `analogWrite(A0,0.5,{ freq : 10 });` - specifying a frequency will force PWM output, even if the pin has a DAC @@ -5789,40 +6954,54 @@ declare function analogRead(pin: Pin): number; * - `forceSoft` - boolean, If true software PWM is used even if hardware PWM or a DAC is available * * **Note:** if you didn't call `pinMode` beforehand then this function will also reset pin's state to `"output"` + * * @url http://www.espruino.com/Reference#l__global_analogWrite */ declare function analogWrite(pin: Pin, value: number, options: any): void; /** * Pulse the pin with the value for the given time in milliseconds. It uses a hardware timer to produce accurate pulses, and returns immediately (before the pulse has finished). Use `digitalPulse(A0,1,0)` to wait until a previous pulse has finished. + * * eg. `digitalPulse(A0,1,5);` pulses A0 high for 5ms. `digitalPulse(A0,1,[5,2,4]);` pulses A0 high for 5ms, low for 2ms, and high for 4ms + * * **Note:** if you didn't call `pinMode` beforehand then this function will also reset pin's state to `"output"` + * * digitalPulse is for SHORT pulses that need to be very accurate. If you're doing anything over a few milliseconds, use setTimeout instead. + * * @url http://www.espruino.com/Reference#l__global_digitalPulse */ declare function digitalPulse(pin: Pin, value: boolean, time: any): void; /** * Set the digital value of the given pin. + * * **Note:** if you didn't call `pinMode` beforehand then this function will also reset pin's state to `"output"` + * * If pin argument is an array of pins (eg. `[A2,A1,A0]`) the value argument will be treated * as an array of bits where the last array element is the least significant bit. + * * In this case, pin values are set least significant bit first (from the right-hand side * of the array of pins). This means you can use the same pin multiple times, for * example `digitalWrite([A1,A1,A0,A0],0b0101)` would pulse A0 followed by A1. + * * If the pin argument is an object with a `write` method, the `write` method will * be called with the value passed through. + * * @url http://www.espruino.com/Reference#l__global_digitalWrite */ declare function digitalWrite(pin: Pin, value: number): void; /** * Get the digital value of the given pin. + * * **Note:** if you didn't call `pinMode` beforehand then this function will also reset pin's state to `"input"` + * * If the pin argument is an array of pins (eg. `[A2,A1,A0]`) the value returned will be an number where * the last array element is the least significant bit, for example if `A0=A1=1` and `A2=0`, `digitalRead([A2,A1,A0]) == 0b011` + * * If the pin argument is an object with a `read` method, the `read` method will be called and the integer value it returns * passed back. + * * @url http://www.espruino.com/Reference#l__global_digitalRead */ declare function digitalRead(pin: Pin): number; @@ -5845,12 +7024,14 @@ declare function digitalRead(pin: Pin): number; * If you want `digitalRead`/etc to set the pin mode automatically after you have called `pinMode`, simply call it again * with no mode argument (`pinMode(pin)`), `auto` as the argument (`pinMode(pin, "auto")`), or with the 3rd 'automatic' * argument set to true (`pinMode(pin, "output", true)`). + * * @url http://www.espruino.com/Reference#l__global_pinMode */ declare function pinMode(pin: Pin, mode: any, automatic: boolean): void; /** * Return the current mode of the given pin. See `pinMode` for more information on returned values. + * * @url http://www.espruino.com/Reference#l__global_getPinMode */ declare function getPinMode(pin: Pin): any; @@ -5858,56 +7039,72 @@ declare function getPinMode(pin: Pin): any; /** * Shift an array of data out using the pins supplied *least significant bit first*, * for example: - *
    `// shift out to single clk+data
    - * shiftOut(A0, { clk : A1 }, [1,0,1,0]);
    - * `
    - *
    `// shift out a whole byte (like software SPI)
    - * shiftOut(A0, { clk : A1, repeat: 8 }, [1,2,3,4]);
    - * `
    - *
    `// shift out via 4 data pins
    - * shiftOut([A3,A2,A1,A0], { clk : A4 }, [1,2,3,4]);
    - * `
    + * + * ``` + * // shift out to single clk+data + * shiftOut(A0, { clk : A1 }, [1,0,1,0]); + * ``` + * + * ``` + * // shift out a whole byte (like software SPI) + * shiftOut(A0, { clk : A1, repeat: 8 }, [1,2,3,4]); + * ``` + * + * ``` + * // shift out via 4 data pins + * shiftOut([A3,A2,A1,A0], { clk : A4 }, [1,2,3,4]); + * ``` + * * `options` is an object of the form: - *
    `{
    - *   clk : pin, // a pin to use as the clock (undefined = no pin)
    - *   clkPol : bool, // clock polarity - default is 0 (so 1 normally, pulsing to 0 to clock data in)
    - *   repeat : int, // number of clocks per array item
    + *
    + * ```
    + * {
    + *   clk : pin, // a pin to use as the clock (undefined = no pin)
    + *   clkPol : bool, // clock polarity - default is 0 (so 1 normally, pulsing to 0 to clock data in)
    + *   repeat : int, // number of clocks per array item
      * }
    - * `
    + * ``` + * * Each item in the `data` array will be output to the pins, with the first * pin in the array being the MSB and the last the LSB, then the clock will be * pulsed in the polarity given. + * * `repeat` is the amount of times shift data out for each array item. For instance * we may want to shift 8 bits out through 2 pins - in which case we need to set * repeat to 4. + * * @url http://www.espruino.com/Reference#l__global_shiftOut */ declare function shiftOut(pins: any, options: any, data: any): void; /** * Call the function specified when the pin changes. Watches set with `setWatch` can be removed using `clearWatch`. + * * If the `options` parameter is an object, it can contain the following information (all optional): - *
    `{
    - *    // Whether to keep producing callbacks, or remove the watch after the first callback
    - *    repeat: true/false(default),
    - *    // Trigger on the rising or falling edge of the signal. Can be a string, or 1='rising', -1='falling', 0='both'
    - *    edge:'rising'(default for built-in buttons)/'falling'/'both'(default for pins),
    - *    // Use software-debouncing to stop multiple calls if a switch bounces
    - *    // This is the time in milliseconds to wait for bounces to subside, or 0 to disable
    - *    debounce:10 (0 is default for pins, 25 is default for built-in buttons),
    - *    // Advanced: If the function supplied is a 'native' function (compiled or assembly)
    - *    // setting irq:true will call that function in the interrupt itself
    - *    irq : false(default)
    - *    // Advanced: If specified, the given pin will be read whenever the watch is called
    - *    // and the state will be included as a 'data' field in the callback
    + *
    + * ```
    + * {
    + *    // Whether to keep producing callbacks, or remove the watch after the first callback
    + *    repeat: true/false(default),
    + *    // Trigger on the rising or falling edge of the signal. Can be a string, or 1='rising', -1='falling', 0='both'
    + *    edge:'rising'(default for built-in buttons)/'falling'/'both'(default for pins),
    + *    // Use software-debouncing to stop multiple calls if a switch bounces
    + *    // This is the time in milliseconds to wait for bounces to subside, or 0 to disable
    + *    debounce:10 (0 is default for pins, 25 is default for built-in buttons),
    + *    // Advanced: If the function supplied is a 'native' function (compiled or assembly)
    + *    // setting irq:true will call that function in the interrupt itself
    + *    irq : false(default)
    + *    // Advanced: If specified, the given pin will be read whenever the watch is called
    + *    // and the state will be included as a 'data' field in the callback
      *    data : pin
    - *    // Advanced: On Nordic devices, a watch may be 'high' or 'low' accuracy. By default low
    - *    // accuracy is used (which is better for power consumption), but this means that
    - *    // high speed pulses (less than 25us) may not be reliably received. Setting hispeed=true
    - *    // allows for detecting high speed pulses at the expense of higher idle power consumption
    - *    hispeed : true
    + *    // Advanced: On Nordic devices, a watch may be 'high' or 'low' accuracy. By default low
    + *    // accuracy is used (which is better for power consumption), but this means that
    + *    // high speed pulses (less than 25us) may not be reliably received. Setting hispeed=true
    + *    // allows for detecting high speed pulses at the expense of higher idle power consumption
    + *    hispeed : true
      * }
    - * `
    + * ``` + * * The `function` callback is called with an argument, which is an object of type `{state:bool, time:float, lastTime:float}`. * * - `state` is whether the pin is currently a `1` or a `0` @@ -5917,59 +7114,76 @@ declare function shiftOut(pins: any, options: any, data: any): void; * * For instance, if you want to measure the length of a positive pulse you could use `setWatch(function(e) { console.log(e.time-e.lastTime); }, BTN, { repeat:true, edge:'falling' });`. * This will only be called on the falling edge of the pulse, but will be able to measure the width of the pulse because `e.lastTime` is the time of the rising edge. + * * Internally, an interrupt writes the time of the pin's state change into a queue with the exact * time that it happened, and the function supplied to `setWatch` is executed only from the main * message loop. However, if the callback is a native function `void (bool state)` then you can * add `irq:true` to options, which will cause the function to be called from within the IRQ. * When doing this, interrupts will happen on both edges and there will be no debouncing. + * * **Note:** if you didn't call `pinMode` beforehand then this function will reset pin's state to `"input"` - * **Note:** The STM32 chip (used in the [Pico](https://espruino.com//EspruinoBoard">Espruino Board
    and `setTime((new Date("Tue, 19 Feb 2019 10:57")).getTime()/1000) - * ` + * + * ``` + * setTime((new Date("Tue, 19 Feb 2019 10:57")).getTime()/1000) + * ``` + * * To set the timezone for all new Dates, use `E.setTimeZone(hours)`. + * * @url http://www.espruino.com/Reference#l__global_setTime */ declare function setTime(time: number): void; /** * Get the serial number of this board + * * @url http://www.espruino.com/Reference#l__global_getSerial */ declare function getSerial(): any; /** * Change the Interval on a callback created with `setInterval`, for example: + * * `var id = setInterval(function () { print('foo'); }, 1000); // every second` + * * `changeInterval(id, 1500); // now runs every 1.5 seconds` + * * This takes effect immediately and resets the timeout, so in the example above, * regardless of when you call `changeInterval`, the next interval will occur 1500ms * after it. + * * @url http://www.espruino.com/Reference#l__global_changeInterval */ declare function changeInterval(id: any, time: number): void; @@ -6095,66 +7341,82 @@ type Modules = { fs: { /** * List all files in the supplied directory, returning them as an array of strings. + * * NOTE: Espruino does not yet support Async file IO, so this function behaves like the 'Sync' version. + * * @url http://www.espruino.com/Reference#l_fs_readdir */ readdir: (path: any) => any; /** * List all files in the supplied directory, returning them as an array of strings. + * * @url http://www.espruino.com/Reference#l_fs_readdirSync */ readdirSync: (path: any) => any; /** * Write the data to the given file + * * NOTE: Espruino does not yet support Async file IO, so this function behaves like the 'Sync' version. + * * @url http://www.espruino.com/Reference#l_fs_writeFile */ writeFile: (path: any, data: any) => boolean; /** * Write the data to the given file + * * @url http://www.espruino.com/Reference#l_fs_writeFileSync */ writeFileSync: (path: any, data: any) => boolean; /** * Append the data to the given file, created a new file if it doesn't exist + * * NOTE: Espruino does not yet support Async file IO, so this function behaves like the 'Sync' version. + * * @url http://www.espruino.com/Reference#l_fs_appendFile */ appendFile: (path: any, data: any) => boolean; /** * Append the data to the given file, created a new file if it doesn't exist + * * @url http://www.espruino.com/Reference#l_fs_appendFileSync */ appendFileSync: (path: any, data: any) => boolean; /** * Read all data from a file and return as a string + * * NOTE: Espruino does not yet support Async file IO, so this function behaves like the 'Sync' version. + * * @url http://www.espruino.com/Reference#l_fs_readFile */ readFile: (path: any) => any; /** * Read all data from a file and return as a string. + * * **Note:** The size of files you can load using this method is limited by the amount of available RAM. To read files a bit at a time, see the `File` class. + * * @url http://www.espruino.com/Reference#l_fs_readFileSync */ readFileSync: (path: any) => any; /** * Delete the given file + * * NOTE: Espruino does not yet support Async file IO, so this function behaves like the 'Sync' version. + * * @url http://www.espruino.com/Reference#l_fs_unlink */ unlink: (path: any) => boolean; /** * Delete the given file + * * @url http://www.espruino.com/Reference#l_fs_unlinkSync */ unlinkSync: (path: any) => boolean; @@ -6162,22 +7424,27 @@ type Modules = { /** * Return information on the given file. This returns an object with the following * fields: + * * size: size in bytes * dir: a boolean specifying if the file is a directory or not * mtime: A Date structure specifying the time the file was last modified + * * @url http://www.espruino.com/Reference#l_fs_statSync */ statSync: (path: any) => any; /** * Create the directory + * * NOTE: Espruino does not yet support Async file IO, so this function behaves like the 'Sync' version. + * * @url http://www.espruino.com/Reference#l_fs_mkdir */ mkdir: (path: any) => boolean; /** * Create the directory + * * @url http://www.espruino.com/Reference#l_fs_mkdirSync */ mkdirSync: (path: any) => boolean; @@ -6191,45 +7458,53 @@ type Modules = { crypto: { /** * Class containing AES encryption/decryption + * * @url http://www.espruino.com/Reference#l_crypto_AES */ AES: any /** * Performs a SHA1 hash and returns the result as a 20 byte ArrayBuffer. + * * **Note:** On some boards (currently only Espruino Original) there * isn't space for a fully unrolled SHA1 implementation so a slower * all-JS implementation is used instead. + * * @url http://www.espruino.com/Reference#l_crypto_SHA1 */ SHA1: (message: any) => ArrayBuffer; /** * Performs a SHA224 hash and returns the result as a 28 byte ArrayBuffer + * * @url http://www.espruino.com/Reference#l_crypto_SHA224 */ SHA224: (message: any) => ArrayBuffer; /** * Performs a SHA256 hash and returns the result as a 32 byte ArrayBuffer + * * @url http://www.espruino.com/Reference#l_crypto_SHA256 */ SHA256: (message: any) => ArrayBuffer; /** * Performs a SHA384 hash and returns the result as a 48 byte ArrayBuffer + * * @url http://www.espruino.com/Reference#l_crypto_SHA384 */ SHA384: (message: any) => ArrayBuffer; /** * Performs a SHA512 hash and returns the result as a 64 byte ArrayBuffer + * * @url http://www.espruino.com/Reference#l_crypto_SHA512 */ SHA512: (message: any) => ArrayBuffer; /** * Password-Based Key Derivation Function 2 algorithm, using SHA512 + * * @url http://www.espruino.com/Reference#l_crypto_PBKDF2 */ PBKDF2: (passphrase: any, salt: any, options: any) => ArrayBuffer; @@ -6238,34 +7513,38 @@ type Modules = { NetworkJS: { /** * Initialise the network using the callbacks given and return the first argument. For instance: - *
    `require("NetworkJS").create({
    -     *   create : function(host, port, socketType, options) {
    -     *     // Create a socket and return its index, host is a string, port is an integer.
    -     *     // If host isn't defined, create a server socket
    -     *     console.log("Create",host,port);
    -     *     return 1;
    +     *
    +     * ```
    +     * require("NetworkJS").create({
    +     *   create : function(host, port, socketType, options) {
    +     *     // Create a socket and return its index, host is a string, port is an integer.
    +     *     // If host isn't defined, create a server socket
    +     *     console.log("Create",host,port);
    +     *     return 1;
          *   },
    -     *   close : function(sckt) {
    -     *     // Close the socket. returns nothing
    +     *   close : function(sckt) {
    +     *     // Close the socket. returns nothing
          *   },
    -     *   accept : function(sckt) {
    -     *     // Accept the connection on the server socket. Returns socket number or -1 if no connection
    -     *     return -1;
    +     *   accept : function(sckt) {
    +     *     // Accept the connection on the server socket. Returns socket number or -1 if no connection
    +     *     return -1;
          *   },
    -     *   recv : function(sckt, maxLen, socketType) {
    -     *     // Receive data. Returns a string (even if empty).
    -     *     // If non-string returned, socket is then closed
    -     *     return null;//or "";
    +     *   recv : function(sckt, maxLen, socketType) {
    +     *     // Receive data. Returns a string (even if empty).
    +     *     // If non-string returned, socket is then closed
    +     *     return null;//or "";
          *   },
    -     *   send : function(sckt, data, socketType) {
    -     *     // Send data (as string). Returns the number of bytes sent - 0 is ok.
    -     *     // Less than 0
    -     *     return data.length;
    +     *   send : function(sckt, data, socketType) {
    +     *     // Send data (as string). Returns the number of bytes sent - 0 is ok.
    +     *     // Less than 0
    +     *     return data.length;
          *   }
          * });
    -     * `
    + * ``` + * * `socketType` is an integer - 2 for UDP, or see SocketType in [https://github.com/espruino/Espruino/blob/master/libs/network/network.h](https://github.com/espruino/Espruino/blob/master/libs/network/network.h) * for more information. + * * @url http://www.espruino.com/Reference#l_NetworkJS_create */ create: (obj: any) => any; @@ -6281,13 +7560,16 @@ type Modules = { net: { /** * Create a Server + * * When a request to the server is made, the callback is called. In the callback you can use the methods on the connection to send data. You can also add `connection.on('data',function() { ... })` to listen for received data + * * @url http://www.espruino.com/Reference#l_net_createServer */ createServer: (callback: any) => Server; /** * Create a TCP socket connection + * * @url http://www.espruino.com/Reference#l_net_connect */ connect: (options: any, callback: any) => Socket; @@ -6296,6 +7578,7 @@ type Modules = { dgram: { /** * Create a UDP socket + * * @url http://www.espruino.com/Reference#l_dgram_createSocket */ createSocket: (type: any, callback: any) => dgramSocket; @@ -6304,22 +7587,30 @@ type Modules = { tls: { /** * Create a socket connection using TLS + * * Options can have `ca`, `key` and `cert` fields, which should be the decoded content of the certificate. - *
    `var options = url.parse("localhost:1234");
    -     * options.key = atob("MIIJKQ ... OZs08C");
    -     * options.cert = atob("MIIFi ... Uf93rN+");
    -     * options.ca = atob("MIIFgDCC ... GosQML4sc=");
    -     * require("tls").connect(options, ... );
    -     * `
    + * + * ``` + * var options = url.parse("localhost:1234"); + * options.key = atob("MIIJKQ ... OZs08C"); + * options.cert = atob("MIIFi ... Uf93rN+"); + * options.ca = atob("MIIFgDCC ... GosQML4sc="); + * require("tls").connect(options, ... ); + * ``` + * * If you have the certificates as `.pem` files, you need to load these files, take the information between the lines beginning with `----`, remove the newlines from it so you have raw base64, and then feed it into `atob` as above. + * * You can also: * * - Just specify the filename (<=100 characters) and it will be loaded and parsed if you have an SD card connected. For instance `options.key = "key.pem";` * - Specify a function, which will be called to retrieve the data. For instance `options.key = function() { eeprom.load_my_info(); }; * * For more information about generating and using certificates, see: + * * [https://engineering.circle.com/https-authorized-certs-with-node-js/](https://engineering.circle.com/https-authorized-certs-with-node-js/) + * * (You'll need to use 2048 bit certificates as opposed to 4096 bit shown above) + * * @url http://www.espruino.com/Reference#l_tls_connect */ connect: (options: any, callback: any) => Socket; @@ -6328,6 +7619,7 @@ type Modules = { CC3000: { /** * Initialise the CC3000 and return a WLAN object + * * @url http://www.espruino.com/Reference#l_CC3000_connect */ connect: (spi: any, cs: Pin, en: Pin, irq: Pin) => WLAN; @@ -6336,6 +7628,7 @@ type Modules = { WIZnet: { /** * Initialise the WIZnet module and return an Ethernet object + * * @url http://www.espruino.com/Reference#l_WIZnet_connect */ connect: (spi: any, cs: Pin) => Ethernet; @@ -6344,12 +7637,14 @@ type Modules = { Wifi: { /** * Disconnect the wifi station from an access point and disable the station mode. It is OK to call `disconnect` to turn off station mode even if no connection exists (for example, connection attempts may be failing). Station mode can be re-enabled by calling `connect` or `scan`. + * * @url http://www.espruino.com/Reference#l_Wifi_disconnect */ disconnect: (callback: any) => void; /** * Stop being an access point and disable the AP operation mode. AP mode can be re-enabled by calling `startAP`. + * * @url http://www.espruino.com/Reference#l_Wifi_stopAP */ stopAP: (callback: any) => void; @@ -6357,6 +7652,7 @@ type Modules = { /** * Connect to an access point as a station. If there is an existing connection to an AP it is first disconnected if the SSID or password are different from those passed as parameters. Put differently, if the passed SSID and password are identical to the currently connected AP then nothing is changed. * When the connection attempt completes the callback function is invoked with one `err` parameter, which is NULL if there is no error and a string message if there is an error. If DHCP is enabled the callback occurs once an IP addres has been obtained, if a static IP is set the callback occurs once the AP's network has been joined. The callback is also invoked if a connection already exists and does not need to be changed. + * * The options properties may contain: * * - `password` - Password string to be used to access the network. @@ -6396,6 +7692,7 @@ type Modules = { /** * Create a WiFi access point allowing stations to connect. If the password is NULL or an empty string the access point is open, otherwise it is encrypted. * The callback function is invoked once the access point is set-up and receives one `err` argument, which is NULL on success and contains an error message string otherwise. + * * The `options` object can contain the following properties. * * - `authMode` - The authentication mode to use. Can be one of "open", "wpa2", "wpa", "wpa_wpa2". The default is open (but open access points are not recommended). @@ -6434,6 +7731,7 @@ type Modules = { * - `powersave` - Power saving mode: `none` (radio is on all the time), `ps-poll` (radio is off between beacons as determined by the access point's DTIM setting). Note that in 'ap' and 'sta+ap' modes the radio is always on, i.e., no power saving is possible. * * Note: esp8266 SDK programmers may be missing an "opmode" option to set the sta/ap/sta+ap operation mode. Please use connect/scan/disconnect/startAP/stopAP, which all set the esp8266 opmode indirectly. + * * @url http://www.espruino.com/Reference#l_Wifi_setConfig */ setConfig: (settings: any) => void; @@ -6470,6 +7768,7 @@ type Modules = { /** * On boards where this is not available, just issue the `connect` commands you need to run at startup from an `onInit` function. + * * Save the current wifi configuration (station and access point) to flash and automatically apply this configuration at boot time, unless `what=="clear"`, in which case the saved configuration is cleared such that wifi remains disabled at boot. The saved configuration includes: * * - mode (off/sta/ap/sta+ap) @@ -6484,6 +7783,7 @@ type Modules = { /** * Restores the saved Wifi configuration from flash. See `Wifi.save()`. + * * @url http://www.espruino.com/Reference#l_Wifi_restore */ restore: () => void; @@ -6497,6 +7797,7 @@ type Modules = { * - mac - The MAC address as string of the form 00:00:00:00:00:00 * * Note that the `ip`, `netmask`, and `gw` fields are omitted if no connection is established: + * * @url http://www.espruino.com/Reference#l_Wifi_getIP */ getIP: (callback: any) => any; @@ -6516,12 +7817,14 @@ type Modules = { /** * Lookup the hostname and invoke a callback with the IP address as integer argument. If the lookup fails, the callback is invoked with a null argument. * **Note:** only a single hostname lookup can be made at a time, concurrent lookups are not supported. + * * @url http://www.espruino.com/Reference#l_Wifi_getHostByName */ getHostByName: (hostname: any, callback: any) => void; /** * Returns the hostname announced to the DHCP server and broadcast via mDNS when connecting to an access point. + * * @url http://www.espruino.com/Reference#l_Wifi_getHostname */ getHostname: (callback: any) => any; @@ -6530,6 +7833,7 @@ type Modules = { * Set the hostname. Depending on implemenation, the hostname is sent with every DHCP request and is broadcast via mDNS. The DHCP hostname may be visible in the access point and may be forwarded into DNS as hostname.local. * If a DHCP lease currently exists changing the hostname will cause a disconnect and reconnect in order to transmit the change to the DHCP server. * The mDNS announcement also includes an announcement for the "espruino" service. + * * @url http://www.espruino.com/Reference#l_Wifi_setHostname */ setHostname: (hostname: any, callback: any) => void; @@ -6537,6 +7841,7 @@ type Modules = { /** * Starts the SNTP (Simple Network Time Protocol) service to keep the clock synchronized with the specified server. Note that the time zone is really just an offset to UTC and doesn't handle daylight savings time. * The interval determines how often the time server is queried and Espruino's time is synchronized. The initial synchronization occurs asynchronously after setSNTP returns. + * * @url http://www.espruino.com/Reference#l_Wifi_setSNTP */ setSNTP: (server: any, tz_offset: any) => void; @@ -6565,6 +7870,7 @@ type Modules = { /** * Issues a ping to the given host, and calls a callback with the time when the ping is received. + * * @url http://www.espruino.com/Reference#l_Wifi_ping */ ping: (hostname: any, callback: any) => void; @@ -6585,52 +7891,64 @@ type Modules = { http: { /** * Create an HTTP Server + * * When a request to the server is made, the callback is called. In the callback you can use the methods on the response (`httpSRs`) to send data. You can also add `request.on('data',function() { ... })` to listen for POSTed data + * * @url http://www.espruino.com/Reference#l_http_createServer */ createServer: (callback: any) => httpSrv; /** * Create an HTTP Request - `end()` must be called on it to complete the operation. `options` is of the form: - *
    `var options = {
    -     *     host: 'example.com', // host name
    -     *     port: 80,            // (optional) port, defaults to 80
    -     *     path: '/',           // path sent to server
    -     *     method: 'GET',       // HTTP command sent to server (must be uppercase 'GET', 'POST', etc)
    -     *     protocol: 'http:',   // optional protocol - https: or http:
    -     *     headers: { key : value, key : value } // (optional) HTTP headers
    +     *
    +     * ```
    +     * var options = {
    +     *     host: 'example.com', // host name
    +     *     port: 80,            // (optional) port, defaults to 80
    +     *     path: '/',           // path sent to server
    +     *     method: 'GET',       // HTTP command sent to server (must be uppercase 'GET', 'POST', etc)
    +     *     protocol: 'http:',   // optional protocol - https: or http:
    +     *     headers: { key : value, key : value } // (optional) HTTP headers
          *   };
    -     * var req = require("http").request(options, function(res) {
    -     *   res.on('data', function(data) {
    -     *     console.log("HTTP> "+data);
    +     * var req = require("http").request(options, function(res) {
    +     *   res.on('data', function(data) {
    +     *     console.log("HTTP> "+data);
          *   });
    -     *   res.on('close', function(data) {
    -     *     console.log("Connection closed");
    +     *   res.on('close', function(data) {
    +     *     console.log("Connection closed");
          *   });
          * });
    -     * // You can req.write(...) here if your request requires data to be sent.
    -     * req.end(); // called to finish the HTTP request and get the response
    -     * `
    + * // You can req.write(...) here if your request requires data to be sent. + * req.end(); // called to finish the HTTP request and get the response + * ``` + * * You can easily pre-populate `options` from a URL using `var options = url.parse("http://www.example.com/foo.html")` + * * There's an example of using [`http.request` for HTTP POST here](https://espruino.com//Internet#http-post) + * * **Note:** if TLS/HTTPS is enabled, options can have `ca`, `key` and `cert` fields. See `tls.connect` for * more information about these and how to use them. + * * @url http://www.espruino.com/Reference#l_http_request */ request: (options: any, callback: any) => httpCRq; /** * Request a webpage over HTTP - a convenience function for `http.request()` that makes sure the HTTP command is 'GET', and that calls `end` automatically. - *
    `require("http").get("http://pur3.co.uk/hello.txt", function(res) {
    -     *   res.on('data', function(data) {
    -     *     console.log("HTTP> "+data);
    +     *
    +     * ```
    +     * require("http").get("http://pur3.co.uk/hello.txt", function(res) {
    +     *   res.on('data', function(data) {
    +     *     console.log("HTTP> "+data);
          *   });
    -     *   res.on('close', function(data) {
    -     *     console.log("Connection closed");
    +     *   res.on('close', function(data) {
    +     *     console.log("Connection closed");
          *   });
          * });
    -     * `
    + * ``` + * * See `http.request()` and [the Internet page](https://espruino.com//Internet) and ` for more usage examples. + * * @url http://www.espruino.com/Reference#l_http_get */ get: (options: any, callback: any) => httpCRq; @@ -6639,34 +7957,44 @@ type Modules = { tv: { /** * This initialises the TV output. Options for PAL are as follows: - *
    `var g = require('tv').setup({ type : "pal",
    -     *   video : A7, // Pin - SPI MOSI Pin for Video output (MUST BE SPI1)
    -     *   sync : A6, // Pin - Timer pin to use for video sync
    -     *   width : 384,
    -     *   height : 270, // max 270
    +     *
    +     * ```
    +     * var g = require('tv').setup({ type : "pal",
    +     *   video : A7, // Pin - SPI MOSI Pin for Video output (MUST BE SPI1)
    +     *   sync : A6, // Pin - Timer pin to use for video sync
    +     *   width : 384,
    +     *   height : 270, // max 270
          * });
    -     * `
    + * ``` + * * and for VGA: - *
    `var g = require('tv').setup({ type : "vga",
    -     *   video : A7, // Pin - SPI MOSI Pin for Video output (MUST BE SPI1)
    -     *   hsync : A6, // Pin - Timer pin to use for video sync
    -     *   vsync : A5, // Pin - pin to use for video sync
    -     *   width : 220,
    -     *   height : 240,
    -     *   repeat : 2, // amount of times to repeat each line
    +     *
    +     * ```
    +     * var g = require('tv').setup({ type : "vga",
    +     *   video : A7, // Pin - SPI MOSI Pin for Video output (MUST BE SPI1)
    +     *   hsync : A6, // Pin - Timer pin to use for video sync
    +     *   vsync : A5, // Pin - pin to use for video sync
    +     *   width : 220,
    +     *   height : 240,
    +     *   repeat : 2, // amount of times to repeat each line
          * });
    -     * `
    + * ``` + * * or - *
    `var g = require('tv').setup({ type : "vga",
    -     *   video : A7, // Pin - SPI MOSI Pin for Video output (MUST BE SPI1)
    -     *   hsync : A6, // Pin - Timer pin to use for video sync
    -     *   vsync : A5, // Pin - pin to use for video sync
    -     *   width : 220,
    -     *   height : 480,
    -     *   repeat : 1, // amount of times to repeat each line
    +     *
    +     * ```
    +     * var g = require('tv').setup({ type : "vga",
    +     *   video : A7, // Pin - SPI MOSI Pin for Video output (MUST BE SPI1)
    +     *   hsync : A6, // Pin - Timer pin to use for video sync
    +     *   vsync : A5, // Pin - pin to use for video sync
    +     *   width : 220,
    +     *   height : 480,
    +     *   repeat : 1, // amount of times to repeat each line
          * });
    -     * `
    + * ``` + * * See the [Television](https://espruino.com//Television) page for more information. + * * @url http://www.espruino.com/Reference#l_tv_setup */ setup: (options: any, width: number) => any; @@ -6688,25 +8016,30 @@ type Modules = { /** * Write to a strip of NeoPixel/WS281x/APA104/APA106/SK6812-style LEDs * attached to the given pin. - *
    `// set just one pixel, red, green, blue
    -     * require("neopixel").write(B15, [255,0,0]);
    -     * `
    - *
    `// Produce an animated rainbow over 25 LEDs
    -     * var rgb = new Uint8ClampedArray(25*3);
    -     * var pos = 0;
    -     * function getPattern() {
    +     *
    +     * ```
    +     * // set just one pixel, red, green, blue
    +     * require("neopixel").write(B15, [255,0,0]);
    +     * ```
    +     *
    +     * ```
    +     * // Produce an animated rainbow over 25 LEDs
    +     * var rgb = new Uint8ClampedArray(25*3);
    +     * var pos = 0;
    +     * function getPattern() {
          *   pos++;
    -     *   for (var i=0;ilength;) {
    -     *     rgb[i++] = (1 + Math.sin((i+pos)*0.1324)) * 127;
    -     *     rgb[i++] = (1 + Math.sin((i+pos)*0.1654)) * 127;
    -     *     rgb[i++] = (1 + Math.sin((i+pos)*0.1)) * 127;
    +     *   for (var i=0;ireturn rgb;
    +     *   return rgb;
          * }
    -     * setInterval(function() {
    -     *   require("neopixel").write(B15, getPattern());
    -     * }, 100);
    -     * `
    + * setInterval(function() { + * require("neopixel").write(B15, getPattern()); + * }, 100); + * ``` + * * **Note:** * * - Different types of LED have the data in different orders - so don't @@ -6729,7 +8062,6 @@ type Modules = { * so you can't do this), or can use a level shifter to shift the voltage up * into the 5v range. * - * * @url http://www.espruino.com/Reference#l_neopixel_write */ write: (pin: Pin, data: any) => void; @@ -6740,14 +8072,17 @@ type Modules = { * Erase the flash storage area. This will remove all files * created with `require("Storage").write(...)` as well * as any code saved with `save()` or `E.setBootCode()`. + * * @url http://www.espruino.com/Reference#l_Storage_eraseAll */ eraseAll: () => void; /** * Erase a single file from the flash storage area. + * * **Note:** This function should be used with normal files, and not * `StorageFile`s created with `require("Storage").open(filename, ...)` + * * @url http://www.espruino.com/Reference#l_Storage_erase */ erase: (name: any) => void; @@ -6755,14 +8090,19 @@ type Modules = { /** * Read a file from the flash storage area that has * been written with `require("Storage").write(...)`. + * * This function returns a memory-mapped String that points to the actual * memory area in read-only memory, so it won't use up RAM. + * * As such you can check if a file exists efficiently using `require("Storage").read(filename)!==undefined`. + * * If you evaluate this string with `eval`, any functions * contained in the String will keep their code stored * in flash memory. + * * **Note:** This function should be used with normal files, and not * `StorageFile`s created with `require("Storage").open(filename, ...)` + * * @url http://www.espruino.com/Reference#l_Storage_read */ read: (name: any, offset: number, length: number) => any; @@ -6771,11 +8111,14 @@ type Modules = { * Read a file from the flash storage area that has * been written with `require("Storage").write(...)`, * and parse JSON in it into a JavaScript object. + * * This is identical to `JSON.parse(require("Storage").read(...))`. * It will throw an exception if the data in the file is not * valid JSON. + * * **Note:** This function should be used with normal files, and not * `StorageFile`s created with `require("Storage").open(filename, ...)` + * * @url http://www.espruino.com/Reference#l_Storage_readJSON */ readJSON: (name: any, noExceptions: boolean) => any; @@ -6784,6 +8127,7 @@ type Modules = { * Read a file from the flash storage area that has * been written with `require("Storage").write(...)`, * and return the raw binary data as an ArrayBuffer. + * * This can be used: * * - In a `DataView` with `new DataView(require("Storage").readArrayBuffer("x"))` @@ -6791,6 +8135,7 @@ type Modules = { * * **Note:** This function should be used with normal files, and not * `StorageFile`s created with `require("Storage").open(filename, ...)` + * * @url http://www.espruino.com/Reference#l_Storage_readArrayBuffer */ readArrayBuffer: (name: any) => any; @@ -6799,8 +8144,10 @@ type Modules = { * Write/create a file in the flash storage area. This is * nonvolatile and will not disappear when the device resets * or power is lost. + * * Simply write `require("Storage").write("MyFile", "Some data")` to write * a new file, and `require("Storage").read("MyFile")` to read it. + * * If you supply: * * - A String, it will be written as-is @@ -6810,21 +8157,27 @@ type Modules = { * * **Note:** If an array is supplied it will not be converted to JSON. * To be explicit about the conversion you can use `Storage.writeJSON` + * * You may also create a file and then populate data later **as long as you * don't try and overwrite data that already exists**. For instance: - *
    `var f = require("Storage");
    -     * f.write("a","Hello",0,14);
    -     * f.write("a"," ",5);
    -     * f.write("a","World!!!",6);
    -     * print(f.read("a")); // "Hello World!!!"
    -     * f.write("a"," ",0); // Writing to location 0 again will cause the file to be re-written
    -     * print(f.read("a")); // " "
    -     * `
    + * + * ``` + * var f = require("Storage"); + * f.write("a","Hello",0,14); + * f.write("a"," ",5); + * f.write("a","World!!!",6); + * print(f.read("a")); // "Hello World!!!" + * f.write("a"," ",0); // Writing to location 0 again will cause the file to be re-written + * print(f.read("a")); // " " + * ``` + * * This can be useful if you've got more data to write than you * have RAM available - for instance the Web IDE uses this method * to write large files into onboard storage. + * * **Note:** This function should be used with normal files, and not * `StorageFile`s created with `require("Storage").open(filename, ...)` + * * @url http://www.espruino.com/Reference#l_Storage_write */ write: (name: any, data: any, offset: number, size: number) => boolean; @@ -6833,30 +8186,39 @@ type Modules = { * Write/create a file in the flash storage area. This is * nonvolatile and will not disappear when the device resets * or power is lost. + * * Simply write `require("Storage").writeJSON("MyFile", [1,2,3])` to write * a new file, and `require("Storage").readJSON("MyFile")` to read it. + * * This is equivalent to: `require("Storage").write(name, JSON.stringify(data))` + * * **Note:** This function should be used with normal files, and not * `StorageFile`s created with `require("Storage").open(filename, ...)` + * * @url http://www.espruino.com/Reference#l_Storage_writeJSON */ writeJSON: (name: any, data: any) => boolean; /** * List all files in the flash storage area. An array of Strings is returned. + * * By default this lists files created by `StorageFile` (`require("Storage").open`) * which have a file number (`"\1"`/`"\2"`/etc) appended to them. - *
    `// All files
    -     * require("Storage").list()
    -     * // Files ending in '.js'
    -     * require("Storage").list(/\.js$/)
    -     * // All Storage Files
    -     * require("Storage").list(undefined, {sf:true})
    -     * // All normal files (eg created with Storage.write)
    -     * require("Storage").list(undefined, {sf:false})
    -     * `
    + * + * ``` + * // All files + * require("Storage").list() + * // Files ending in '.js' + * require("Storage").list(/\.js$/) + * // All Storage Files + * require("Storage").list(undefined, {sf:true}) + * // All normal files (eg created with Storage.write) + * require("Storage").list(undefined, {sf:false}) + * ``` + * * **Note:** This will output system files (eg. saved code) as well as * files that you may have written. + * * @url http://www.espruino.com/Reference#l_Storage_list */ list: (regex: any, filter: any) => any; @@ -6864,17 +8226,22 @@ type Modules = { /** * List all files in the flash storage area matching the specfied regex (ignores StorageFiles), * and then hash their filenames *and* file locations. + * * Identical files may have different hashes (eg. if Storage is compacted and the file moves) but * the changes of different files having the same hash are extremely small. - *
    `// Hash files
    -     * require("Storage").hash()
    -     * // Files ending in '.boot.js'
    -     * require("Storage").hash(/\.boot\.js$/)
    -     * `
    + * + * ``` + * // Hash files + * require("Storage").hash() + * // Files ending in '.boot.js' + * require("Storage").hash(/\.boot\.js$/) + * ``` + * * **Note:** This function is used by Bangle.js as a way to cache files. * For instance the bootloader will add all `.boot.js` files together into * a single `.boot0` file, but it needs to know quickly whether anything has * changed. + * * @url http://www.espruino.com/Reference#l_Storage_hash */ hash: (regex: any) => number; @@ -6885,14 +8252,17 @@ type Modules = { * garbage and moves on to a fresh part of flash memory. Espruino only * fully erases those files when it is running low on flash, or when * `compact` is called. + * * `compact` may fail if there isn't enough RAM free on the stack to * use as swap space, however in this case it will not lose data. + * * **Note:** `compact` rearranges the contents of memory. If code is * referencing that memory (eg. functions that have their code stored in flash) * then they may become garbled when compaction happens. To avoid this, * call `eraseFiles` before uploading data that you intend to reference to * ensure that uploaded files are right at the start of flash and cannot be * compacted further. + * * @url http://www.espruino.com/Reference#l_Storage_compact */ compact: () => void; @@ -6901,6 +8271,7 @@ type Modules = { * This writes information about all blocks in flash * memory to the console - and is only useful for debugging * flash storage. + * * @url http://www.espruino.com/Reference#l_Storage_debug */ debug: () => void; @@ -6910,21 +8281,25 @@ type Modules = { * Storage. Due to fragmentation there may be more * bytes available, but this represents the maximum * size of file that can be written. + * * @url http://www.espruino.com/Reference#l_Storage_getFree */ getFree: () => number; /** * Returns: - *
    `{
    -     *   totalBytes // Amount of bytes in filesystem
    -     *   freeBytes // How many bytes are left at the end of storage?
    -     *   fileBytes // How many bytes of allocated files do we have?
    -     *   fileCount // How many allocated files do we have?
    -     *   trashBytes // How many bytes of trash files do we have?
    -     *   trashCount // How many trash files do we have?
    +     *
    +     * ```
    +     * {
    +     *   totalBytes // Amount of bytes in filesystem
    +     *   freeBytes // How many bytes are left at the end of storage?
    +     *   fileBytes // How many bytes of allocated files do we have?
    +     *   fileCount // How many allocated files do we have?
    +     *   trashBytes // How many bytes of trash files do we have?
    +     *   trashCount // How many trash files do we have?
          * }
    -     * `
    + * ``` + * * @url http://www.espruino.com/Reference#l_Storage_getStats */ getStats: () => any; @@ -6932,6 +8307,7 @@ type Modules = { /** * Writes a lookup table for files into Bangle.js's storage. This allows any file stored * up to that point to be accessed quickly. + * * @url http://www.espruino.com/Reference#l_Storage_optimise */ optimise: () => void; @@ -6939,8 +8315,11 @@ type Modules = { /** * Open a file in the Storage area. This can be used for appending data * (normal read/write operations only write the entire file). + * * Please see `StorageFile` for more information (and examples). + * * **Note:** These files write through immediately - they do not need closing. + * * @url http://www.espruino.com/Reference#l_Storage_open */ open: (name: any, mode: any) => StorageFile; @@ -6949,6 +8328,7 @@ type Modules = { Flash: { /** * Returns the start and length of the flash page containing the given address. + * * @url http://www.espruino.com/Reference#l_Flash_getPage */ getPage: (addr: number) => any; @@ -6956,31 +8336,37 @@ type Modules = { /** * This method returns an array of objects of the form `{addr : #, length : #}`, representing * contiguous areas of flash memory in the chip that are not used for anything. + * * The memory areas returned are on page boundaries. This means that you can * safely erase the page containing any address here, and you won't risk * deleting part of the Espruino firmware. + * * @url http://www.espruino.com/Reference#l_Flash_getFree */ getFree: () => any; /** * Erase a page of flash memory + * * @url http://www.espruino.com/Reference#l_Flash_erasePage */ erasePage: (addr: any) => void; /** * Write data into memory at the given address + * * In flash memory you may only turn bits that are 1 into bits that are 0. If * you're writing data into an area that you have already written (so `read` * doesn't return all `0xFF`) you'll need to call `erasePage` to clear the * entire page. + * * @url http://www.espruino.com/Reference#l_Flash_write */ write: (data: any, addr: number) => void; /** * Read flash memory from the given address + * * @url http://www.espruino.com/Reference#l_Flash_read */ read: (length: number, addr: number) => any;