LTE Beacon: Micro-app API reference [0.2.19]
Micro-apps are written in JavaScript. All of ECMAScript 5.1 is supported. Select things from ECMAScript 2015 (also known as the “6th edition”, or “ECMAScript 6”) are also supported:
- arrow functions
- classes
- enhanced object literals (shorthands & computed/dynamic property names)
- default function arguments
- template literals
- promises
-
ArrayBuffer
and typed arrays -
DataView
,Map
,Set
Object.keys
Some notably-not-supported ES2015 features:
-
let
andconst
- destructuring
- spread and rest
...
operators - iterators and
for ... of
-
Object.values
and.entries
- (and more)
None of ES2016 and beyond is supported at this time, most notable ommision being async
and await
.
API includes some additional helper function added to standard objects:
-
ArrayBuffer.prototype.toJSON()
- convertsArrayBuffer
to hexadecimal string. Used byJSON.stringify()
-
ArrayBuffer.prototype.toHexString()
- convertsArrayBuffer
to hexadecimal string -
ArrayBuffer.prototype.toRawString()
- convertsArrayBuffer
to ASCII string -
ArrayBuffer.prototype.toArray()
- convertsArrayBuffer
to array of numbers -
String.prototype.toHexArray()
- converts hexadecimal string into array of numbers from 0 to 255 -
String.prototype.toHexArrayBuffer()
- converts hexadecimal string intoArrayBuffer
-
String.prototype.toArrayBuffer()
- converts ASCII string intoArrayBuffer
-
Array.prototype.toHexString()
- converts array of numbers from 0 to 255 into hexadecimal string -
Array.prototype.toArrayBuffer()
- converts array of numbers from 0 to 255 intoArrayBuffer
Other than that, here’s a list of LTE-Beacon–specific functions and APIs.
Valid for firmware 0.2.19. See API reference for other firmware versions.
- Global functions
- Timer functions
- Bluetooth Low Energy functions
- Creating BLE packets
- Input/Output
- Audio
- IMU
- Battery
- Temperature
- Cloud communication
- Data synchronisation
- Storage
- Location
- UWB Ranging
- System
- Modem
- Application
- Cryptographic functions
- NFC
microApp API Reference
Global functions
print(...)
Description: Prints message on debug console. You can enter many arguments that will be space separated. Objects will be converted to string using JSON.stringify
.
Note: This is a blocking function when connected via Bluetooth. It may slow down application.
Arguments:
- text (stringable, max length: 1024) - Text that will be displayed on console. It might be truncated when it will be longer than max length.
preview
preview(data)
Description: Sends data to visualisation console.
Note: This is a blocking function when connected via Bluetooth. It may slow down application.
Arguments:
- data (object) - Data to be visualised
Errors thrown:
toHex
toHex(array)
Description: Converts arraybuffer/array of numbers to hex string
Arguments:
- array (object) - Array of numbers or
ArrayBuffer
that will be converted to hex string.
Returns: object
toMs
toMs(interval)
Description: Converts string time description to milliseconds
Arguments:
- interval (interval, unit: ms) - String representation of time interval
Invocation example:
print(toMs("30s")+"ms"); // This should print 30000ms
Returns: number
toSec
toSec(interval)
Description: Converts string time description to seconds
Arguments:
- interval (interval, unit: s) - String representation of time interval
Invocation example:
print(toSec("1h")+"s"); // This should print 3600s
Returns: number
Timer functions
Timer functions that allow to schedule tasks asynchronously
single
timers.single(interval, callback)
Description: Start single shot timer
Arguments:
- interval (interval, unit: ms) - Number of milliseconds that timer will wait before invoking callback
-
callback (function, optional) - Callback function that will be called when timer fires
Function signature:
() => ...
Returns: handle object
Handler object methods:
-
handler.stop() - Stops timer. Calling on stoped timer has no effect.
-
handler.end() - Return promise called after timer finishes.
-
handler.reset(interval) - Resets timer. Calling on stoped timer will schedule it again.
- interval (interval, unit: ms, default: 0, optional) - New interval in milliseconds. If ommited (or 0) previous interval will be used.
Errors thrown:
- ESR0004 Not enough resources
repeat
timers.repeat(interval, callback)
Description: Start repeated timer.
Arguments:
- interval (interval, unit: ms) - Number of milliseconds that timer will wait before invoking callback
-
callback (function) - Callback function that will be called when timer fires
Function signature:
() => ...
Invocation example:
// Blink LEDs every 200ms
var on = false;
timers.repeat('200ms', () => io.led(on = !on))
Returns: handle object
Handler object methods:
-
handler.stop() - Stops timer. Calling on stopped timer will have no effect.
-
handler.restart(interval) - Restarts repeated timer. Works only on stopped timer.
- interval (interval, unit: ms, default: 0, optional) - New interval in milliseconds. If ommited (or 0) previous interval will be used.
Errors thrown:
- ESR0004 Not enough resources
at
timers.at(timestamp, callback)
Description: Invoke timer at specified UTC time.
Arguments:
- timestamp (any) - UTC time in milliseconds or
Date
object -
callback (function) - Callback function that will be called when timer fires.
Function signature:
() => ...
Returns: handle object
Handler object methods:
- handler.stop() - Stops timer. Calling on stopped timer will have no effect.
Errors thrown:
- ESR0004 Not enough resources
count
timers.count(interval, count, callback)
Description: Invoke timer number of times in specified interval
Arguments:
- interval (interval, unit: ms) - Number of milliseconds that timer will wait before invoking callback
- count (number, min: 0) - Number of timers timer will be called.
-
callback (function) - Callback function that will be called when timer fires.
Function signature:
(count) => ...
- count (number) - Current count number (counting down to 0)
Invocation example:
// Blink LEDs 5 times every 200ms
timers.count('200ms', 5, (count) => io.led(count % 2 == 1))
Returns: handle object
Handler object methods:
-
handler.stop() - Stops timer. Calling on stopped timer will have no effect.
-
handler.end() - Return promise called after timer finishes.
Errors thrown:
- ESR0004 Not enough resources
Bluetooth Low Energy functions
Bluetooth Low Energy scanning and advertising functions
advertise
Variant 1:
ble.advertise(callback)
Description: This variant will call given function that will provide BLE packet that will be advertised. It allows to advertise packet that change dynamically during time: for example broadcast current temperature. Default advertising parameters are transmit power -4dBm and 500ms interval.
Arguments:
-
callback (function) - Callback function that will provide packet each time it will be advertised. Returned object has to have similar structure to scan records received by
ble.startScan(...)
function.Function signature:
(txPower) => ...
- txPower (number, since: 0.0.8) - Transmit power used to send this advertisement for convinient adjusting measured power.
Invocation example:
// Advertise device with temperature in its name.
//Note that extra braces around arrow function body are necessary.
ble.advertise(() => ({name: "Temp=" + sensors.temp.get().toFixed(1)}))
Variant 2:
ble.advertise(data)
Description: This variant will advertise statically defined packet (its content does not change). Default advertising parameters are transmit power -4dBm and 500ms interval.
Arguments:
- data (object) - Packet that will be advertised. Similar to the structure of scan records received by
ble.startScan(...)
function.
Invocation example:
//Advertise device that has only a name
//Notes that you can chain handler function invocations together.
ble.advertise({name: "MyDevice"}).power(4).interval(300)
Returns: handle object
Handler object methods:
-
handler.stop() - Stops advertiser
-
handler.pause() - Pauses advertiser. On stopped advertiser is does nothing.
-
handler.resume() - Resumes advertiser. On stopped advertiser is does nothing.
-
handler.interval(interval) - Sets new advertising interval. Shorter interval - more power is consumed. Longer interval - more difficult to quickly detect. If this function is not used default interval is 500ms.
- interval (interval, unit: ms, min: 100) - Interval in milliseconds
-
handler.power(power) - Sets new advertising power (in dBm).
- power (number, unit: dBm, min: -40, max: 20) - Power in dBm. Allowed values are -40, -20, -16, -12, -8, -4, 0, 4, 8, 20.
If different value is passed, advertising power will set to highest valid value lower than the value given (eg. 7 will snap to 4).
If this function is not used default advertising power is -4dBm
- power (number, unit: dBm, min: -40, max: 20) - Power in dBm. Allowed values are -40, -20, -16, -12, -8, -4, 0, 4, 8, 20.
Errors thrown:
- ESR0004 Not enough resources
startScan
ble.startScan(callback, duration, options)
Description: Start scanning session for BLE packets. It returns promise that will be resolved when scan stops (either from timeout or ble.stopScan(...)
).
Arguments:
-
callback (function) - Callback function that will be called when new packet is detected.
Using blocking functions (likeprint
) in this callback may slow down scanning and miss some packets. Note that in the example packet is only printed out when it was succesfully recognized as Estimote Location to minimize blocking byprint
.Function signature:
(scanRecord) => ...
- scanRecord (object) - Raw BLE advertising packet.
Object fields:
- rssi (number, unit: dBm) - Received packet signal strength (RSSI)
- channel (number, since: 0.0.8) - Channel number (37,38,39) on which packet was received
- scanResponse (bool, since: 0.0.9) - ‘true’ if received packet is a scan response
- connectable (bool, since: 0.0.9) - ‘true’ if received packet is connectable
- addr (arraybuffer) - MAC device address
- name (string, optional) - Device advertised name
- manufData (arraybuffer, optional) - Manufacturers data
- serviceData (object, optional) - Service data map. Key (service UUID) is a string, value is an arraybuffer.
- serviceUUIDs (array, optional) - Array of arraybuffers with UUIDs of services.
- txPower (number, unit: dBm, optional) - Advertised transmit power
- flags (number, optional) - Advertised packet flags
- raw (arraybuffer, optional, since: 0.2.7) - Raw advertising packet. This ArrayBuffer is only valid inside callback function.
Example:
{ rssi : -67, channel : 37, scanResponse : false, connectable : true, addr : feab1214112c, name : "MyDevice", manufData : fe34567689, serviceData : {"fe9a" : "fe124566783234534"}, serviceUUIDs : ["fe9a"], txPower : 4, flags : 2 }
- duration (interval, unit: ms, default: 10000, optional) - Scan duration. 0 if there is no time limit. Default value is 10000ms (10s).
-
options (object, optional, since: 0.2.4) - Advanced scan options
Object fields:
- passive (bool, default: false, optional) - Passive scan without sending scan requests. There will be no scan responses received.
Enabling this option might be helpful to get better packet rate especially when advertising at the same time. - scanRequests (bool, default: false, optional) - Return also scan requests received from other active scanning BLE devices. Works only when Bluetooth is disconnected.
- interval (interval, unit: ms, min: 1, max: 10240, default: 150, optional) - Scan interval - how often scan cycle will be started
- window (interval, unit: ms, min: 1, max: 10240, default: 100, optional) - Scan window - how long it will scan after cycle is started
- channels (array, default: [37,38,39], optional, since: 0.2.5) - Scan channels list channels. Only valid ones are 37, 38, 39. List cannot be empty.
- deduplicate (bool, default: false, optional) - Remove duplicated scan records (using MAC address). Only one packet with given MAC address will be received in scan session (
startScan
restarts session).
Example:
{ passive : false, scanRequests : false, interval : "150ms", window : "100ms", channels : [37,38,39], deduplicate : false }
- passive (bool, default: false, optional) - Passive scan without sending scan requests. There will be no scan responses received.
Returns: promise
parse
ble.parse(scanRecord)
Description: Parses scanned raw BLE advertisement and extracts data. It can recognize most common packets like iBeacon or Eddystone and Estimote.
Arguments:
- scanRecord (object) - Raw BLE packet scanned provided by startScan callback
Invocation example:
ble.startScan((scanRecord) => {
var packet = ble.parse(scanRecord);
if(packet) {
print(JSON.stringify(packet));
}
})
Returns: object
stopScan
ble.stopScan(resolvePromise)
Description: Stops BLE scanning immediately.
Arguments:
- resolvePromise (bool, default: true, optional) - If true then the startScan promise will be resolved
Invocation example:
ble.stopScan(true)
Creating BLE packets
Builders that will construct most popular packets like iBeacon, Eddystone or Estimote proprietary
eddystoneUrl
ble.build.eddystoneUrl(url, measuredPower)
Description: Builds EddystoneURL packet
Arguments:
- url (string, max length: 50) - URL to be advertised
- measuredPower (number, unit: dBm, min: -127, max: 127, default: -20, optional) - Measured power in dBm (measured at 0m)
Invocation example:
ble.build.eddystoneUrl("https://estimote.com", -20)
Returns: object
eddystoneTlm
ble.build.eddystoneTlm()
Description: Builds single EddystoneTLM packet. Since it generates single packet you need to pass whole function to ble.advertise to make packet change over time.
Invocation example:
ble.advertise(ble.build.eddystoneTlm)
Returns: object
eddystoneUid
ble.build.eddystoneUid(namespace, instance, measuredPower)
Description: Builds EddystoneUID packet
Arguments:
- namespace (arraybuffer, max length: 10) - ArrayBuffer or hex string with namespace ID (10 bytes)
- instance (arraybuffer, max length: 6) - ArrayBuffer or hex string with instance ID (6 bytes)
- measuredPower (number, unit: dBm, min: -127, max: 127, default: -20, optional) - Measured power in dBm (measured at 0m)
Invocation example:
ble.build.eddystoneUid("123456789ABCDEF01234", "349012AEB2E3", -20)
Returns: object
iBeacon
ble.build.iBeacon(uuid, major, minor, measuredPower)
Description: Builds iBeacon packet
Arguments:
- uuid (arraybuffer, max length: 16) - ArrayBuffer or hex string with UUID
- major (number, min: 1, max: 65535) - iBeacon major number from 1 to 65535
- minor (number, min: 1, max: 65535) - iBeacon minor number from 1 to 65535
- measuredPower (number, unit: dBm, min: -127, max: 127, default: -50, optional) - Measured power in dBm (measured at 1m)
Invocation example:
ble.build.iBeacon("123e4567-e89b-12d3-a456-426655440000", 1024, 512, -50)
Returns: object
altBeacon
ble.build.altBeacon(id, manufacturerId, measuredPower, reserved)
Description: Builds AltBeacon packet
Arguments:
- id (arraybuffer, max length: 20) - ArrayBuffer or hex string with beacon ID. At least 16 bytes long but no longer than 20 bytes
- manufacturerId (number, min: 1, max: 65535) - Manufacturer ID
- measuredPower (number, unit: dBm, min: -127, max: 127, default: -50, optional) - Measured power in dBm (measured at 1m)
- reserved (number, min: 0, max: 256, default: 0, optional) - Reserved value
Invocation example:
ble.build.altBeacon("123e4567-e89b-12d3-a456-426655440000", 1024, -50, 0)
Returns: object
estimoteLocation
ble.build.estimoteLocation(measuredPower)
Description: Builds Estimote Location packet
Arguments:
- measuredPower (number, unit: dBm, min: -127, max: 127, default: -50, optional) - Measured power in dBm (measured at 1m)
Invocation example:
ble.build.estimoteLocation(-50)
Returns: object
estimoteLocationTrigger
ble.build.estimoteLocationTrigger(measuredPower)
Description: Builds Estimote Location trigger packet. It should be advertised with 100ms and -4 dBm txPower.
Arguments:
- measuredPower (number, unit: dBm, min: -127, max: 127, default: -50, optional) - Measured power in dBm (measured at 1m)
Invocation example:
ble.build.estimoteLocationTrigger(-50)
Returns: object
estimoteTelemetry
ble.build.estimoteTelemetry()
Description: Builds single Estimote Telemetry packet. Since it generates single packet you need to pass whole function to ble.advertise(...)
to make packet change over time.
Invocation example:
ble.advertise(ble.build.estimoteTelemetry)
Returns: object
estimoteNearable
ble.build.estimoteNearable()
Description: Builds single Estimote Nearable packet. Since it generates single packet you need to pass whole function to ble.advertise(...)
to make packet change over time.
Since: 0.2.4
Invocation example:
ble.advertise(ble.build.estimoteNearable)
Returns: object
Input/Output
led
Variant 1:
io.led(id, state)
Description: Sets LED on or off. Controls only LEDs in the main ring. Side LEDs are controlled by the system.
Arguments:
- id (number) - LED number or RGB segment enum. On some hardwares it may light up whole LED segment.
Invalid LED number will cause no effect (no error will be thrown).-
io.Led.LTE = 100 → LTE side LEDs
-
io.Led.GPS = 101 → GPS side LEDs
-
io.Led.BLE = 102 → BLE side LEDs
-
- state (bool) - Set true to turn on LED
Invocation example:
io.led(1, true); // Turns on second LED on AI beacon and second segment on LTE beacon
io.led(io.Led.BLE); // Turns whole BLE side LED segment on AI and LTE beacons
Variant 2:
io.led(state)
Description: Turn on or off all LEDs (on the ring)
Arguments:
- state (bool) - Set true to turn on all LEDs (on the ring)
Invocation example:
io.led(true)
setLedColor
Variant 1:
io.setLedColor(id, color)
Description: Sets LED RGB color. Controls only LEDs in the main ring. Side LEDs are controlled by the system.
Arguments:
- id (number) - LED number or RGB segment enum. On some hardwares it may light up whole LED segment.
Invalid LED number will cause no effect (no error will be thrown).-
io.Led.LTE = 100 → LTE side LEDs
-
io.Led.GPS = 101 → GPS side LEDs
-
io.Led.BLE = 102 → BLE side LEDs
-
- color (array) - Array containing three numbers for red, green and blue colors from 0.0 to 1.0 (max ilumination). Predefined set of colors can be found in enum
io.Color
-
io.Color.RED = [1, 0, 0] → Red color
-
io.Color.GREEN = [0, 1, 0] → Green color
-
io.Color.BLUE = [0, 0, 1] → Blue color
-
io.Color.YELLOW = [1, 1, 0] → Yellow color
-
io.Color.WHITE = [1, 1, 1] → White color
-
io.Color.CYAN = [0, 1, 1] → Cyan color
-
io.Color.MAGENTA = [1, 0, 1] → Magenta color
-
io.Color.ORANGE = [0.99, 0.41, 0.002] → Orange color
-
Invocation example:
io.setLedColor(1, [0.5, 0.0, 1.0])
Variant 2:
io.setLedColor(id, htmlColor)
Warning: This is a deprecated API and it is subject to change.
Description: Sets LED RGB color. Controls only LEDs in the main ring. Side LEDs are controlled by the system.
Arguments:
- id (number) - LED number or RGB segment enum. On some hardwares it may light up whole LED segment.
Invalid LED number will cause no effect (no error will be thrown).-
io.Led.LTE = 100 → LTE side LEDs
-
io.Led.GPS = 101 → GPS side LEDs
-
io.Led.BLE = 102 → BLE side LEDs
-
- htmlColor (string, max length: 20) - HTML style color description.
Invocation example:
io.setLedColor(1, "#FF77EB")
Variant 3:
io.setLedColor(color)
Description: Sets RGB color for all LEDs (on the ring)
Arguments:
- color (array) - Array containing three numbers for red, green and blue colors from 0.0 to 1.0 (max ilumination). Predefined set of colors can be found in enum
io.Color
Invocation example:
io.setLedColor([0.5, 0.0, 1.0])
Variant 4:
io.setLedColor(htmlColor)
Warning: This is a deprecated API and it is subject to change.
Description: Sets RGB color for all LEDs (on the ring)
Arguments:
- htmlColor (string, max length: 20) - HTML style color description.
Invocation example:
io.setLedColor("#FF77EB")
setLedBrightness
Variant 1:
io.setLedBrightness(id, brightness)
Description: Sets LED brightness. Controls only LEDs in the main ring. Side LEDs are controlled by the system.
Arguments:
- id (number) - LED number or RGB segment enum. On some hardwares it may light up whole LED segment.
Invalid LED number will cause no effect (no error will be thrown).-
io.Led.LTE = 100 → LTE side LEDs
-
io.Led.GPS = 101 → GPS side LEDs
-
io.Led.BLE = 102 → BLE side LEDs
-
- brightness (number) - Number from 0 to 1.0 with LED brightness.
Invocation example:
io.setLedBrightness(1, 0.5)
Variant 2:
io.setLedBrightness(brightness)
Description: Sets brightness for all LEDs (on the ring)
Arguments:
- brightness (number) - Number from 0 to 1.0 with LED brightness.
Invocation example:
io.setLedBrightness(0.5)
getMaxLeds
io.getMaxLeds()
Description: Gets number of RGB LEDs available that can be controlled individually. Useful when running code on different hardware revisions.
Invocation example:
// Spinner
var i =0;
timers.repeat('300ms', () => {
io.led(i, false);
i = (i + 1) % io.getMaxLeds();
io.led(i, true);
});
Returns: number
press
Variant 1:
io.press(callback, pressType)
Description: Listen for button press. You can assign different callback to each press type (long, short, very long).
Assigning two callbacks to the same pressType
will replace previous one. Passing null
as callback function will unregister previous callback.
Arguments:
-
callback (function) - Function called when button is pressed. Passing
null
will unregister current callback.Function signature:
() => ...
-
pressType (number, default: 0, optional) - Button press type
-
io.PressType.SHORT = 0 → Single, short press, less than 1 second
-
io.PressType.LONG = 1 → Long press, more than 3 seconds
-
io.PressType.VERY_LONG = 2 → Very long press, more than 5s
-
io.PressType.DOUBLE = 3 → Double press shorter than 500ms
-
io.PressType.TRIPLE = 4 → Triple press shorter than 1s
-
Invocation example:
io.press(() => print("short press"), io.PressType.SHORT)
io.press(() => print("long press"), io.PressType.LONG)
Variant 2:
io.press(buttonId, callback, pressType)
Description: Listen for button press. You can assign different callback to each press type (long, short, very long).
Assigning two callbacks to the same pressType
will replace previous one. Passing null
as callback function will unregister previous callback.
Arguments:
- buttonId (number, default: 0) - Button type
-
io.Button.MAIN = 0 → Main button
-
io.Button.SIDE = 1 → Side button (when available)
-
-
callback (function) - Function called when button is pressed. Passing
null
will unregister current callback.Function signature:
() => ...
- pressType (number, default: 0, optional) - Button press type
-
io.PressType.SHORT = 0 → Single, short press, less than 1 second
-
io.PressType.LONG = 1 → Long press, more than 3 seconds
-
io.PressType.VERY_LONG = 2 → Very long press, more than 5s
-
io.PressType.DOUBLE = 3 → Double press shorter than 500ms
-
io.PressType.TRIPLE = 4 → Triple press shorter than 1s
-
Invocation example:
io.press(io.Button.MAIN, () => print("short press"), io.PressType.SHORT)
io.press(io.Button.MAIN, () => print("long press"), io.PressType.LONG)
onRawPress
io.onRawPress(callback)
Description: Listen for main button state change. It only reports if button was pressed or released, no debouncing here. It can be used to construct more complicated button press patterns.
Arguments:
-
callback (function) - Function called when button state is changed. Passing
null
will unregister callback.Function signature:
(state) => ...
- state (bool) -
true
if button is pressed down.
- state (bool) -
Invocation example:
io.onRawPress((state) => print("state=" + state))
setVibration
Note: This function might not be available on all hardware revisions.
io.setVibration(value, duration, power)
Description: Turns vibration on or off. Vibration might not be available on all hardware versions. Returned promise will always be resolved (not rejected) when vibration stops. You can use it to chain together several invocations to create vibration pattern.
Arguments:
- value (bool) - True to turn vibration on, false to turn it off. If it is
false
you can skip other agruments. - duration (interval, unit: ms, max: 30000, default: 0, optional) - Duration of vibration when turning on. Max. 30s
- power (number, min: 0.0, max: 1.0, default: 1.0, optional, since: 0.2.15) - Number from 0 to 1.0 with power. Power 0 means vibration is the weakest, but not stopped.
Invocation example:
io.setVibration(true, "3s", 0.5)
Returns: promise
Audio
Audio functions
Note: This API might not be available on all hardware revisions.
buzzer
io.audio.buzzer(value, duration, frequency)
Description: Turns single tone buzzer on or off. Returned promise will always be resolved (not rejected) when buzzer stops. You can use it to chain together several subsequent tones to create a melody.
Arguments:
- value (bool) -
true
to turn buzzer on,false
to turn it off - duration (interval, unit: ms, max: 30000, default: 0, optional) - Duration of sound. Max. 30s
- frequency (number, unit: hz, min: 100, max: 20000, default: 4000, optional) - Buzzer frequency. Default value is it’s resonant frequency giving strongest sound.
Invocation example:
io.audio.buzzer(true, "3s", 4000)
Returns: promise
play
Note: This function might not be available on all hardware revisions.
io.audio.play(sample, options)
Description: Plays audio sample. Audio playback might not be available on all hardware versions. Returned promise will always be resolved (not rejected) when audio stops. You can use it to chain together several tones to create a melody.
Arguments:
- sample (object) - Audio sample to play. Currently supported is only
ArrayBuffer
with 8-bit samples. -
options (object, optional) - Audio playback options.
Object fields:
- loop (number, default: 1, optional) - Number of times audio sample is played. 0 is continous playback. Default is 1.
- duration (interval, unit: ms, max: 1800000, default: 30000, optional) - Maximum playback time, even when looping.
- sampleRate (number, unit: hz, min: 4000, max: 50000, default: 8000, optional) - Sample rate in Hz.
Example:
{ loop : 2, duration : "3s", sampleRate : 8000 }
Returns: promise
setVolume
io.audio.setVolume(volume)
Description: Sets audio volume even during playback.
Arguments:
- volume (number) - Number from 0 to 1.0 with relative volume.
Invocation example:
io.audio.setVolume(0.5)
IMU
Inertial Measurement Unit (IMU) functions
Note: This API might not be available on all hardware revisions.
getAccel
sensors.imu.getAccel()
Description: Returns acceleration vector in G. Will return all zeros on hardware that does not support it.
Returns: object
Object fields:
- x (number, unit: g) - Accelertion value in X axis
- y (number, unit: g) - Accelertion value in Y axis
- z (number, unit: g) - Accelertion value in Z axis
Example:
{
x : 0.514,
y : 0.00134,
z : 0.9878
}
getGyro
sensors.imu.getGyro()
Description: Returns rotation rate vector in deg/s. AI Beacon only. Will return all zeros on hardware that does not support it.
Returns: object
Object fields:
- x (number, unit: g) - Rotation rate in X axis
- y (number, unit: g) - Rotation rate in Y axis
- z (number, unit: g) - Rotation rate in Z axis
Example:
{
x : 0.514,
y : 0.00134,
z : 0.9878
}
getOrient
sensors.imu.getOrient()
Description: Returns device orientation in more human readable form
Returns: object
Object fields:
- orient (string, optional) - Device orientation - flat or vertical
- side (string, optional) - Device side that is pointing up - top, bottm ble, gnss, cloud
Example:
{
orient : "flat",
side : "top"
}
setSens
sensors.imu.setSens(level)
Description: Sets sensitivity
Arguments:
- level (number) - Sets accelerometer sensitivity level
-
sensors.imu.Level.LOWEST = 0 → Lowest level
-
sensors.imu.Level.LOW = 1 → Low level
-
sensors.imu.Level.MEDIUM = 2 → Medium level
-
sensors.imu.Level.HIGH = 3 → High level
-
sensors.imu.Level.HIGHEST = 4 → Highest level
-
Invocation example:
sensors.imu.setSens(sensors.imu.Level.MEDIUM)
Returns: undefined
setResp
sensors.imu.setResp(level)
Description: Sets sensitivity
Arguments:
- level (number) - Sets accelerometer responsivness level
-
sensors.imu.Level.LOWEST = 0 → Lowest level
-
sensors.imu.Level.LOW = 1 → Low level
-
sensors.imu.Level.MEDIUM = 2 → Medium level
-
sensors.imu.Level.HIGH = 3 → High level
-
sensors.imu.Level.HIGHEST = 4 → Highest level
-
Invocation example:
sensors.imu.setResp(sensors.imu.Level.MEDIUM)
Returns: undefined
setRange
sensors.imu.setRange(range)
Description: Sets acceleration range.
Arguments:
- range (number) - Sets accelerometer range
-
sensors.imu.Range.RANGE_2G = 0 → ± 2g
-
sensors.imu.Range.RANGE_4G = 1 → ± 4g
-
sensors.imu.Range.RANGE_8G = 2 → ± 8g
-
sensors.imu.Range.RANGE_16G = 3 → ± 16g
-
Invocation example:
sensors.imu.setRange(sensors.imu.Range.RANGE_2G)
Returns: undefined
onMotion
Variant 1:
sensors.imu.onMotion(callback)
Description: Invokes callback function when device is in motion
Arguments:
-
callback (function) - Callback function that will be called when motion is detected. Passing
null
will unregister previous callback.Function signature:
(motion) => ...
- motion (bool) - True if device is in motion
Invocation example:
sensors.imu.onMotion((motion) => {
print(`Is moving: ${motion}`)
})
Variant 2:
sensors.imu.onMotion(eventType, callback, options)
Description: Invokes callback function when device is in motion
Arguments:
- eventType (number) - Event type. Some events might not be supported on all hardware revisions. If event type is not supported function will throw an exception.
-
sensors.imu.MotionEvent.GENERIC = 0 → Generic motion
-
sensors.imu.MotionEvent.FREE_FALL = 1 → Free fall
-
sensors.imu.MotionEvent.SINGLE_TAP = 2 → Single tap
-
sensors.imu.MotionEvent.DOUBLE_TAP = 3 → Double tap
-
sensors.imu.MotionEvent.TILT = 4 → Tilt
-
sensors.imu.MotionEvent.STEP = 5 → Step
-
sensors.imu.MotionEvent.ORIENTATION = 6 → Orientation change
-
sensors.imu.MotionEvent.WAKE_UP = 7 → Wake up
-
sensors.imu.MotionEvent.MLC = 8 → Events from Machine Learning Core
-
-
callback (function) - Callback function that will be called for different kinds of motion events. Set of supported events is dependent on hardware revision. Passing
null
will unregister callback for particular event type.Function signature:
(eventData) => ...
- eventData (object) - Event data that depends on event type
- options (object, optional) - Additional options, different for each motion event type.
Returns: undefined
Errors thrown:
- ESR0003 Unsupported feature.
- ESR1801 Unsupported event: {event_code}
- ESR1802 Bad event options
- ESR1803 Internal sensor error
- ESR1804 Data too big. Max {max_size}b
- ESR1805 Bad data format
Battery
Battery diagnostic functions.
getVoltage
sensors.battery.getVoltage()
Description: Returns battery volatage in V
Returns: number
isExtPower
sensors.battery.isExtPower()
Description: Returns true
if external power is available.
Returns: bool
isCharging
sensors.battery.isCharging()
Description: Returns true
if battery is charging. Note that isExtPower
may be true, but isCharging
may return false because batter is full.
Returns: bool
getPerc
sensors.battery.getPerc()
Description: Energy left in battery in %
Returns: number
getCapacity
sensors.battery.getCapacity()
Description: Energy left in battery in mAh. Battery must go through full charge/discharge cycle for this value to be accurate.
Returns: number
getAvgCurrent
sensors.battery.getAvgCurrent()
Description: Gets average current in mA. Negative values mean that battery is charging. Averaging window is quite long so it may take up to a minute for the value to reach stable value.
Returns: number
setPowerListener
sensors.battery.setPowerListener(callback)
Description: Register power state listener. It will be called when device power state has changed (external power connected/disconnected, battery charging started, stopped). Registering new handler will overwrite previous one (setting it to null
will unregister current listener).
Callback will be invoked immediately after this function is called with current charging status and external power.
Arguments:
-
callback (function) -
Function signature:
(externalPower, charging) => ...
- externalPower (bool) - Is
true
if external power was applied - charging (bool) - Is
true
if battery is charging
- externalPower (bool) - Is
Returns: undefined
Temperature
Temperature reading functions.
get
sensors.temp.get()
Description: Current temperature in Celsius degrees.
Note: When chargning device can get warmer and returned value will not reflect real ambient temperature. Same effect can also be observed when modem is used to transmit data very often.
Returns: number
setFastMode
sensors.temp.setFastMode(enabled)
Description: Enables fast measurement mode
Arguments:
- enabled (bool, default: true) - If true then temperature measurement will be takes in shorter intervals
Invocation example:
sensors.temp.setFastMode(true)
Returns: undefined
Cloud communication
Cloud communications functions.
enqueue
cloud.enqueue(type, message, options)
Description: Enqueues a message to be sent to cloud whenever a next synchronisation event occurs. The message should be delivered eventually (if is set to be non-volatile), but can be delayed due to a long synchronisation period being set, bad cellular reception, or a critically low battery. Max serialized message size is about 8kB (this value may change in the future), otherwise function will throw an exception. Function returns size of enqued data in bytes (after optional compression).
Device ID and timestamp are automatically included in the event so there is not need to include them inside event message.
This function may block, so avoid using is frequently because it may slow down execution of other parts of your code.
This function may throw ESR0202 No storage space
if device is not able to send data to the Cloud fast enough to make space for new events (try to decrease event enqueue rate in this case).
Arguments:
- type (string, max length: 30) - User provided event type name.
- message (pure_object) - Serializable user data object - any JSON compatible object is valid. Promises, functions, handles (eg. from timers) inside object will throw an exception.
-
options (object, optional) - Individual event options. Volatile means that message can be removed if there is not enough storage space.
Object fields:
- volatile (bool, default: true, optional) - If event is volatile it means it can be deleted when there is not enough space in storage (to make space for new events).
- ttl (interval, unit: s, default: 0, optional) - Time-To-Live - how long event is considered valid to be uploaded to server. 0 means indefinitely.
Example:
{ volatile : false, ttl : "24h" }
Invocation example:
cloud.enqueue("status", {battery: 0.98, temp: 23.5}, {volatile: true})
Returns: number
Errors thrown:
- ESR0104 Execution interrupted
- ESR0201 Storage error
- ESR0202 No storage space
- ESR0203 Not serializable
- ESR0204 Message too big (max {max_size}b).
setVar
cloud.setVar(name, message)
Description: Sets variable that needs to be sent to Cloud. Variables are lightweight, non-persistent way to pass information to Cloud. They are kept on VM heap and sent to Cloud during sync. Only their last set value is sent if it has changed since last synchronization. On the Cloud they appear as ordinary events. Max number of variables is 30 and their size is limited to 1kB after serialization.
Arguments:
- name (string, max length: 30) - Variable name
- message (any) - Serializable user data object - any JSON compatible object is valid. Promises, functions, handles (eg. from timers) inside object will throw an exception.
Invocation example:
cloud.setVar("status", {battery: 0.98, temp: 23.5})
Returns: number
Errors thrown:
onReceive
Variant 1:
cloud.onReceive(msgHandler)
Description: Receives message from cloud. It overwrites previous callback. Setting null
will disable callback. Receiving messages happens during synchornization with Cloud. Usually this function dispatches incoming messages to other handling functions.
Arguments:
-
msgHandler (function) - Function that will receive and process messages from Cloud
Function signature:
(msg) => ...
- msg (object) - Envelope with a message received from Cloud
Object fields:
- type (string) - Message type
- ts (number, unit: ms) - Enqueue timestamp
- payload (object) - Message payload (JSON-like object)
Example:
{ type : "start_scan", ts : 12345465456534, payload : {timeout: 1000} }
Invocation example:
cloud.onReceive((msg) => {
switch(msg.type) {
case "led":
io.led(msg.payload.ledNumber, msg.payload.state);
break;
case "color":
io.setLedColor(msg.payload.color);
break;
default:
print("Unknown payload type: " + msg.type);
break;
}
})
Variant 2:
cloud.onReceive(null)
Description: Clears Cloud message callback
Returns: undefined
onPropertiesChanged
Note: This function might not be available on all hardware revisions.
cloud.onPropertiesChanged(handler)
Description: Called when beacon Cloud properties has changed. When callback is set and properties are available then it will be invoked immediately. Properties can change at any moment, but they only updated during synchronization.
Cloud properties are a set of key-value pairs that are defined per device basis. They contain name, serial number, color, assigned tags, etc. (this list may be extended in the future). Some of those properties can be changed in Cloud console, others are permanent.
Cloud properties can be used to change behavior of micro app depending on which device it is installed using for example tags.
Arguments:
-
handler (function) - Function that will receive metadata about beacon.
Function signature:
(properties) => ...
- properties (object) - Envelope with a message received from Cloud.
Set of received properties may change without firmware version update.
Object fields:
- name (string) - Beacon name
- tags (array) - List of beacon tags
- color (string) - Device color
- serial (string, optional) - Device serial number if available
Example:
{ name : "My Beacon 2", tags : ['kitchen', 'celing'], color : "mint" }
- properties (object) - Envelope with a message received from Cloud.
Invocation example:
cloud.onPropertiesChanged((props) => {
print("Beacon name is: " + props.name);
})
Returns: undefined
Data synchronisation
Synchronisation functions
setHandler
sync.setHandler(callback)
Description: Register synchronisation start handler. Registering new handler will overwrite previous.
You can return a promise here and sync will wait for promise to resolve or reject for at least 5min.
If you enqueue your event messages here they will be delivered in this synchronisation cycle.
Arguments:
-
callback (function) - Callback function can return a promise. Sync process will wait (but no longer than 5m) till this promise is resolved or rejected. This feature is available since version 0.2.4.
Passingnull
will unregister current callback.Function signature:
() => ...
Invocation example:
sync.setHandler(() => {
cloud.enqueue("status", {temp: sensors.temp.get(), bat: sensors.battery.getPerc()});
});
Returns: undefined
setEndHandler
sync.setEndHandler(callback)
Description: Register synchronisation end handler. Registering new handler will overwrite previous. Setting it null
will disable handler. Start and end handler can be called multiple times when device in re-trying to connect to the Cloud.
Arguments:
-
callback (function) -
Function signature:
(error) => ...
- error (error) - Synchronization error or
undefined
if none happened
- error (error) - Synchronization error or
Invocation example:
// Turn LEDs red is sync fails.
sync.setEndHandler((error) => {
if(error) {
io.led(true);
io.setLedColor(io.Color.RED);
}
});
Returns: undefined
now
sync.now()
Description: Triggers synchronisation with cloud immediatly. If invoked during synchronisation it will do nothing. This function is asynchronous and will return immediatly.
Try to avoid using sync.now()
just after cloud.enqueue()
and calling them in short intervals. This will keep modem on and consume significat amount of power.
Function returns true
if sync process has been started, it returns false
if sync process was in progress when function was called.
Returns: bool
setSyncPeriod
sync.setSyncPeriod(syncPeriod)
Description: Sets maximum synchronisation period in seconds. It reschedules pending synchronization automatically when called. Synchronisation may happen earlier due to calling sync.now()
or other internal events (like low battery or running out of storage memory). New sync period time is calculated from when last sync finished, so when you call sync.now()
next scheduled sync will happen after set period.
Arguments:
- syncPeriod (interval, unit: s, min: 120, max: 7776000) - Synchronization period in seconds (or you can use string interval)
Invocation example:
sync.setSyncPeriod("12h")
Storage
Local persistent key-value storage that can handle multiple values.
save
storage.save(key, data)
Description: Stores a single record in local storage under provided numeric key. If key had previous records it overwrites them. Max serialized record size is about 12kB (this value may change in the future). Function returns size of saved data in bytes.
Arguments:
- key (number) - Record key
- data (any) - Serializable user data object - any JSON compatible object is valid. Promises, functions, handles (eg. from timers) inside object will throw an exception.
Returns: number
Errors thrown:
- ESR0201 Storage error
- ESR0202 No storage space
- ESR0203 Not serializable
- ESR0204 Message too big (max {max_size}b).
- ESR0205 Data store timeout
add
storage.add(key, data)
Description: Adds a record to local storage under provided numeric key. There can be many records under given key. Max serialized record size is about 12kB (this value may change in the future). Function returns size of saved data in bytes.
Arguments:
- key (number) - Record key
- data (any) - Serializable user data object - any JSON compatible object is valid. Promises, functions, handles (eg. from timers) inside object will throw an exception.
Returns: number
Errors thrown:
- ESR0201 Storage error
- ESR0202 No storage space
- ESR0203 Not serializable
- ESR0204 Message too big (max {max_size}b).
- ESR0205 Data store timeout
read
storage.read(key)
Description: Reads record from local storage from given numeric key. If key has multiple records then reads and returns the last of them. Returns undefined
when no record does not exist under provided key.
Arguments:
- key (number) - Record key
Returns: object
remove
storage.remove(key)
Description: Removes all records from local storage with given numeric key. Returns true
if any record was found and deleted.
Since: 0.0.5
Arguments:
- key (number) - Record key
Returns: bool
readAll
Variant 1:
storage.readAll(handle)
Description: Reads all records from storage using provided function.
Note: Since storage memory is bigger than operational memory, storing all elements in a single data structure during read may lead to out of memory errors.
Arguments:
-
handle (function) -
Function signature:
(key, data) => ...
- key (number) - Record key
- data (object) - JSON like object with data
Variant 2:
storage.readAll(id, handle)
Description: Reads all records from storage with given numeric key using provided function.
Note: Since storage memory is bigger than operational memory, storing all elements in data structure may lead to out of memory errors.
Arguments:
- id (number) - Record key
-
handle (function) -
Function signature:
(id, data) => ...
- id (number) - Record key
- data (object) - JSON like object with data
Returns: undefined
Errors thrown:
clear
storage.clear()
Description: Clears all records from local storage (it does not affect equeued events).
Returns: undefined
getStats
storage.getStats()
Description: Get storage statistics.
Since: 0.1.0
Returns: object
Object fields:
- total (number, unit: byte) - Total size of storage (that includes space for app, user storage and events).
- used (number, unit: byte) - Used storage in bytes (includes space for app, user storage and events).
- free (number, unit: byte) - Free storage space
Example:
{
total : 96000,
used : 5345,
free : 68000
}
Location
Location functions using global sattelite navigation systems (GNSS).
Note: This API might not be available on all hardware revisions.
distance
location.distance(from, to)
Description: Calculates distance between two geographical locations
Arguments:
- from (object) - Source location
- to (object) - Destination location
Returns: number
startUpdates
location.startUpdates(callback, options)
Description: Invoke callback when GNNS position changes. You can register only one callback (calling it again will override callback).
Function will report position updates (if position can be obtained) for at least 15min unless different value is specified in timeout parameter in options (0 timeout means infinite). Updates will be returned after minimum minInterval
seconds and when device moved more than minDistance meters from last position. minDistance is 0 by default and this value means it is not used.
If location fails returned promise is rejected. Promise will be resolved with last known position (or undefined
) either when location.stop()
wil be called or on timeout.
Arguments:
-
callback (function, default: {0,0}, optional) - Callback function that will be called when position has changed. This callback will be called only if position was succesfully obtained.
Function signature:
(position) => ...
- position (object) - Geographical position.
Object fields:
- lat (number, unit: deg) - Lattitude
- long (number, unit: deg) - Longitude
- speed (number, unit: km/h) - Estimated speed
- alt (number, unit: m) - Altitude
- head (number, unit: deg) - Heading
- prec (number) - Horizontal precision (HDOP)
- diff (number, unit: m) - Difference from last returned position
- ts (number, unit: ms) - UTC timestamp (sice 1 Jan 1970)
- sat (number) - Number of sattelites
Example:
{ lat : 50.014, long : 19.934, speed : 36, alt : 176, head : 124, prec : 2.4, diff : 22.5, ts : 1528289744000, sat : 124 }
-
options (object, optional) - Location options like minimal reporting interval (in s), minimal distance (in m) or overall location timeout (in s). Returned promise will be rejected if
minInterval
is greater thantimeout
.Object fields:
- timeout (interval, unit: s, default: 900, optional) - Maximum time GNSS is switched on. 0 for unlimited. Timeout is calculated from the moment GNSS subsystem has woke up and is ready to start acquiring position.
- minInterval (interval, unit: s, default: 5, optional) - Minimal interval between GNSS position callback calls
- minDistance (number, unit: m, default: 0, optional) - Minimal reporting distance
- maxFixWait (interval, unit: s, min: 40, max: 600, default: 180, optional) - Maximum time to wait for fix before turning GNSS off and waiting ‘minInterval’ seconds for next try. If ‘minInterval’ is smaller than ‘maxFixTime’ then GNSS will be always on.
Example:
{ timeout : 180, minInterval : 0, minDistance : 0.5, maxFixWait : 40 }
Invocation example:
location.startUpdates((position) => {
print(`lattitude=${position.lat} longitude=${position.long}`)
}, {minInterval: 10, minDistance: 10.2, timeout: 120})
Returns: promise
mock
Variant 1:
location.mock(position)
Description: Mocks current GNSS position. Use for testing only. You need to start location tracking as ususal using startUpdates
, but if you call this method mocked position will be returned in callback as if it got real fix. Mocked location objects have field called mock
set to 1
. Mocking does not affect Last Known Location. Mock works only after startUpdates
has been called.
Arguments:
- position (object) - Mocked device position.
Variant 2:
location.mock(null)
Description: Stops position mocking
Returns: undefined
stop
location.stop(resolvePromise)
Description: Stops location tracking
Arguments:
- resolvePromise (bool, default: true, optional) - If
true
then thestartUpdates
promise will be resolved
Invocation example:
location.stop(true)
Returns: undefined
UWB Ranging
Distance ranging using Ultra Wide Band (AI Beacon only)
Note: This API might not be available on all hardware revisions.
start
uwb.start(role, options, callback)
Description: Provides distances from other UWB devices
Arguments:
- role (number) - Sets device role
-
uwb.Role.TOF_RESPONDER = 0 → Time of Flight - Responder - receives measured distance. Works only with devices that have INITIATOR role.
-
uwb.Role.TOF_INITIATOR = 1 → Time of Flight - Initiator - initiates ranging procedure. Works only with devices that have RESPONDER role.
-
uwb.Role.TOF_DUAL = 4 → Time of Flight - Initiator and Responder - switches between Initiator and Responder roles
-
uwb.Role.TDOA_TAG = 2 → Time Difference of Arrival - sends blinks. Set it for trackable assets. Works only with devices that have ANCHOR role.
-
uwb.Role.TDOA_ANCHOR = 3 → Time Difference of Arrival - receives blinks and sends them to Cloud for computation. Mount device in fixed location. Works only with devices that have TAG role.
-
-
options (object, optional) - Location options like minimal reporting interval (in s), minimal distance (in m) or overall location timeout (in s). Returned promise will be rejected if
minInterval
is greater thantimeout
.Object fields:
- timeout (interval, unit: s, default: 20, optional) - Maximum time UWB is switched on. 0 for unlimited.
- mode (number, default: uwb.Mode.LONG_RANGE, optional) - UWB mode: high performance, longer range or low power. All devices must have the same mode set to communicate with each other.
-
uwb.Mode.HIGH_RESPONSIVNESS = 0 → High responsivness
-
uwb.Mode.LONG_RANGE = 1 → Long range mode
-
uwb.Mode.LOW_POWER = 2 → Low power mode
-
- dualRole - Dutal role (switched initiator and responder) settings
* initiatorTime (interval, unit: ms, default: 500, optional) - In DUAL role it sets how long initiator should work. Effective time will be randomized.
* responderTime (interval, unit: ms, default: 500, optional) - In DUAL role it sets how long responder should work. Effective time will be randomized.
* randomize (number, unit: %, min: 0, max: 100, default: 20, optional) - Percentage of effective interval randomization - panId (number, default: DEFAULT_PAN_ID, optional) - Two-byte identifier of UWB network. Devices with the same panId are able to communicate with each other.
Note: It is good practice to change PAN ID to avoid conflicts with other UWB devices. There will be a warning if default PAN ID is used. - minDistance (number, unit: m, default: 0, optional) - Minimal reporting distance
- maxDistance (number, unit: m, default: 10000, optional) - Maximum reporting distance
- blinkPeriod (interval, unit: ms, default: 1000, optional) - Blink period for TAG
- neighbours (array, optional, since: 0.2.7) - List of IDs of neighbours initiator is ranging with
Example:
{ timeout : 0, mode : uwb.Mode.LONG_RANGE, dualRole : { initiatorTime : 0, responderTime : 0, randomize : 0 }, panId : 0x1234, minDistance : 0.5, maxDistance : 10, blinkPeriod : 1000 }
-
callback (function, default: {0,0}, optional) - Callback function that will be called when distance has been measured. This callback will be called only if position was succesfully obtained. It is not valid role for TOF_INITIATOR role (exception thrown).
Function signature:
(distance) => ...
- distance (object) - Device distance
Object fields:
- id (string) - Other device id
- dist (number, unit: m) - Distance
- lqi (number, optional) - Measurment quality
Example:
{ id : "ab3456", dist : 6.934, lqi : 0.3 }
Invocation example:
uwb.start(uwb.Role.RESPONDER, {minDistance: 1.2, maxDistance: 10.2, timeout: 120, panId: 0x2341 }, (distance) => {
print(`id=${distance.id} distance=${distance.dist}`)
})
Returns: promise
Errors thrown:
restart
uwb.restart(role, options)
Description: Restarts ranging with new role and parameters keeping the same promise and callback. To use this function UWB must be started first.
Arguments:
- role (number, default: 255, optional) - Sets device role
-
uwb.Role.TOF_RESPONDER = 0 → Time of Flight - Responder - receives measured distance. Works only with devices that have INITIATOR role.
-
uwb.Role.TOF_INITIATOR = 1 → Time of Flight - Initiator - initiates ranging procedure. Works only with devices that have RESPONDER role.
-
uwb.Role.TOF_DUAL = 4 → Time of Flight - Initiator and Responder - switches between Initiator and Responder roles
-
uwb.Role.TDOA_TAG = 2 → Time Difference of Arrival - sends blinks. Set it for trackable assets. Works only with devices that have ANCHOR role.
-
uwb.Role.TDOA_ANCHOR = 3 → Time Difference of Arrival - receives blinks and sends them to Cloud for computation. Mount device in fixed location. Works only with devices that have TAG role.
-
-
options (object, optional) - Location options like minimal reporting interval (in s), minimal distance (in m) or overall location timeout (in s). Returned promise will be rejected if
minInterval
is greater thantimeout
.Object fields:
- timeout (interval, unit: s, default: 20, optional) - Maximum time UWB is switched on. 0 for unlimited.
- mode (number, default: uwb.Mode.LONG_RANGE, optional) - UWB mode: high performance, longer range or low power. All devices must have the same mode set to communicate with each other.
-
uwb.Mode.HIGH_RESPONSIVNESS = 0 → High responsivness
-
uwb.Mode.LONG_RANGE = 1 → Long range mode
-
uwb.Mode.LOW_POWER = 2 → Low power mode
-
- dualRole - Dutal role (switched initiator and responder) settings
* initiatorTime (interval, unit: ms, default: 500, optional) - In DUAL role it sets how long initiator should work. Effective time will be randomized.
* responderTime (interval, unit: ms, default: 500, optional) - In DUAL role it sets how long responder should work. Effective time will be randomized.
* randomize (number, unit: %, min: 0, max: 100, default: 20, optional) - Percentage of effective interval randomization - panId (number, default: DEFAULT_PAN_ID, optional) - Two-byte identifier of UWB network. Devices with the same panId are able to communicate with each other.
Note: It is good practice to change PAN ID to avoid conflicts with other UWB devices. There will be a warning if default PAN ID is used. - minDistance (number, unit: m, default: 0, optional) - Minimal reporting distance
- maxDistance (number, unit: m, default: 10000, optional) - Maximum reporting distance
- blinkPeriod (interval, unit: ms, default: 1000, optional) - Blink period for TAG
- neighbours (array, optional, since: 0.2.7) - List of IDs of neighbours initiator is ranging with
Example:
{ timeout : 0, mode : uwb.Mode.LONG_RANGE, dualRole : { initiatorTime : 0, responderTime : 0, randomize : 0 }, panId : 0x1234, minDistance : 0.5, maxDistance : 10, blinkPeriod : 1000 }
Invocation example:
uwb.restart(uwb.Role.RESPONDER, {minDistance: 1.2, maxDistance: 10.2, timeout: 120, panId: 0x2341 })
Returns: undefined
Errors thrown:
stop
uwb.stop(resolvePromise)
Description: Stops UWB ranging for all roles.
Arguments:
- resolvePromise (bool, default: true, optional) - If
true
then thestart
promise will be resolved
Invocation example:
uwb.stop(true)
Returns: undefined
blink
uwb.blink(userData)
Description: When in TDoA TAG role it sends a single blink. It allows more fine grained control over blinking schedule. It is recommended to set blinkPeriod
to 0 so it won’t blink automatically. It will throw an error when used with wrong role, setting or with UWB not started.
Arguments:
- userData (any, default: NULL, optional) - User data (4 bytes) that will be sent within blink.
Invocation example:
uwb.blink(NULL)
Returns: undefined
Errors thrown:
System
System information and global settings functions
getPublicId
sys.getPublicId()
Description: Gets device public identifier as hex string.
Note: Device ID is already included in event that is sent using cloud.enqueue(...)
Returns: string
getUptime
sys.getUptime()
Description: Gets system uptime in seconds since last reset.
Returns: number
isTimeSynced
sys.isTimeSynced()
Description: Check if time has been synchronized. If not then any date operation will print invalid time error on console. Same can be achieved by new Date().getFullYear() > 2018
Returns: bool
getFirmware
sys.getFirmware()
Description: Gets firmware version as 3 element array [major, minor, patch]
Since: 0.0.4
Returns: object
Returned value example:
[0,0,5]
getHardware
sys.getHardware()
Description: Gets hardware revision as string
Since: 0.0.4
Returns: string
Modem
Cellular Modem Radio control and diagnostic
Note: This API might not be available on all hardware revisions.
getOperators
modem.getOperators()
Description: Gets list of available operators. This may take we minutes and use significant amount of power.
Note: Calling this function again before promise is resolved will cause previous promise to be rejected.
When NB-IoT is enabled scan may take up to 30min before it times-out.
Invocation example:
modem.getOperators()
.then((opers) => print("Operators:" + JSON.stringify(opers)))
.catch((e) => print("Error: " + e))
Returns: promise
Returned value example:
[{name: "T-Mobile", type: "gsm", status: "curr"},
{name: "Orange", type: "gsm", status: "avail"},
{name:"Verizon", type: "gsm", status: "avail"}]
getStatus
modem.getStatus()
Description: Gets current network status like signal strength, operator, cell ID.
Note: Calling this function again before promise is resolved will cause previous promise to be rejected.
Invocation example:
modem.getStatus()
.then((status) => print("Status:" + JSON.stringify(status)))
.catch((e) => print("Error: " + e))
Returns: promise
Object fields:
- name (string) - Operator name
- signal (number) - Signal strength
- rssi (number, optional) - RSSI
- rsrp (number, optional) - RSRP
- rsrq (number, optional) - RSRQ
- mcc (number) - Mobile Country Code (MCC)
- mnc (number) - Mobile Network Code (MNC)
- lac (number) - Location Area Code (LAC)
- cell (number) - Cell ID (CID)
- tech (string) - Technology used (GSM, LTE Cat. M1., NB IoT)
- band (string) - Used band symbol
Example:
{
name : "T-Mobile",
signal : 22,
rssi : -92,
rsrp : -17,
rsrq : -17,
mcc : 260,
mnc : 2,
lac : 1111,
cell : 1111,
tech : "Cat-M1",
band : "LS"
}
getCells
modem.getCells()
Description: Gets information about cells in neigboughood. Similar to getOperators, but focuses more on signal parameters. When NB-IoT is enabled scan may take up to 30min before it times-out.
Some hardware revisions may not support this function and reject promise with ESR0003 Unsupported feature.
Invocation example:
modem.getCells()
.then((cells) => print("Cells:" + JSON.stringify(cells)))
.catch((e) => print("Error: " + e))
Returns: promise
Object fields:
- name (string) - Operator name
- signal (number) - Signal strength
- rssi (number, optional) - RSSI
- rsrp (number, optional) - RSRP
- rsrq (number, optional) - RSRQ
- mcc (number) - Mobile Country Code (MCC)
- mnc (number) - Mobile Network Code (MNC)
- lac (number) - Location Area Code (LAC)
- cell (number) - Cell ID (CID)
- tech (string) - Technology used (GSM, LTE Cat. M1., NB IoT)
- band (string) - Used band symbol
Example:
{
name : "T-Mobile",
signal : 22,
rssi : -92,
rsrp : -17,
rsrq : -17,
mcc : 260,
mnc : 2,
lac : 1111,
cell : 1111,
tech : "Cat-M1",
band : "LS"
}
getInfo
modem.getInfo()
Description: Gets device information like IMEI, IMSI, ICCID.
Note: Calling this function again before promise is resolved will cause previous promise to be rejected.
Invocation example:
modem.getInfo()
.then((info) => print("Info:" + JSON.stringify(info)))
.catch((e) => print("Error: " + e))
Returns: promise
Object fields:
- iccid (string) - Integrated Circuit Card Identifier (ICCID) - unchangeable SIM card number (usually printed on it)
- imei (string) - International Mobile Equipment Identity (IMEI)
- imsi (string) - International Mobile Subscriber Identity (IMSI)
Example:
{
iccid : "00000000000000000000000",
imei : "000000000000000000",
imsi : "000000000000000000"
}
setAirplaneMode
modem.setAirplaneMode(state)
Description: Sets airplane mode on or off. This will make all LTE related functions to reject their promises and all cellular communication will be turned off.
Arguments:
- state (bool, default: true) - Turns the Airplane Mode on or off. When turned on, the LTE module is shut down, so the heartbeat reports will not be sent and any attempts to sync with Estimote Cloud will be queued until the Airplane Mode is turned back off.
Invocation example:
modem.setAirplaneMode(true)
Returns: undefined
Application
Application execution control and error handling functions
setErrorHandler
app.setErrorHandler(errorHandler)
Description: Sets global error handler that will handle all uncaught exceptions from callbacks and promises. When no handler function is set, errors will be displayed on debug console.
Arguments:
-
errorHandler (function) - Handles errors from callbacks and system. Passing
null
will unregister current callback.Function signature:
(type, error) => ...
- type (number) - Error type. 0 - application error, 1 - system error, 2 - fatal error (app was restarted)
- error (object) - Error object
Invocation example:
app.setErrorHandler((type, errorObj) => print(type + ": " + errorObj))
setInstallHandler
app.setInstallHandler(callback)
Description: Register new application install handler. It will be called on old app before new app is started. Its a place to save current state of an current app so it can be passed to new one. Registering new handler will overwrite previous.
Note: Do not start any asynchronous here since app will be stopped immediately after this callback returns.
Arguments:
-
callback (function) - Callback function called on old app before a new app is installed. It should avoid doing blocking and long running operations.
Passingnull
will unregister current callback.Function signature:
() => ...
Invocation example:
app.setInstallHandler(() => {
storage.save(0, { "state": currentState });
});
Returns: undefined
remove
app.remove()
Description: Stops and deletes application. New application can be sent though Bluetooth or deployed by Cloud.
stop
app.stop()
Description: Stops application. App can be restarted by cycling side button or by installing new app.
restart
app.restart()
Description: Restarts application
getUptime
app.getUptime()
Description: Gets application uptime is ms (since installation, system reboot or comanded restart)
Since: 0.0.5
Returns: number
gc
app.gc()
Description: Forces garbage collector to run
Since: 0.0.9
getMemStats
app.getMemStats()
Description: Get memory statistics
Since: 0.1.0
Returns: object
Object fields:
- total (number, unit: byte) - Total number of heap memory
- used (number, unit: byte) - Used heap memory bytes.
- free (number, unit: byte) - Free heap memory bytes.
- peak (number, unit: byte) - Peak used heap memory bytes since app started.
Example:
{
total : 78000,
used : 5345,
free : 68000,
peak : 5345
}
Cryptographic functions
Functions for encryption/decryption and calculating hash functions.
Note: Not all algorithms are available on all hardware revisions due to memory restrictions.
Note: This API might not be available on all hardware revisions.
hash
crypto.hash(hashType, key)
Description: Calculates hash function
Arguments:
- hashType (number) - Hash function type
-
crypto.Hash.SHA1 = 0 → SHA 1
-
crypto.Hash.SHA256 = 1 → SHA 256
-
crypto.Hash.SHA224 = 2 → SHA 224
-
crypto.Hash.SHA384 = 3 → SHA 384
-
crypto.Hash.SHA512 = 4 → SHA 512
-
- key (arraybuffertext, optional) - Key to compute keyed hash (HMAC)
Returns: handle object
Handler object methods:
-
handler.digest() - Calculates hash
-
handler.update(data) - Adds new data to hash
- data (arraybuffertext) - Array buffer with data to be hashed
Errors thrown:
- ESR0004 Not enough resources
encode
crypto.encode(codeType, message, key, iv)
Description: Encodes given message
Arguments:
- codeType (number) - Code type
-
crypto.Code.BASE64 = 0 → Base-64 encoding
-
crypto.Code.HEX = 1 → Hex encoding
-
crypto.Code.AES = 2 → AES simple block encoding. Data size must be 64bytes. Key length must be 16b (128-bit), 24b (192-bit) or 32b (256-bit).
-
crypto.Code.AES_CTR = 3 → AES CTR mode encoding.Key length must be 16b (128-bit), 24b (192-bit) or 32b (256-bit).
-
- message (arraybuffertext) - Message to be encoded
- key (arraybuffertext, optional) - Key used to encrypt message
- iv (arraybuffertext, optional) - Initialization Vector used to encrypto message
Returns: object
decode
crypto.decode(codeType, message, key, iv)
Description: Decodes given message
Arguments:
- codeType (number) - Code type
-
crypto.Code.BASE64 = 0 → Base-64 encoding
-
crypto.Code.HEX = 1 → Hex encoding
-
crypto.Code.AES = 2 → AES simple block encoding. Data size must be 64bytes. Key length must be 16b (128-bit), 24b (192-bit) or 32b (256-bit).
-
crypto.Code.AES_CTR = 3 → AES CTR mode encoding.Key length must be 16b (128-bit), 24b (192-bit) or 32b (256-bit).
-
- message (arraybuffertext) - Message to be decoded
- key (arraybuffertext, optional) - Key used to decrypt message
- iv (arraybuffertext, optional) - Initialization Vector used to encrypto message
Returns: object
NFC
Near Field Communication control functions.
Note: This API might not be available on all hardware revisions.
onFieldChanged
nfc.onFieldChanged(callback)
Description: Invokes callback function when other device exters or exists the communication field
Arguments:
-
callback (function) - Callback function that will be called when other device enters or exits communication field. Passing
null
will unregister callback.Function signature:
(field) => ...
- field (bool) - Is
true
if device is communication field
- field (bool) - Is
Invocation example:
nfc.onFieldChanged((field) => {
print(`Is field on: ${field}`)
})
Returns: undefined
onWrite
nfc.onWrite(callback)
Description: Invokes callback function when NFC tag has been written. Tag becomes writable only when this callback is registered.
Arguments:
-
callback (function) - Callback function that will be called when other device writes NFC tag. Passing
null
will unregister callback.Function signature:
(data) => ...
- data (arraybuffer) - Raw NDEF data received from external device.
Invocation example:
nfc.onWrite((data) => {
print(`Received raw NDEF data`)
})
Returns: undefined
onRead
nfc.onRead(callback)
Description: Invokes callback function just before NDEF message is read. Can be used to update tag contents with nfc.setMsg
on demand.
Arguments:
-
callback (function) - Callback function that will be called when other device reads NFC tag. Passing
null
will unregister callback.Function signature:
() => ...
Invocation example:
nfc.onRead(() => {
nfc.setMsg([
{
recordType: nfc.RecordType.TEXT,
text: `Battery: ${sensors.battery.getVoltage().toFixed(2)}V`
}
)
})
Returns: undefined
startReader
Note: This function might not be available on all hardware revisions.
nfc.startReader(callback, options)
Description: Starts NFC reader and invokes callback function when external NFC tag has been read.
Reader starts only for amount of time specified in options. It does that to conserve power. Recommended power efficient scenario is to start reader on external event like button press.
Reader functionality might not be supported on all hardware revisions.
Arguments:
-
callback (function) - Callback function that will be called when other device writes NFC tag.
Function signature:
(data) => ...
- data (object) - Raw NDEF data received from external device.
-
options (object, optional, since: 0.2.13) - Advanced NFC reader options
Object fields:
- timeout (interval, unit: s, default: 10, optional) - Read wait time. For how long device should wait for tag to appear. After that time reader is turned off and promise is resolved.
- lowPower (bool, default: true, optional) - Enable lower power consumption for the price of responsivness.
Example:
{ timeout : "10s", lowPower : true }
Returns: promise
stopReader
Note: This function might not be available on all hardware revisions.
nfc.stopReader(resolvePromise)
Description: Stops NFC reader immediately.
Arguments:
- resolvePromise (bool, default: true, optional) - If true then the startReader promise will be resolved
Invocation example:
nfc.stopReader(true)
setMsg
Variant 1:
nfc.setMsg(message)
Description: Sets NDEF message so it can be read from device as a tag.
Arguments:
- message (object) - NDEF message as an array of separate NDEF records. Each record must have
recordType
field that defines what other fields must be set.
Invocation example:
nfc.setMsg([{recordType: nfc.RecordType.TEXT,text: "Estimtote Welcomes"},{recordType: nfc.RecordType.URI, uri: 'https://estimote.com'},{recordType: nfc.RecordType.EXTERNAL, type: "custom:type", data: "ab32fef4e5e6e712"}])
Variant 2:
nfc.setMsg(null)
Description: Clears user defined NDEF message and sets back initial one
Invocation example:
nfc.setMsg(null)
Returns: undefined
Errors thrown:
- ESR1103 Message too big. Max {max_size}b
- ESR1104 Invalid format
- ESR1105 Invalid record type: {type}
- ESR1106 Missing field: {field_name}
config
nfc.config(config)
Description: Advanced NFC configuration options
Arguments:
-
config (object, optional, since: 0.2.13) - Advanced NFC options
Object fields:
- id (arraybuffer, optional) - Valid ID length are 4, 7 or 10 bytes. If this value is not set it will be set to the prefix of device public identifier.
- cardEmulation (bool, default: true, optional) - Enables/diables card emulation.
- nfcA - NFC-A options
* enabled (bool, default: true, optional) - NFC-A emulation enabled
* atqa (number, default: 0x0044, optional) - ATQA
* sak (number, default: 0x20, optional) - SAK - nfcF - NFC-F options
* enabled (bool, default: false, optional) - NFC-F emulation enabled
* systemCode (number, default: 0x12FC, optional) - System Code (SENS_REF)
Example:
{ cardEmulation : true, nfcA : { }, nfcF : { } }
Returns: undefined
Errors thrown:
- ESR1107 Bad ID