LTE Beacon: Micro-app API reference

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
  • Map data structure
  • ArrayBuffer and typed arrays
  • promises

Some notably-not-supported ES2015 features:

  • let and const
  • destructuring
  • spread and rest ... operators
  • iterators and for ... of
  • (and more)

None of ES2016 and beyond is supported at this time, most notable ommision being async and await.

Other than that, here’s a list of LTE-Beacon–specific functions and APIs:

Global functions

print

print(text)

Description: Prints message on debug console.

Arguments:

  • text (stringable) - Text that will be displayed on console.

toHex

toHex(array)

Description: Converts arraybuffer/array to hex string

Arguments:

  • array (object) - Text that will be displayed on console.

Returns: object

setTimeout

setTimeout(callback, interval)

Description: Start single shot timer (alias for timers.single)

Arguments:

  • callback (function) - Callback function that will be called when timer fires
    Function signature: () => ...

  • interval (number, unit: ms) - Number of milliseconds that timer will wait before invoking callback

Returns: handle object

Handler object methods:

  • handler.stop() - Stops timer. Calling on stoped timer has no effect.

setInterval

setInterval(callback, interval)

Description: Start repeated timer (alias for timers.repeat)

Arguments:

  • callback (function) - Callback function that will be called when timer fires
    Function signature: () => ...

  • interval (number, unit: ms) - Number of milliseconds that timer will wait before invoking callback

Returns: handle object

Handler object methods:

  • handler.stop() - Stops timer. Calling on stoped timer has no effect.

Timer functions

Timer functions that allow to schedule tasks asynchronously

single

 timers.single(interval, callback)

Description: Start single shot timer

Arguments:

  • interval (number, 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: () => ...

Returns: handle object

Handler object methods:

  • handler.stop() - Stops timer. Calling on stoped timer has no effect.

  • handler.reset() - Resets timer. Calling on stoped timer will schedule it again.

repeat

 timers.repeat(interval, callback)

Description: Start repeated timer.

Arguments:

  • interval (number, 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: () => ...

Returns: handle object

Handler object methods:

  • handler.stop() - Stops timer. Calling on stopped timer will have no effect.

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.

Bluetooth Low Energy functions

Bluetooth Low Energy scanning and advertising functions

 ble.advertise(callback)

Description: This variant will call given function that will provide BLE packet that will be advertised.

Arguments:

  • callback (function) - Callback function that will provide packet each time it will be advertised.
    Function signature: () => ...
 ble.advertise(data)

Description: This variant will advertise statically defined packet.

Arguments:

  • data (object) - Packet that will be advertised

Returns: handle object

Handler object methods:

  • handler.stop() - Stops advertiser

  • handler.interval(interval) - Sets new advertising interval

    • interval (number, ms)- Interval in milliseconds
  • handler.power(interval) - Sets new advertising power (in dBm)

    • interval (number, dBm)- Power in dBm

startScan

 ble.startScan(callback, duration = 10000)

Description: Start scanning for BLE packets. It returns promise that will be resolved when scan stops (either from timeout or stopScan).

Arguments:

  • callback (function) - Callback function that will be called when new packet is detected
    Function signature: (scanRecord) => ...
    • scanRecord (object) - Raw BLE advertising packet.
  • duration (number, unit: ms) - Scan duration. 0 if there is no time limit. Default value is 10000ms (10s).

Returns: promise

Invocation example:

ble.startScan((scanRecord) => {
var packet = ble.parse(scanRecord)
if(packet) {
print(JSON.stringify(packet))
}
}, 10000)

parse

 ble.parse(scanRecord)

Description: Parses scanned BLE advertisment and extracts data. It can recognize most common packets like iBeacon or Eddystone

Arguments:

  • scanRecord (object) - Raw BLE packet scanned provided by startScan callback

Returns: object

stopScan

 ble.stopScan(resolvePromise = true)

Description: Stop BLE scanning

Arguments:

  • resolvePromise (bool) - 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 or Eddystone

eddystoneUrl

 ble.build.eddystoneUrl(url, measuredPower = -20)

Description: Builds EddystoneURL packet

Arguments:

  • url (string) - URL to be advertised
  • measuredPower (number, unit: dBm, min: -127, max: 127) - Measured power in dBm (measured at 0m)

Returns: object

Invocation example:

ble.build.eddystoneUrl("https://estimote.com", -20)

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.

Returns: object

eddystoneUid

 ble.build.eddystoneUid(namespace, instance, measuredPower = -20)

Description: Builds EddystoneUID packet

Arguments:

  • namespace (arraybuffer) - ArrayBuffer or hex string with namespace ID (10 bytes)
  • instance (arraybuffer) - ArrayBuffer or hex string with instance ID (6 bytes)
  • measuredPower (number, unit: dBm, min: -127, max: 127) - Measured power in dBm (measured at 0m)

Returns: object

Invocation example:

ble.build.eddystoneUid("123456789ABCDEF01234", "349012AEB2E3", -20)

iBeacon

 ble.build.iBeacon(uuid, major, minor, measuredPower = -50)

Description: Builds iBeacon packet

Arguments:

  • uuid (arraybuffer) - 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) - Measured power in dBm (measured at 1m)

Returns: object

Invocation example:

ble.build.iBeacon("123e4567-e89b-12d3-a456-426655440000", 1024, 512, -50)

estimoteLocation

 ble.build.estimoteLocation(measuredPower = -50)

Description: Builds Estimote Location packet

Arguments:

  • measuredPower (number, unit: dBm, min: -127, max: 127) - Measured power in dBm (measured at 1m)

Returns: object

Invocation example:

ble.build.estimoteLocation(-50)

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.

Returns: object

BLE device-to-device connectivity

Input/Output

led

Warning: This is temporary API and it is subject to change.

 io.led(id, state)

Description: Sets LED on or off

Arguments:

  • id (number) - RGB segment number
  • state (bool) - Set true to turn on LED
 io.led(state)

Description: Sets LED on or off

Arguments:

  • state (bool) - Set true to turn on LED

Invocation example:

io.led(true)

setLedColor

Warning: This is temporary API and it is subject to change.

 io.setLedColor(id, color)

Description: Sets LED RGB color

Arguments:

  • id (number) - RGB segment number
  • color (array) - Array containing three numbers for red, green and blue colors from 0.0 to 1.0 (max ilumination)
 io.setLedColor(color)

Description: Sets LED RGB color

Arguments:

  • color (array) - Array containing three numbers for red, green and blue colors from 0.0 to 1.0 (max ilumination)

Invocation example:

io.setLedColor([0.5, 0.0, 1.0])

setLedBrightness

Warning: This is temporary API and it is subject to change.

 io.setLedBrightness(id, brightness)

Description: Sets LED brightness

Arguments:

  • id (number) - RGB segment number
  • brightness (number) - Number from 0 to 1.0 with LED brightness.
 io.setLedBrightness(brightness)

Description: Sets LED brightness

Arguments:

  • brightness (number) - Number from 0 to 1.0 with LED brightness.

Invocation example:

io.setLedBrightness(0.5)

press

 io.press(callback, pressType = 0)

Description: Listen for button press. You can assign different callback to each press type (long, short, very long)

Arguments:

  • callback (function) - Function called when button is pressed
    Function signature: () => ...

  • pressType (number) - Button press type

    • io.PressType.SHORT = 0 - Short press, lest than 1 second
    • io.PressType.VERY_LONG = 2 - Very long press, more than 5s
    • io.PressType.LONG = 1 - Long press, more than 3 second

Invocation example:

io.press(() => print("short press"), io.PressType.SHORT)
io.press(() => print("long press"), io.PressType.LONG)

Accelerometer

Accelerometer control functions.

get

 sensors.accel.get()

Description: Returns acceleration in G

Returns: object

setSens

 sensors.accel.setSens(level)

Description: Sets sensitivity

Arguments:

  • level (number) - Sets accelerometer sensitivity level

Returns: undefined

Invocation example:

sensors.accel.setSens(io.accel.Level.MEDIUM)

setResp

 sensors.accel.setResp(level)

Description: Sets sensitivity

Arguments:

  • level (number) - Sets accelerometer responsivness level

Returns: undefined

Invocation example:

sensors.accel.setResp(io.accel.Level.MEDIUM)

onMotion

 sensors.accel.onMotion(callback)

Description: Invokes callback function when device is on motion

Arguments:

  • callback (function) - Callback function that will be called when motion is detected
    Function signature: (motion) => ...
    • motion (bool) - True if device is in motion
 sensors.accel.onMotion(null)

Description: Unregisters motion callback

Returns: undefined

Battery

Battery diagnostic functions.

getVoltage

 sensors.battery.getVoltage()

Description: Returns battery volatage in V

Returns: number

isExtPower

 sensors.battery.isExtPower()

Description: True if external power is available.

Returns: bool

isCharging

 sensors.battery.isCharging()

Description: True if battery is charging

Returns: bool

getPerc

 sensors.battery.getPerc()

Description: Energy left in battery in %

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.

Arguments:

  • callback (function) -
    Function signature: (externalPower, charging) => ...
    • externalPower (bool) - True if external power was applied
    • charging (bool) - True if battery is charging
 sensors.battery.setPowerListener(null)

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.

Returns: undefined

Temperature

Temperature reading functions.

get

 sensors.temp.get()

Description: Temperature in C

Returns: number

setFastMode

 sensors.temp.setFastMode(enabled)

Description: Enables fast measurement mode

Arguments:

  • enabled (bool) - If true then temperature measurement will be takes in shorter intervals

Returns: void

Invocation example:

sensors.temp.setFastMode(true)

Cloud communication

Cloud communications functions.

enqueue

 cloud.enqueue(type, message)

Description: Enqueues event message to be sent to cloud during synchronisation.

Arguments:

  • type (string) - Event type name
  • message (pure_object) - Arbitrary user data object

Returns: undefined

Errors thrown:

  • JS serialization error
  • Storage system error
  • Message is too big
  • Not enough storage space

Invocation example:

cloud.enqueue("status", {battery: 0.98, temp: 23.5})

Data synchronisation

Synchronisation functions

setHandler

 sync.setHandler(callback)

Description: Register synchronisation handler. Registering new handler will overwrite previous. Setting it null will disable handler.

Arguments:

  • callback (function) -
    Function signature: () => ...
 sync.setHandler(null)

Description: Register synchronisation handler. Registering new handler will overwrite previous. Setting it null will disable handler.

Returns: undefined

now

 sync.now()

Description: Forces synchronisation

Returns: bool

setSyncPeriod

 sync.setSyncPeriod(syncPeriod)

Description: Sets synchronisation period in seconds

Arguments:

  • syncPeriod (number, unit: s, min: 120, max: 7776000) -

Storage

Local storage functions

save

 storage.save(id, data)

Description: Stores message in local storage under provided numeric key

Arguments:

  • id (number) - Record ID/key
  • data (any) - User data

Returns: undefined

Errors thrown:

  • JS serialization error
  • Storage system error
  • Message is too big
  • Not enough storage space

    read

     storage.read(id)
    

Description: Reads message from local storage from given numeric key

Arguments:

  • id (number) - Record ID/key

Returns: object

remove

 storage.remove(id)

Description: Removes message from local storage from given numeric key. Returns true if message was found and deleted.

Since: 0.0.5

Arguments:

  • id (number) - Record ID/key

Returns: bool

readAll

 storage.readAll(handle)

Description: Reads all messages from storage using provided function.

Arguments:

  • handle (function) -
    Function signature: (id, data) => ...
    • id (number) - Record id/key
    • data (object) - JSON with data

Returns: undefined

clear

 storage.clear()

Description: Clears all records from local storage

Returns: undefined

Location

Location functions using global sattelite navigation systems (GNSS)

distance

 location.distance(from, to)

Description: Calculates distance between two geographical locations

Arguments:

  • from (object) - From location
  • to (object) - Destination location

Returns: number

startUpdates

 location.startUpdates(callback, options = location_default_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 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 or when device moved more than minDistance meters from last position. minDistance is 0 by default and this value means it is not used.

Arguments:

  • callback (function) - Callback function that will be called when position has changed
    Function signature: (position) => ...
    • position (object) - Geographical position.
      Example:
      {ts: 1537333256000, long: 20.23444343, alt: 265, lat: 30.452345, head: 0, prec: 1.20, speed: 0 }
      
  • options (object) - Location options like minimal reporting interval (in s), minimal distance (in m) or overall location timeout (in s)

Returns: promise

Invocation example:

location.startUpdates((position) => { print(`lattitude=${position.lat} longitude=${position.long}`)
}
}, {minInterval: 10, minDistance: 10.2, timeout: 120 })

stop

 location.stop(resolvePromise = true)

Description: Stops location tracking

Arguments:

  • resolvePromise (bool) - If true then the startUpdates promise will be resolved

Returns: undefined

Invocation example:

location.stop(true)

System

System information and global settings functions

getPublicId

 sys.getPublicId()

Description: Gets device public identifier as hex string

Returns: string

getUptime

 sys.getUptime()

Description: Gets system uptime in seconds since last reset

Returns: number

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

LTE

LTE Radio control and diagnostic

getOperators

 lte.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 reject.

Returns: promise

Returned value example:

[{name: "T-Mobile",type: "gsm", status: "curr"}, {name: "Orange", type: "gsm","status": "avail"},{name:"Verizon",type: "gsm",status: "avail"}

Invocation example:

lte.getOperators().then((opers) => print("Operators:" + JSON.stringify(opers))).then((e)=> print("Error: JSON.stringify(e)))

getStatus

 lte.getStatus()

Description: Gets network status like signal strength, operator, cell ID. Note: Calling this function again before promise is resolved will cause previous promise to reject.

Returns: promise

Returned value example:

{name:"T-Mobile" signal:22,mcc:260,mnc:2,lac:1111,cell:11111,iccid:"00000000000000000000000",tech:"Cat-M1"}

Invocation example:

lte.getStatus().then((status) => print("Status:" + JSON.stringify(status))).then((e)=> print("Error: JSON.stringify(e)))

setAirplaneMode

Warning: This is temporary API and it is subject to change.

 lte.setAirplaneMode(state)

Description: Sets airplace mode on or off

Arguments:

  • state (bool) - Set true to turn on airplane mode

Returns: void

Invocation example:

lte.setAirplaneMode(true)

Application

Application execution control and error handling sfunctions

setErrorHandler

 app.setErrorHandler(errorHandler)

Description: Registers global error handler.

Arguments:

  • errorHandler (function) - Handles errors from callbacks and system
    Function signature: (type, msg) => ...
    • type (number) - Error type
    • msg (string) - Error message
 app.setErrorHandler(null)

Description: Unregisters global error handler.

remove

 app.remove()

Description: Stops and deletes application

stop

 app.stop()

Description: Stops application

restart

 app.restart()

Description: Restarts application

getUptime

 app.getUptime()

Description: Gets application uptime is ms

Since: 0.0.5

Returns: number

NFC

Near Field Communication control functions

onFieldChanged

 nfc.onFieldChanged(callback)

Description: Invokes callback function when other device in communication field

Arguments:

  • callback (function) - Callback function that will be called when other device is in communication field
    Function signature: (field) => ...
    • field (bool) - True if device is communication field
 nfc.onFieldChanged(null)

Description: Unregisters field callback

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
    Function signature: (data) => ...
    • data (arraybuffer) - Raw NDEF data received from external device.
 nfc.onWrite(null)

Description: Unregisters write callback

Returns: undefined

setMsg

 nfc.setMsg(message)

Description: Sets NDEF message so it can be read from device as a tag.

Arguments:

  • message (object) - NDEF message
 nfc.setMsg(null)

Description: Sets NDEF message so it can be read from device as a tag.

Returns: undefined

Errors thrown:

  • Invalid format
  • Invalid record type
  • Too big
  • Missing field

Invocation example:

nfc.setMsg(setMsg(null))