Javascript APIs

MetaSensors are supported on Linux. Developers can create their own Apps using Node.Js on Linux.

Here is a tutorial to install Javascript/Node/NPM on Linux.

You should be comfortable with your choice of Linux distro.

Note

Some installation steps may change or look slightly different depending on your Linux distro of choice.

Source Code

You can find the Javascript code on Github here: https://github.com/mbientlab/MetaWear-SDK-JavaScript.

Python Tutorials

You can find tutorials to use the Javascript libs here: https://mbientlab.com/javascriptdocs/latest.

C++ API Documentation

The C++ API calls are documented here: https://mbientlab.com/documents/metawear/cpp/latest/.

Installation

Ubuntu is popular and highly recommended as the Linux distro of choice. Simply follow the Ubuntu install steps on the Ubuntu website :

_images/ubuntu-0.png

The great thing about Ubuntu is that it comes with many packages installed. Please note that if you choose to install a bare-bones Linux distro, you may need to install many utilities, libraries and packages needed to support MetaWear development.

If you are going to use Raspbian OS, we recommend the “Raspbian Buster with desktop” (or similar), the lite and the max versions have either too much or too little pre-installed. Just follow the steps here.

For any other OS, simply follow the guide on their installation site.

OS Updates

If Ubuntu or your OS asks for an update, be kind and update! Run:

>>> sudo apt-get update

To upgrade (with caution) run: – this usually takes a while, DO NOT STOP IT.

>>> sudo apt upgrade

Bluetooth

Make sure that the Bluetooth hardware (adapter) is recognized by your OS by using the following command:

>>> hcitool dev
_images/ubuntu-1.png

If your distro does not come with Bluetooth drivers installed, install the required packages with their dependencies:

>>> sudo apt install bluetooth pi-bluetooth bluez blueman bluez-utils

Check the bluetooth status:

>>> systemctl status bluetooth

Connect your Bluetooth device and restart the Bluetooth services:

>>> sudo /etc/init.d/bluetooth restart

or

>>> sudo systemctl start bluetooth

Verify your Bluetooth device is detected along with the appropriate modules:

>>> lsusb
    Device 005: ID 0a12:0001 Cambridge Silicon Radio, Ltd Bluetooth Dongle (HCI mode)

Finally review the output of hcitool dev:

>>> hcitool dev
    Devices:
        hci0    00:11:95:00:1A:CF

You can also load the Bluetooth command-line tool, you need to enter the following command on your Raspberry Pi.

>>> bluetoothctl

Now that we are in the Bluetooth command-line tool, we need to go ahead and turn the agent on.

Switching the agent on will allow us to search for and pair with other Bluetooth devices. You can do this by using the command below.

>>> agent on

The next step is to tell the Bluetooth device on our Raspberry Pi to scan for other devices.

By scanning for devices, we can retrieve their MAC address and begin the process of pairing that device with the Raspberry Pi. To start the scan process, all you need to do is enter the following command.

>>> scan on

From this command, you should start seeing a result like what we have below.

>>> [bluetooth]# scan on
    Discovery started
        [CHG] Controller DC:A6:32:05:7F:06 Discovering: yes
        [NEW] Device 51:B8:16:6A:6F:C6 51-B8-16-6A-6F-C6
        [NEW] Device 40:23:43:3F:4E:58 BRAVIA 4K UR2

If you are having difficulties, please consult the community forum and manual for your OS of choice. The Ubuntu forum has already addressed many issues you may come upon.

Dongles

Linux systems typically support USB to Bluetooth Dongle; they might even support multiple Dongles.

You can use these Dongles to get more sensors connected via the BLE link simultaneously.

First, plug in the USB to BLE Dongle.

Then, you can use lsusb -t to display how the USB devices and hubs are arranged and their allocated speeds.

>>> lsusb
    Bus 002 Device 005: ID 0a12:0001 Cambridge Silicon Radio, Ltd Bluetooth Dongle (HCI mode)
>>> hciconfig
    hci0:   Type: USB
>>> hciconfig -a hci0
    Manufacturer: Accel Semiconductor Ltd. (74)

If it shows up as an hci device, great, you are done!

If not, there are a couple things to consider. First, you need to make sure it is actually a Linux supported dongle: https://elinux.org/RPi_USB_Bluetooth_adapters.

If your dongle is not on this list, you are out of luck and need to purchase a new one that is on the list.

Warning

If you have two of the same dongles, sometimes the second dongle may not be recognized by the system.

Once you have determined that your BLE Dongle is Linux supported, run the following commands with the Dongles plugged-in:

>>> sudo apt-get update
>>> sudo apt-get upgrade
>>> sudo reboot now

Virtual Machines (VMs)

If you are running in a virtual environment, you will need to take extra care to make sure the Bluetooth drivers and adapters are working in the VM before you do anything else.

For example, VirtualBox guest OS doesn’t recognize the Bluetooth adapter by default. There are many great tutorials to get this working like this one here.

_images/vm-0.png

Steps you can take:

  1. Disable Bluetooth Adapter on Host OS

  2. Launch Guest OS

  3. Enable Bluetooth Adapter on Host OS

  4. Enable Bluetooth Adapter in the usb device list (Guest OS): Devices->usb->check my device

You may also need to install the VirtualBox extension Pack or similar support software, see more information here.

MbientLab is not responsible for VM support. Please consult the forum for the appropriate VM software you are using if you run into issues.

Internet

You also need to make sure you have internet access. The quickest way to test this is to use ping in the terminal:

>>> ping www.google.com

Also check with:

>>> ip address show
>>> ip link show
_images/ubuntu-2.png

If you are having trouble, you can Google “How to connect to the internet on Ubuntu” or similar. There are many options to connect to the internet including wireless and LAN; we quickly highlight them below.

You can troubleshoot through the Ubuntu Network manager. If your local network connection isn’t working, ensure the Enable Networking and Enable Wi-Fi options are selected here in the menu:

_images/ubuntu-11.png

Connect to a Wireless Network

If you have a wireless-enabled computer running the Ubuntu operating system, you can connect to a nearby wireless network to get to the internet. To do this:

  1. Open the System Menu on the right side of the top bar.

  2. Click on Wi-Fi Not Connected to expand the menu.

  3. Click on Select Network.

  4. Look through the names of the nearby networks. Select the one you want. If you don’t see the name of the network you want, click More to see additional networks. If you still don’t see the network you want, it may be hidden or you may be out of range.

  5. Enter the password for the network and click Connect.

_images/ubuntu-26.jpeg

Configure to a Wired Network

To set up most wired network connections, all you need to do is plug in a network cable. The wired network icon (settings) is displayed on the top bar with three dots while the connection is being established. The dots disappear when you are connected.

If this does not happen, you should first of all make sure that your network cable is plugged in. One end of the cable should be plugged into the rectangular Ethernet (network) port on your computer, and the other end should be plugged into a switch, router, network wall socket or similar (depending on the network setup you have). Sometimes, a light beside the Ethernet port will indicate that it is plugged in and active.

If you are still not connected, your network may not support automatic setup (DHCP). In this case you will have to configure it manually. Please consult the appropriate documentation.

_images/ubuntu-27.png

Install Node

There are many ways to install node so choose wisely.

Install Node.js using Ubuntu official repository:

>>> sudo apt install nodejs

Install Node.js using NodeSouce repository:

>>> curl -sL https://deb.nodesource.com/setup_10.x | sudo -E bash –
>>> sudo apt-get install nodejs

Also you can pick which version you want:

Node.js v12.x:

>>> curl -sL https://deb.nodesource.com/setup_12.x | sudo -E bash -
>>> sudo apt-get install -y nodejs

Node.js v10.x:

>>> curl -sL https://deb.nodesource.com/setup_10.x | sudo -E bash -
>>> sudo apt-get install -y nodejs

Note

It is up to you to decide which version of node you want to use with some Googlefu.

To compile and install native addons from npm you may also need to install build tools:

>>> sudo apt-get install -y build-essential
>>> sudo apt-get install npm
>>> sudo apt-get update
>>> sudo apt-get upgrade

Check with:

>>> node -v
>>> npm -v
_images/ubuntu-25.png

Dependencies

The metawear libraries depend on Noble which has further dependencies.

Install Dev tools

These are nice to have tools as well as the latest bluetooth packages:

>>> sudo apt-get install build-essential
>>> sudo apt-get install bluez
>>> sudo apt-get install libboost-all-dev
>>> sudo apt-get install libbluetooth-dev

or

>>> sudo apt-get install bluetooth bluez libbluetooth-dev libudev-dev
_images/ubuntu-19.png

You may also need:

>>> sudo apt-get install libusb-dev
>>> sudo apt-get install libudev-dev

Install Git

Git is a distributed version-control system for tracking changes in source code during software development. It is designed for coordinating work among programmers, but it can be used to track changes in any set of files.

Git is nice to have if you are going to fork our repository or create your own. You can learn more about it with some Googlefu.

>>> sudo apt-get install git-core

Check that everything works:

>>> git --version

MetaWear

MetaWear and noble are available on the node package manager. Simply run the command:

>>> npm install metawear

Upgrade MetaWear

To check if any module in a project is ‘old’ run:

>>> npm outdated

‘outdated’ will check every module defined in package.json and see if there is a newer version in the NPM registry.

To update all dependencies, if you are confident this is desirable:

>>> npm update

To update a single dependency such as metawear:

>>> npm update metawear

Check Noble

Our Javascript APIs are built on the Noble Bluetooth libraries (A Node.js BLE central module). They should automatically be installed with the metawear package.

If they are not, simply run:

>>> npm install noble

API Code Repository

Head over to our Javascript Github page: https://github.com/mbientlab/MetaWear-SDK-JavaScript

You can clone the repository or simply download as a ZIP file:

>>> git clone --recursive https://github.com/mbientlab/MetaWear-SDK-JavaScript
_images/ubuntu-22.png

Then run install:

>>> npm install
_images/ubuntu-21.png

This should install all of the dependencies for you. If there are any issues, you can download individual packages (see package.json).

Usage

Play with the additional example scripts to get familiar with our JS SDK and don’t forget to refer to our developer documentation.

Simply install the NPM module:

>>> npm install metawear

This will compile our CPP libraries and may take some time.

To use, simply require the metawear package:

var MetaWear = require('metawear');

Discover the first MetaWear device seen:

MetaWear.discover(function (device) { ... }

Or a specific MAC address:

MetaWear.discoverByAddress('cb:7d:c5:b0:20:8f', function(device) { ... }

There are other options too, documented in Noble Device.

After that, you must connect to the device:

device.connectAndSetUp(function (error) { ... }

At this point you can call any of the MetaWear SDK’s, for example, you can blink the LED green:

var pattern = new MetaWear.LedPattern();
MetaWear.mbl_mw_led_load_preset_pattern(pattern.ref(), MetaWear.LedPreset.BLINK);
MetaWear.mbl_mw_led_write_pattern(device.board, pattern.ref(), MetaWear.LedColor.GREEN);
MetaWear.mbl_mw_led_play(device.board);

Complete Example:

var MetaWear = require('metawear');

MetaWear.discover(function (device) {
    device.connectAndSetUp(function (error) {
            var pattern = new MetaWear.LedPattern();
            MetaWear.mbl_mw_led_load_preset_pattern(pattern.ref(), MetaWear.LedPreset.BLINK);
            MetaWear.mbl_mw_led_write_pattern(device.board, pattern.ref(), MetaWear.LedColor.GREEN);
            MetaWear.mbl_mw_led_play(device.board);
            // After 5 seconds we reset the board to clear the LED, when we receive
            // a disconnect notice we know the reset is complete, so exit the program
            setTimeout(function () {
                device.on('disconnect', function () {
                        process.exit(0);
                });
                MetaWear.mbl_mw_debug_reset(device.board);
            }, 5000);
    });
});

First Script

You can now navigate to the examples folder and run any example using the command:

>>> node led.js

Modify the commented out section of the JS file and add the specific MAC address of your MetaSensor.

_images/ubuntu-23.png

Run with sudo because of Noble:

>>> sudo node led.js
_images/ubuntu-24.png

The LED example will cause the led to blink green a few times. Run the other examples in the examples directory and build on top of them.

If you run into any issues, try:

>>> npm rebuild

Here’s a look at our APIs in Javascript that wrap around our C++ library.

Connect

First create a MblMwBtleConnection and then call mbl_mw_metawearboard_create to instantiate a MblMwMetaWearBoard struct.

After you have instantiated a MblMwMetaWearBoard, you then need to initialize its internal state by calling mbl_mw_metawearboard_initialize. Initializing can take a few seconds and will asynchronously alert the caller when it is finished.

If initialization succeeded, MBL_MW_STATUS_OK will be passed to the callback function, otherwise a non-zero value will be returned instead signalling the task failed. You can check if a MblMwMetaWearBoard has been initialized by calling mbl_mw_metawearboard_is_initialized.

When you use our Javascript API, MetaWear is the central class of the MetaWear API. It contains methods for connecting, disconnecting, saving and restoring state. We have wrapped around all these C++ calls so that all you have to do is import MetaWear and call the connect() or connectAndSetUp() functions respectively:

var MetaWear = require('metawear');

// This will connect to the MetaSensor with the specific MAC address
//MetaWear.discoverByAddress('cb:7d:c5:b0:20:8f', function(device) { ... }
// This will connect to the closest MetaSensor
MetaWear.discover(function (device) {
    console.log('discovered ' + device.address); //where address is MAC address of MetaSensor
    device.connectAndSetUp(function (error) {
        if (error) {
            console.log(error);
            process.exit(1);
        }
        console.log('connected ' + device.address);
    });
});

Disconnect

In the C++ library, you are responsible for telling the SDK that a bluetooth connection is lost (depending you which Bluetooth library you use).

The C++ APIs use the on_disconnect field to pass a function pointer to the Bluetooth LE wrapper for handling disconnect events.

For Javascript, we use Noble as the Bluetooth library.

We created the function disconnect() which can be called to disconnect the board. The C++ callback function on_disconnect() can be used to manage disconnect events.

var MetaWear = require('metawear');
...
device.on('disconnect', function () {
      console.log('we got disconnected!');
});
...
device.disconnect(function (error) {
      console.log('disconnect call finished');
});

Reset

If your board is stuck in a bad state or needs to be reset, there are a few steps and functions you should call to throughly reset your board:

MetaWear.discover(function (device) {
    console.log('discovered ' + device.address);
    device.connectAndSetUp(function (error) {
        console.log('connected ' + device.address);
        // Stops data logging
        MetaWear.mbl_mw_logging_stop(device.board);
        // Clear the logger of saved entries
        MetaWear.mbl_mw_logging_clear_entries(device.board)
        // Remove all macros on the flash memory
        MetaWear.mbl_mw_macro_erase_all(device.board);
        // Restarts the board after performing garbage collection
        MetaWear.mbl_mw_debug_reset(device.board);
        device.disconnect(function (error) {
            console.log('disconnect call finished');
        });
    });
});

You can take time to look at what each call does in the C++ documentation yourself.

Data

Data signals are an abstract representation of data producers. The API treats them as an event that contains data and represents them with the MblMwDataSignal struct.

They can be safely typecasted to an MblMwEvent.

Signal data is encapsulated by the MblMwData struct. The struct contains a:

  • Timestamp of when the data was created

  • Pointer to the data

  • Data type id indicating how to cast the pointer

An enumeration of data types is defined by the MblMwDataTypeId enum and structs wrapping non basic data types are defined in the types.h header file.

#include "metawear/core/data.h"
#include <chrono>
#include <iomanip>

using std::chrono::duration_cast;
using std::chrono::milliseconds;
using std::chrono::system_clock;
using std::chrono::time_point;

void data_printer(void* context, const MblMwData* data) {
    // Print data as 2 digit hex values
    uint8_t* data_bytes = (uint8_t*) data->value;
    string bytes_str("[");
    char buffer[5];
    for (uint8_t i = 0; i < data->length; i++) {
        if (i) {
            bytes_str += ", ";
        }
        sprintf(buffer, "0x%02x", data_bytes[i]);
        bytes_str += buffer;
    }
    bytes_str += "]";

    // Format time as YYYYMMDD-HH:MM:SS.LLL
    time_point<system_clock> then(milliseconds(data->epoch));
    auto time_c = system_clock::to_time_t(then);
    auto rem_ms= data->epoch % 1000;

    cout << "{timestamp: " << put_time(localtime(&time_c), "%Y%m%d-%T") << "." << rem_ms << ", "
        << "type_id: " << data->type_id << ", "
        << "bytes: " << bytes_str.c_str() << "}"
        << endl;
}

Let’s take a look at the most common MblMwCartesianFloat data type. Angular velocity from the Gyropscope is represented by the MblMwCartesianFloat struct and is in units of degrees per second. The x, y, and z fields contain the angular velocity of the spin around that axis.

For the Python and Javascript APIs, you cast the type when you subscribe to the signal. The type FnVoid_VoidP_DataP represents the MblMwCartesianFloat type.

Don’t bother too much with the rest of the code, we will look into it in more details in the rest of this tutorial. Concentrate on the different data types that can come from our sensors and how we cast them:

function startAccelStream(device) {
  device.connectAndSetUp(function (error) {
    // Get the gyroscope signal
    var rotSignal = MetaWear..mbl_mw_gyro_bmi160_get_rotation_data_signal(device.board);

    // Subscribe to it and create the callback
    MetaWear.mbl_mw_datasignal_subscribe(rotSignal, ref.NULL, MetaWear.FnVoid_VoidP_DataP.toPointer(function gotTimer(context, dataPtr) {
      // Callback function to parse the gyro data
      var data = dataPtr.deref();
      var pt = data.parseValue();
      console.log(pt.x, pt.y, pt.z);
    }));

    // Enable the gyroscope
    MetaWear.mbl_gyro_bmi160_enable_rotation_sampling(device.board);
    MetaWear.mbl_mw_gyro_bmi160_start(device.board);

    // Stop after 5 seconds
    setTimeout(function () {
      // Disable the gyroscope
      MetaWear.mbl_mw_gyro_bmi160_stop(device.board);
      MetaWear.mbl_mw_gyro_bmi160_disable_rotation_sampling(device.board);
      // Unsubscribe to it
      MetaWear.mbl_mw_datasignal_unsubscribe(accSignal);
      MetaWear.mbl_mw_debug_disconnect(device.board);
    }, 5000);
  });
}

You can take a look at our swift, javascript and python binding files for all the available data types. The binding file locations are in the next section.

Bindings

The binding files that bridge the C++ to the Javascript APIs are particularly important.

They describe all the different data types, sensor classes, settings and more:

Language

Bindings File

Javascript:

cbindings.js

The bindings are very useful and you should have them handy in the language of your choice.

Streaming

You can stream sensor data continuously from any of the digital sensors on board including the magnetomer, gyroscope, accelerometer, pressure, humidity and light sensor.

When you do so, you need to setup the sensor with the frequency interval of the desired data (sampling frequency).

You need to lookup the capabilities and setup requirements of that particular sensor and write your code accordingly. For example, the accelerometer might need the resolution to be set at +/-4g and the sample rate at 25Hz.

To stream data live from your MetaSensor board, call mbl_mw_datasignal_subscribe with the desired data signal and include a callback function for handling the received data.

Terminating the live stream is done by calling mbl_mw_datasignal_unsubscribe . Don’t forget to turn of the sensor as well!

Here is an example to stream accelerometer data:

function startAccelStream(device) {
    device.connectAndSetUp(function (error) {
        // Set the max range of the accelerometer
        MetaWear.mbl_mw_acc_set_range(device.board, 8.0);
        MetaWear.mbl_mw_acc_write_acceleration_config(device.board);

        // Get the acc signal
        var accSignal = MetaWear.mbl_mw_acc_get_acceleration_data_signal(device.board);

        // Subscribe to it and create the callback function
        MetaWear.mbl_mw_datasignal_subscribe(accSignal, ref.NULL, MetaWear.FnVoid_VoidP_DataP.toPointer(function gotTimer(context, dataPtr) {
            // Callback function to parse the acc data
            var data = dataPtr.deref();
            var pt = data.parseValue();
            console.log(pt.x, pt.y, pt.z);
        }));
        // Enable and start the acc
        MetaWear.mbl_mw_acc_enable_acceleration_sampling(device.board);
        MetaWear.mbl_mw_acc_start(device.board);

        // Stop after 5 seconds
        setTimeout(function () {
            // Stop the stream and disable the acc
            MetaWear.mbl_mw_acc_stop(device.board);
            MetaWear.mbl_mw_acc_disable_acceleration_sampling(device.board);
            MetaWear.mbl_mw_datasignal_unsubscribe(accSignal);
            MetaWear.mbl_mw_debug_disconnect(device.board);
        }, 5000);
    });
}

Logging

Alternatively, data can be logged and retrieved at a later time. This applies to the same sensors including the magnetomer, gyroscope, accelerometer, pressure, humidity and light sensor.

This takes a bit more effort because your code will need to know what data is being logged so you are responsible for saving logger IDs and retrieving them when you download the sensor data from the MetaSensor internal memory.

You also need to handle the callbacks as the data is downloaded from the MetaSensor memory.

Warning

MetaSensors have a finite memory and when you run out of memory, new entries will over-write old entries. You can actually change this setting in the mbl_mw_logging_start call.

Note

Please see our calculator function to see how many sensor data entries and at what frequency will the memory of the MetaSensor become full.

Loggers record data from a data signal and are represented by the MblMwDataLogger struct. You create an MblMwDataLogger object by calling mbl_mw_datasignal_log with the data signal you want to log. If successful, the callback function will be executed with a MblMwDataLogger* pointer and a null pointer if it failed.

MblMwDataLogger objects only interact with the specific data signal, they do not control the logging features.

MblMwDataLogger objects are identified by a numerical id; you can retrieve the id by calling mbl_mw_logger_get_id. The id is used to retrieve existing loggers from the API with the mbl_mw_logger_lookup_id function and is important when you have multiple loggers running.

Like a data signal, you can subscribe to an MblMwDataLogger to process the downloaded data. Call mbl_mw_logger_subscribe to attach a callback function to the MblMwDataLogger which handles all received data.

After you have setup the signal loggers, start the logger by calling mbl_mw_logging_start.

When you are ready to retrieve the data, execute mbl_mw_logging_download . You will need to pass in a MblMwLogDownloadHandler struct to handle notifications from the logger.

We have updated our streaming accelerometer data example to log data this time:

var acceLogger = null;

function startLogging(device, callback) {
    // Set up the acc functionality
    MetaWear.mbl_mw_acc_set_odr(device.board, 50.0);
    MetaWear.mbl_mw_acc_set_range(device.board, 16.0);
    MetaWear.mbl_mw_acc_write_acceleration_config(device.board);
    // Create a logger
    var accSignal = MetaWear.mbl_mw_acc_get_acceleration_data_signal(device.board);
    MetaWear.mbl_mw_datasignal_log(accSignal, ref.NULL, MetaWear.FnVoid_VoidP_DataLoggerP.toPointer(function (context, logger) {
        accelLogger = logger;
        callback(logger.address() ? null : new Error('failed to start logging accel'));
    }));
    // Start logging and enable the acc
    MetaWear.mbl_mw_logging_start(device.board, 0);
    MetaWear.mbl_mw_acc_enable_acceleration_sampling(device.board);
    MetaWear.mbl_mw_acc_start(device.board);
}

function downloadLog(device, callback) {
    // Disable accel
    MetaWear.mbl_mw_acc_stop(device.board);
    MetaWear.mbl_mw_acc_disable_acceleration_sampling(device.board);
    // Stop logging
    MetaWear.mbl_mw_logging_stop(device.board);
    // Setup handler for accel data points and create callback to parse incoming logger data
    MetaWear.mbl_mw_logger_subscribe(accelLogger, ref.NULL, MetaWear.FnVoid_VoidP_DataP.toPointer(function onSignal(context, dataPtr) {
        var data = dataPtr.deref();
        var pt = data.parseValue();
        console.log(data.epoch + ' ' + pt.x + ',' + pt.y + ',' + pt.z);
    }));
    // Setup the handlers for events during the download
    var downloadHandler = new MetaWear.LogDownloadHandler();
    // Logger progress callback
    downloadHandler.received_progress_update = MetaWear.FnVoid_VoidP_UInt_UInt.toPointer(function onSignal(context, entriesLeft, totalEntries) {
        console.log('received_progress_update entriesLeft:' + entriesLeft + ' totalEntries:' + totalEntries);
    });
    // Logger unknown entry callback
    downloadHandler.received_unknown_entry = MetaWear.FnVoid_VoidP_UByte_Long_UByteP_UByte.toPointer(function onSignal(context, id, epoch, data, length) {
        console.log('received_unknown_entry');
    });
    // Logger bad entry callback
    downloadHandler.received_unhandled_entry = MetaWear.FnVoid_VoidP_DataP.toPointer(function onSignal(context, dataPtr) {
        var data = dataPtr.deref();
        var dataPoint = data.parseValue();
        console.log('received_unhandled_entry: ' + dataPoint);
    });
    // Actually start the log download, this will cause all the handlers we setup to be invoked
    MetaWear.mbl_mw_logging_download(device.board, 20, downloadHandler.ref());
}

Reading

Analog sensors such as the temperature sensor or the on-board push button cannot be read continuously; they will only send data when they receive a command to do so. You can either read them once OR use a timer loop to read them multiple times.

You can also read the pressure, light, and humidity sensors once if you wish.

Data signals that represent this type of data source are called readable signals. You can check if a data signal is readable by calling mbl_mw_datasignal_is_readable.

The read command is issued by calling mbl_mw_datasignal_read or mbl_mw_datasignal_read_with_parameters.

When using readable signals, you must decide up front if the data will be streamed or logged before interacting with it. That is, you should either have subscribed to or setup a logger for a readable signal before reading it.

Note

This is a great way to get very low sampling rates for certain sensors.

We will look at an example for the temperature sensor. Temperature reads are manually triggered by calling mbl_mw_datasignal_read. The data is represented as a float and is in units of Celsius.

Let’s do a one time read:

// Get temp signal
var tempSignal = MetaWear.mbl_mw_multi_chnl_temp_get_temperature_data_signal(device.board, MetaWearRProChannel.ON_BOARD_THERMISTOR)

// Subscribe to it
MetaWear.mbl_mw_datasignal_subscribe(tempSignal, ref.NULL, MetaWear.FnVoid_VoidP_DataP.toPointer(function gotTemp(context, dataPtr) {
    var data = dataPtr.deref();
    var pt = data.parseValue();
    console.log(pt);
}));

// Read it
MetaWear.mbl_mw_datasignal_read(temp_signal)

See the Timer section below to understand how we can do continuous reads of some of the analog sensors and peripherals.

Writing

Sometimes you want to send commands to the board. You can turn on the LED, make the board vibrate if it has a coin vibration motor on it, or send GPIO, I2C or SPI commands.

Let’s take a look at the LED since all boards come with an on-board RGD LED.

An led pattern is represented by the MblMwLedPattern struct. Users can configure every part of the pulse or load one of the preset patterns using the mbl_mw_led_load_preset_pattern function. Patterns are written to the board with the mbl_mw_led_write_pattern function.

After writing patterns to the board, you can playback the pattern, similar to playing a music track, using mbl_mw_led_play, mbl_mw_led_pause, and mbl_mw_led_stop.

To remove patterns, call mbl_mw_led_stop_and_clear; this will also stop pattern playback.

// Create a pattern
var pattern = new MetaWear.LedPattern();
...
// Load the LED with the pattern
MetaWear.mbl_mw_led_load_preset_pattern(pattern.ref(), MetaWear.LedPreset.BLINK);
MetaWear.mbl_mw_led_write_pattern(device.board, pattern.ref(), MetaWear.LedColor.GREEN);
// Play the pattern
MetaWear.mbl_mw_led_play(device.board);
...
MetaWear.mbl_mw_led_stop_and_clear(device.board)

Events

An event is an asynchronous notification from the MetaWear board represented in the C++ API by the MblMwEvent struct.

The board can be programmed to execute MetaWear commands in response to an event firing. To start recording commands, call mbl_mw_event_record_commands. While in a recording state, all MetaWear functions called will instead be recorded on the board and executed when the event is fired.

To stop recording, call mbl_mw_event_end_record. This function is asynchronous and will alert the caller when it is completed via a callback function. If recording events was successful, MBL_MW_STATUS_OK will be passed into the callback function, otherwise MBL_MW_STATUS_ERROR_TIMEOUT is used.

MetaWear.discover(function (device) {
  device.connectAndSetUp(function (error) {
    // Create an event based on a disconnection
    event= MetaWear.mbl_mw_settings_get_disconnect_event(device.board);
    // Create LED pattern
    let pattern = new MetaWear.LedPattern();
    pattern.repeat_count = 5

    // Start recording commands based on disconnect event:
    MetaWear.mbl_mw_event_record_commands(event);
    // The first command is to write the led pattern
    MetaWear.mbl_mw_led_write_pattern(device.board, pattern.ref(), MetaWear.LedColor.GREEN);
    // The second command is to play the led pattern
    MetaWear.mbl_mw_led_play(device.board);
    // Stop recording commands (everything up until now is going into the MetaSensor memory)
    MetaWear.mbl_mw_event_end_record(timer, ref.NULL, MetaWear.FnVoid_VoidP_VoidP_Int.toPointer((ctx, ptr, status) => {
        resolve(null);
    }))
  });
});

Timer

A MetaWear timer can be thought of as an event that is fired at fixed intervals. These timers are represented by the MblMwTimer struct and can be safely typcased to a MblMwEvent struct. Timers can be used to schedule periodic tasks or setup a delayed task execution.

MblMwTimer objects are identified by a numerical id; you can retrieve the id by calling mbl_mw_timer_get_id. The id is used to retrieve existing timers from the API with the mbl_mw_timer_lookup_id function.

Before you can schedule tasks, you first need to create a timer, by calling either mbl_mw_timer_create or mbl_mw_timer_create_indefinite. These functions are asynchronous and will pass a pointer to the caller when the timer is created. When you have a valid MblMwTimer, you can use the command recording system outlined in Events section to program the board to respond to the periodic events. Upon recording timer task commands, call mbl_mw_timer_start to start the timer.

When you are done using a timer, you can remove it with mbl_mw_timer_remove.

async function startLogging(device, callback) {
  // Get temp signal
  console.log('Get temp signal');
  var tempSignal = MetaWear.mbl_mw_multi_chnl_temp_get_temperature_data_signal(device.board, 1);
  // Create a timer
  console.log('Create timer');
  var promise = new Promise((resolve, reject) => {
    var timer = MetaWear.mbl_mw_timer_create_indefinite(device.board, 1000, 0, ref.NULL, MetaWear.FnVoid_VoidP_TimerP.toPointer(function onSignal(context, timer) {
      console.log(context);
      console.log('Timer created');
      console.log(timer);
      resolve(timer);
    }));
  });
  tempTimer = await promise;
  console.log(tempTimer);
  // Create event based on timer and record as a command
  console.log('Record command');
  MetaWear.mbl_mw_event_record_commands(tempTimer);
  console.log('Command to read temp signal');
  MetaWear.mbl_mw_datasignal_read(tempSignal);
  console.log('End record command');
  promise = new Promise((resolve, reject) => {
    var rec = MetaWear.mbl_mw_event_end_record(tempTimer, ref.NULL, MetaWear.FnVoid_VoidP_EventP_Int.toPointer(function onSignal(context, dataPtr, lstatus) {
      console.log('Command created');
      resolve(lstatus);
    }));
  });
  let rec = await promise;
  // Start timer
  MetaWear.mbl_mw_timer_start(tempTimer);
  // Create a logger
  MetaWear.mbl_mw_datasignal_log(tempSignal, ref.NULL, MetaWear.FnVoid_VoidP_DataLoggerP.toPointer(function (context, logger) {
    tempLogger = logger;
    callback(logger.address() ? null : new Error('failed to start logging temp'));
  }));
  // Start logger
  MetaWear.mbl_mw_logging_start(device.board, 0);
}

Component Signals

Some signals, such as the acceleration datasignal, are composed of multiple values. While you can interact with them as a whole, sometimes it is more convenient to only use individual values.

To access the component values, call mbl_mw_datasignal_get_component with the signal and an index represnting which component to retrieve. If a signal is single valued, the function will return null.

console.log('Set up acc signal.');
let acc = MetaWear.mbl_mw_acc_get_acceleration_data_signal(device.board);

console.log('Get x component of acc.');
let acc_x = MetaWear.mbl_mw_datasignal_get_component(acc, 0); //cbindings.Const.ACC_ACCEL_X_AXIS_INDEX);

console.log('Set up stream.');
MetaWear.mbl_mw_datasignal_subscribe(acc_x, ref.NULL, MetaWear.FnVoid_VoidP_DataP.toPointer((ctx, pointer) => {
    var data = pointer.deref();
    var value = data.parseValue();
    console.log('epoch: ' + data.epoch + ' acc x: ' + value);
}))

Sensor Fusion

The sensor_fusion.h header file interfaces with the sensor fusion algorithm running on MetaMotion boards. When using the sensor fusion algorithm, it is important that you do not simultaneously use the Accelerometer, Gyro, and Magnetometer modules; the algorithm configures those sensors internally based on the selected fusion mode.

To activate the sensor fusion algorithm, first set the fusion mode and data ranges, then subscribe to and enable the desired output data, and finally, call mbl_mw_sensor_fusion_start.

The sensor fusion algorithm has 4 fusion modes, listed in the below table:

Mode

Description

NDoF

Calculates absolute orientation from accelerometer, gyro, and magnetometer

IMUPlus

Calculates relative orientation in space from accelerometer and gyro data

Compass

Determines geographic direction from th Earth’s magnetic field

M4G

Similar to IMUPlus except rotation is detected with the magnetometer

The mode is set with mbl_mw_sensor_fusion_set_mode and written to the board by calling mbl_mw_sensor_fusion_write_config. Before writing the configuration, you can also set the acceleration and rotation ranges of the accelerometer and gyroscope respectively.

// Setup gyro, acc, and sensor fusion settings
MetaWear.mbl_mw_sensor_fusion_set_mode(device.board, 1); //SensorFusionMode.NDOF);
MetaWear.mbl_mw_sensor_fusion_set_acc_range(device.board, 2 ); //SensorFusionAccRange._8G)
MetaWear.mbl_mw_sensor_fusion_set_gyro_range(device.board, 0); //SensorFusionGyroRange._2000DPS)
MetaWear.mbl_mw_sensor_fusion_write_config(device.board);

console.log('Get quat signal.');
let signal = MetaWear.mbl_mw_sensor_fusion_get_data_signal(device.board, 3); //QUATERNION

console.log('Set up stream.');
MetaWear.mbl_mw_datasignal_subscribe(signal, ref.NULL, MetaWear.FnVoid_VoidP_DataP.toPointer((ctx, pointer) => {
var data = pointer.deref();
var value = data.parseValue();
console.log('epoch: ' + data.epoch + ' quat: ' + value.x + ' ' + value.y + ' ' + value.z);
}));

console.log('Start sensor fusion.');
MetaWear.mbl_mw_sensor_fusion_enable_data(device.board, 3); //QUATERNION
MetaWear.mbl_mw_sensor_fusion_start(device.board);

What’s important is that you look at all the capabilities and settings of each sensor.

For example, for the sensor fusion to work, you need to pick the MODE, the OUTPUT TYPE, the GYROSCOPE RANGE, and the ACCELEROMETER RANGE. These are things you need to think about before you start coding.

Learn more here: https://mbientlab.com/cppdocs/latest/sensor_fusion.html

Data Processing

Data signals can be fed through the on-board data processors to filter and/or transform the data in the firmware.

By performing computations on the MetaWear side, you can reduce the amount of data that is sent over the radio and the amount of postprocessing that is done on your mobile device.

Data processors can also be chained together to perform more complex tasks, such as using the rss, average, and threshold processors to determine if the board is in freefall based on the XYZ acceleration data.

Here is an example of the rss processor. RSS which stands for root sum square is a statistical method of dealing with a series of values where each value is squared, the sum of these squares is calculated and the square root of that sum is then taken:

// start to setup rms->avg->thresh->log chain
console.log('Get acc signal');
var acc = MetaWear.mbl_mw_acc_get_acceleration_data_signal(device.board);

// create RSS
console.log('Create RSS');
let promise = new Promise((resolve, reject) => {
  var rms = MetaWear.mbl_mw_dataprocessor_rss_create(acc, ref.NULL, MetaWear.FnVoid_VoidP_DataProcessorP.toPointer(function onSignal(context, dataPtr) {
    console.log('RSS Created');
    resolve(dataPtr);
  }));
});
let rms = await promise;

Data processors are functions in the firmware that filter or transform sensor data and are represented by the MblMwDataProcessor struct.

In the C++ API, data processors can be thought of as a data signal whose data is produced by the on-board data processor. As such, a MblMwDataProcessor can be safely typecasted to a MblMwDataSignal.

This section will focus on the MblMwDataProcessor struct. Data processors are identified by a unique numerical ID; you can retrieve this id by calling mbl_mw_dataprocessor_get_id. The data processor ID is used to lookup a previously created MblMwDataProcessor object with the mbl_mw_dataprocessor_lookup_id function.

Some processors have an internal state that can be read and modified; the internal state is treated as a readable MblMwDataSignal.

#include "metawear/core/datasignal.h"
#include "metawear/processor/dataprocessor.h"

// Assume input processor is a Buffer processor
void subscribe_state_signal(MblMwDataProcessor* buffer_processor) {
    auto state_signal = mbl_mw_dataprocessor_get_state_data_signal(buffer_processor);
    mbl_mw_datasignal_subscribe(state_signal, nullptr, data_printer);
    mbl_mw_datasignal_read(state_signal);
}

Removing a processor is handled by calling mbl_mw_dataprocessor_remove. When a processor is removed, all processors that consume its output will also be removed.

#include "metawear/core/datasignal_fwd.h"
#include "metawear/processor/dataprocessor.h"
#include "metawear/processor/math.h"

void remove_processors(MblMwDataSignal* temp_signal) {
    static MblMwDataProcessor* first_processor= nullptr;

    static auto add_32_created = [](void* context, MblMwDataProcessor* processor) -> void {
        // Removes all 3 processors in the chain
        mbl_mw_dataprocessor_remove(first_processor);
    };
    static auto div_10_created = [](void* context, MblMwDataProcessor* processor) -> void {
        mbl_mw_dataprocessor_math_create((MblMwDataSignal*) processor, MBL_MW_MATH_OP_ADD, 32.f,
                context, add_32_created);
    };
    static auto mul_18_created = [](void* context, MblMwDataProcessor* processor) -> void {
        first_processor = processor;
        mbl_mw_dataprocessor_math_create((MblMwDataSignal*) processor, MBL_MW_MATH_OP_DIVIDE,
                10.f, context, div_10_created);
    };
    mbl_mw_dataprocessor_math_create(temp_signal, MBL_MW_MATH_OP_MULTIPLY, 18.f, nullptr, mul_18_created);
}

There are many more processors which are detailed here.

Multiple sensors

console.log('Get gyro and acc signal');
let acc = MetaWear.mbl_mw_acc_get_acceleration_data_signal(device.board)
let gyro = MetaWear.mbl_mw_gyro_bmi160_get_rotation_data_signal(device.board)

console.log('Set up stream.')
MetaWear.mbl_mw_datasignal_subscribe(acc, ref.NULL, MetaWear.FnVoid_VoidP_DataP.toPointer((ctx, pointer) => {
    var data = pointer.deref();
    var value = data.parseValue();
    console.log('epoch: ' + data.epoch + ' acc: ' + value.x + ' ' + value.y + ' ' + value.z)
}))
MetaWear.mbl_mw_datasignal_subscribe(gyro, ref.NULL, MetaWear.FnVoid_VoidP_DataP.toPointer((ctx, pointer) => {
    var data = pointer.deref();
    var value = data.parseValue();
    console.log('epoch: ' + data.epoch + ' gyro: ' + value.x + ' ' + value.y + ' ' + value.z)
}))

console.log('Start accelerometer.')
MetaWear.mbl_mw_acc_enable_acceleration_sampling(device.board)
MetaWear.mbl_mw_acc_start(device.board)

console.log('Start gyroscope.')
MetaWear.mbl_mw_gyro_bmi160_enable_rotation_sampling(device.board)
MetaWear.mbl_mw_gyro_bmi160_start(device.board)

Multiple sensors with Fuser

The fuser is one of our data processors.

The fuser processor combines data from multiple sensors into 1 message. When fusing multiple data sources, ensure that they are sampling at the same frequency, or at the very least, integer multiples of the fastest frequency. Data sources sampling at the lower frequencies will repeat the last received value.

Unlike the other data sources, fuser data is represented as an MblMwData array, which is indexed based on the order of the data signals passed into mbl_mw_dataprocessor_fuser_create.

let acc = MetaWear.mbl_mw_acc_get_acceleration_data_signal(device.board)
let gyro = MetaWear.mbl_mw_gyro_bmi160_get_rotation_data_signal(device.board)

let fuser = await new Promise((resolve, reject) => {
    console.log("creating fuser")
    MetaWear.mbl_mw_dataprocessor_fuser_create(acc, new MetaWear.ArrayDataSignalP([gyro]), 1, ref.NULL, MetaWear.FnVoid_VoidP_DataProcessorP.toPointer((ctx, pointer) => {
      if (!pointer) {
        reject("Failed to create fuser")
      } else {
        resolve(pointer);
      }
    }))
    console.log("fuser created?")
})

MetaWear.mbl_mw_datasignal_subscribe(fuser, ref.NULL, MetaWear.FnVoid_VoidP_DataP.toPointer((ctx, pointer) => {
    var data = pointer.deref();
    var values = data.parseValue({'nElem': 2});

    let acc = values[0]
    let gyro = values[1]

    console.log(`acc: (${acc.x},${acc.y},${acc.z}), gyro; (${gyro.x},${gyro.y},${gyro.z})`)
}))

MetaWear.mbl_mw_gyro_bmi160_enable_rotation_sampling(device.board)
MetaWear.mbl_mw_acc_enable_acceleration_sampling(device.board)

MetaWear.mbl_mw_gyro_bmi160_start(device.board)
MetaWear.mbl_mw_acc_start(device.board)

Dongles

If you buy a Bluetooth dongle or you get one from our store, go ahead and plug it in.

It will either get recognized by your system immediately or it won’t. A few ways to check:

lsusb is a utility for displaying information about USB buses in the system and the devices connected to them. Run the command:

>>> lsusb

This should at least show that you have the Dongle plugged in.

Now you need to know if it is recognized by your OS as a bluetooth controller.

You can do this using hcitool, which is used to configure Bluetooth connections and send special commands to Bluetooth devices. You can also use hciconfig which is used to configure Bluetooth devices:

>>> sudo hcitool dev

or

>>> sudo hciconfig

If you installed bluetooth utils earlier, you can also use bluetoothctl. Bluetoothctl is the main command for configuring Bluetooth devices on Linux:

>>> bluetoothctl
    list

You can look into each tool and how to use them with a little Googlefu. The important thing here is to make sure that your dongle is plugged in, working, and usable as a bluetooth controller.

If your bluetooth dongle is NOT recognized by your system; follow these steps:

  1. Plug in the dongle.

  2. Update the OS:

    >>> sudo apt update
    >>> sudo apt upgrade
    
  3. Reboot the machine:

    >>> sudo reboot now
    
_images/python3-13.png

To specify a dongle when using the MetaWear APIs, you need to know the dongle’s MAC address.

In the screenshot above and example below, the dongle MAC address is B8:27:EB:F2:61:2E. The MAC is found using the commands above. Something to note here is that the MAC address of the internal Bluetooth adapter of the RaspberryPi is 00:1A:7D:DA:71:13.

Let’s go ahead and take a look at sending MetaWear API commands through a specific USB-BLE dongle and NOT through the internal adapater of the my PI.

//Multiple Adapters
//hci0 is used by default to override set the NOBLE_HCI_DEVICE_ID environment variable to the interface number.
//Example, specify hci1:
//sudo NOBLE_HCI_DEVICE_ID=1 node <your file>.js

//Reporting all HCI events
//By default noble waits for both the advertisement data and scan response data for each Bluetooth address. If your device does not use scan response the following environment variable can be used to bypass it.
//sudo NOBLE_REPORT_ALL_HCI_EVENTS=1 node <your file>.js

var MetaWear = require('../index')//require('metawear');

// If you know the MAC address, you can uncomment this line
MetaWear.discoverByAddress('f9:b5:f9:81:3f:77', function(device) {
//MetaWear.discover(function (device) {
  device.connectAndSetUp(function (error) {
    var pattern = new MetaWear.LedPattern();
    MetaWear.mbl_mw_led_load_preset_pattern(pattern.ref(), MetaWear.LedPreset.BLINK);
    MetaWear.mbl_mw_led_write_pattern(device.board, pattern.ref(), MetaWear.LedColor.GREEN);
    MetaWear.mbl_mw_led_play(device.board);
    setTimeout(function () {
      device.on('disconnect', function () {
        process.exit(0);
      });
      MetaWear.mbl_mw_debug_reset(device.board);
    }, 5000);
  });
});

Anonymous downloading

Anonymous data signals are a variant of the Logger type used to retrieve logged data from a board that was not programmed by the current host device. Use mbl_mw_metawearboard_create_anonymous_datasignals to sync the host device with the board’s current logger state. If the function fails, a null pointer will be returned and the uint32_t parameter instead corresponds to a status code from the SDK.

Because of the anonymous nature of the object, users will need to rely on an identifier string to determine what kind of data is being passed to each route. Generate the identifier string by calling mbl_mw_logger_generate_identifier for each MblMwDataLogger type and match these values with mbl_mw_anonymous_datasignal_get_identifier.

Warning

Please note that not all loggers are supported.

MetaWear.discover(function (device) {
  console.log('connecting...' + device.address);
  device.connectAndSetUp(function (error) {
    console.log('connected!');
    MetaWear.mbl_mw_metawearboard_create_anonymous_datasignals(device.board, ref.NULL,
      MetaWear.FnVoid_VoidP_MetaWearBoardP_AnonymousDataSignalP_UInt.toPointer(function (context, board, anonymousSignals, size) {
        if (!anonymousSignals) {
          console.log('nothing being logged');
          process.exit(1);
        }
        // Set the size on the array so we can index
        anonymousSignals.length = size;
        var i;
        for (i = 0; i < size; i++) {
          var identifier = MetaWear.mbl_mw_anonymous_datasignal_get_identifier(anonymousSignals[i]);
          MetaWear.mbl_mw_anonymous_datasignal_subscribe(anonymousSignals[i], ref.NULL, MetaWear.FnVoid_VoidP_DataP.toPointer(function onSignal(context, dataPtr) {
            var data = dataPtr.deref();
            var pt = data.parseValue();
            console.log(identifier + ':' + data.epoch + ' ' + JSON.stringify(pt));
          }));
        }
        download(device, function () {
          device.once('disconnect', function (reason) {
            process.exit(0);
          });
          MetaWear.mbl_mw_macro_erase_all(device.board);
          MetaWear.mbl_mw_debug_reset_after_gc(device.board);
          MetaWear.mbl_mw_debug_disconnect(device.board);
        });
      }));
  });
});

function download(device, callback) {
  // Setup the handlers for events during the download
  var downloadHandler = new MetaWear.LogDownloadHandler();
  downloadHandler.received_progress_update = MetaWear.FnVoid_VoidP_UInt_UInt.toPointer(function onSignal(context, entriesLeft, totalEntries) {
    console.log('received_progress_update entriesLeft:' + entriesLeft + ' totalEntries:' + totalEntries);
    if (entriesLeft === 0) {
      callback(null);
    }
  });
  downloadHandler.received_unknown_entry = MetaWear.FnVoid_VoidP_UByte_Long_UByteP_UByte.toPointer(function onSignal(context, id, epoch, data, length) {
    console.log('received_unknown_entry');
  });
  downloadHandler.received_unhandled_entry = MetaWear.FnVoid_VoidP_DataP.toPointer(function onSignal(context, dataPtr) {
    var data = dataPtr.deref();
    var dataPoint = data.parseValue();
    console.log('received_unhandled_entry: ' + dataPoint);
  });
  // Actually start the log download, this will cause all the handlers we setup to be invoked
  MetaWear.mbl_mw_logging_download(device.board, 20, downloadHandler.ref());
}

Macro

The on-board flash memory can also be used to store MetaWear commands instead of sensor data. Recorded commands can be executed any time after being programmed with the functions in macro.h header file.

To record commands:

  1. Call mbl_mw_macro_record to put the API in macro mode

  2. Use the MetaWear commands that you want programmed

  3. Exit macro mode with mbl_mw_macro_end_record

Macros can be set to run on boot by setting the exec_on_boot parameter with a non-zero value.

Erasing macros is done with the mbl_mw_macro_erase_all method. The erase operation will not occur until you disconnect from the board.

console.log('Macro started');
MetaWear.mbl_mw_macro_record(device.board, 1)

console.log('LED');
var pattern = new MetaWear.LedPattern();
MetaWear.mbl_mw_led_load_preset_pattern(pattern.ref(), MetaWear.LedPreset.BLINK);
MetaWear.mbl_mw_led_write_pattern(device.board, pattern.ref(), MetaWear.LedColor.GREEN);
MetaWear.mbl_mw_led_play(device.board);
console.log('END');

var promise = new Promise((resolve, reject) => {
  var macro = MetaWear.mbl_mw_macro_end_record(device.board, ref.NULL, MetaWear.FnVoid_VoidP_Int.toPointer(function onSignal(context, rec) {
    console.log('Macro created');
    console.log(rec);
    resolve(rec);
  }));
});
var rec = await promise;

Next steps

Advanced developers building more complex apps can refer to the Javascript Documentation.