Twilio Sync for IoT and Programmable Wireless on a MultiConnect® Dragonfly™

Today we'll bring Twilio Sync for IoT to 4G using the Arm Mbed Online IDE and a Multi-Tech MultiConnect® Dragonfly™. We'll use the Twilio Device Manager to create a Device Fleet then a connection to Sync. We'll do all of that using Twilio's Programmable Wireless cellular connectivity.

And what are we going to do with all of that power? Blink an LED, of course!

Sync for IoT is currently in Developer Preview, which means access is by invite only. If you'd like to try what you see in these docs, sign up for the developer preview and the team at Twilio will get you onboarded as soon as possible.

Sign Up For (or Sign Into) a Twilio Account

Create a new Twilio account (you can sign up for a free Twilio trial) or sign into an existing Twilio account.

Once logged in, click the Twilio Device Manager link to go to the Sync for IoT console.

Purchase and Activate a Programmable Wireless SIM Card

The code in this Quickstart will work with 4G via Twilio's Programmable Wireless. You can order SIM cards here directly from the Twilio console.

Here's the order of operations to activate a SIM card:

Once your SIM has a rate plan with data enabled insert it into the board's SIM slot. Additionally, attach the cellular antenna to your board.

Deploy a Fleet of MultiConnect® Dragonfly™ Things

Device Fleets are collections of devices, keys or certificates, and configurations of Twilio Sync. You may create many fleets, but each individual fleet will be isolated.

A Default Fleet is already provisioned for you in Sync for IoT. Get started by navigating to it in the Device Management console:

Locating the default Ffleet in the Twilio Console

(You may also deploy and configure a fleet through the Twilio REST API.)

Loading Code Samples...
Language
SDK Version:
  • 5.x
Response Format:
  • json
SDK Version:
  • 7.x
SDK Version:
  • 3.x
SDK Version:
  • 5.x
SDK Version:
  • 6.x
SDK Version:
  • 5.x
Format:
  • JSON
const accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
const authToken = 'your_auth_token';
const Twilio = require('twilio').Twilio;

const client = new Twilio(accountSid, authToken);

client.preview.deployed_devices.fleets
  .create({
    friendlyName: 'My Fleet of Devices',
  })
  .then(response => {
    console.log(response);
  })
  .catch(error => {
    console.log(error);
  });
// Get the Node helper library from https://twilio.com/docs/libraries/csharp
using System;
using System.Collections.Generic;
using Twilio;
using Twilio.Rest.Preview.DeployedDevices;

public class Example
{
    public static void Main(string[] args)
    {
        // Get your Account SID and Auth Token from https://twilio.com/console
        const string accountSid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
        const string authToken = "your_auth_token";
        TwilioClient.Init(accountSid, authToken);

        var fleet = FleetResource.Create(
            friendlyName: "My Fleet of Devices"
        );

        Console.WriteLine(fleet.Sid);
    }
}
<?php
// Get the Node helper library from https://twilio.com/docs/libraries/php
require_once '/path/to/vendor/autoload.php'; // Loads the library

use Twilio\Rest\Client;

// Get your Account SID and Auth Token from https://twilio.com/console
$accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
$authToken = 'your_auth_token';
$client = new Client($accountSid, $authToken);

$fleet = $client->preview->deployedDevices->fleets->create(
  array(
    'friendlyName' => 'My Fleet of Devices'
  )
);

echo $fleet->sid;
# Get the Node helper library from https://twilio.com/docs/libraries/ruby
require 'twilio-ruby'

# Get your Account SID and Auth Token from https://twilio.com/console
account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
auth_token = 'your_auth_token'
client = Twilio::REST::Client.new(account_sid, auth_token)

fleet = client.preview.deployed_devices.fleets.create(
  friendly_name: 'My Fleet of Devices'
)

puts fleet.sid
# Get the Node helper library from https://twilio.com/docs/libraries/python
from twilio.rest import Client

# Get your Account SID and Auth Token from https://twilio.com/console
account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
auth_token = 'your_auth_token'
client = Client(account_sid, auth_token)

fleet = client.preview.deployed_devices.fleets.create(
    friendly_name='My Fleet of Devices')

print(fleet.sid)
// Get the Node helper library from https://twilio.com/docs/libraries/java
import com.twilio.Twilio;
import com.twilio.rest.preview.deployedDevices.Fleet;
import com.twilio.rest.preview.deployedDevices.FleetCreator;

public class Example {
    // Get your Account SID and Auth Token from https://twilio.com/console
    public static final String ACCOUNT_SID = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
    public static final String AUTH_TOKEN = "your_auth_token";

    public static void main(String[] args) {
        Twilio.init(ACCOUNT_SID, AUTH_TOKEN);

        FleetCreator fleetCreator = new FleetCreator();
        Fleet fleet = fleetCreator
                .setFriendlyName("My Fleet of Devices")
                .create();

        System.out.println(fleet.getSid());
    }
}
curl -u 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX:your_auth_token' \
  -X POST https://preview.twilio.com/DeployedDevices/Fleets
{
  "sid": "FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "friendly_name": null,
  "account_sid": "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "default_deployment_sid": "DLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "date_created": "2017-08-14T15:25:45Z",
  "date_updated": "2017-08-14T15:25:45Z",
  "url": "https://preview.twilio.com/DeployedDevices/Fleets/FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "links": {
    "certificates": "https://preview.twilio.com/DeployedDevices/Fleets/FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Certificates",
    "keys": "https://preview.twilio.com/DeployedDevices/Fleets/FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Keys",
    "devices": "https://preview.twilio.com/DeployedDevices/Fleets/FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Devices",
    "deployments": "https://preview.twilio.com/DeployedDevices/Fleets/FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Deployments"
  }
}
Using the API to create a Device Fleet in Sync for IoT.
Create a Device Fleet

Using the API to create a Device Fleet in Sync for IoT.

Let's move next to the Deployment.

Configure the Default Deployment

Twilio provides a default Deployment as well, configuring it upon Fleet creation. The 'Default Deployment' field in your Fleet should look something like this:

A default deployment is automatically provisioned for each new Device Fleet.

Follow the 'Configure the Deployment' link:

Every deployment is configured with a default Service Instance.

Twilio also creates a default Sync Service Instance. Instances are similar to isolated databases. When you make an update on a Sync primitive (such as a Document), the update only affects the named primitive in this Instance.

As before, you can create and configure a Deployment with the API.

Loading Code Samples...
Language
SDK Version:
  • 5.x
Response Format:
  • json
SDK Version:
  • 7.x
SDK Version:
  • 3.x
SDK Version:
  • 5.x
SDK Version:
  • 6.x
SDK Version:
  • 5.x
Format:
  • JSON
const accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
const authToken = 'your_auth_token';
const Twilio = require('twilio').Twilio;

const client = new Twilio(accountSid, authToken);
const fleet = client.preview.deployed_devices.fleets(
  'FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
);

fleet
  .deployments('FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
  .update({
    friendlyName: 'My New Device Deployment',
    syncServiceSid: 'ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
  })
  .then(response => {
    console.log(response);
  })
  .catch(error => {
    console.log(error);
  });
// Get the C# helper library from https://twilio.com/docs/libraries/csharp
using System;
using System.Collections.Generic;
using Twilio;
using Twilio.Rest.Preview.DeployedDevices;

public class Example
{
    public static void Main(string[] args)
    {
        // Get your Account SID and Auth Token from https://twilio.com/console
        const string accountSid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
        const string authToken = "your_auth_token";
        TwilioClient.Init(accountSid, authToken);

        const string deploymentSid = "DLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
        var deployment = DeploymentResource.Update(
            deploymentSid,
            friendlyName: "My New Device Deployment");

        Console.WriteLine(deploymentSid.FriendlyName);
    }
}
<?php
// Get the PHP helper library from https://twilio.com/docs/libraries/php
require_once '/path/to/vendor/autoload.php'; // Loads the library

use Twilio\Rest\Client;

// Get your Account SID and Auth Token from https://twilio.com/console
$accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
$authToken = 'your_auth_token';
$client = new Client($accountSid, $authToken);

$deploymentSid = 'DLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
$deployment = $client->preview->deployedDevices->deployments($deploymentSid)->update(
  array(
    'friendlyName' => 'My New Device Deployment'
  )
);

echo $deployment->friendlyName;
# Get the Ruby helper library from https://twilio.com/docs/libraries/ruby
require 'twilio-ruby'

# Get your Account SID and Auth Token from https://twilio.com/console
account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
auth_token = 'your_auth_token'
client = Twilio::REST::Client.new(account_sid, auth_token)

deployment_sid = 'DLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
deployment = client.preview.deployed_devices
                   .deployments(deployment_sid)
                   .update(friendly_name: 'My New Device Deployment')

puts deployment.friendly_name
# Get the Node helper library from https://twilio.com/docs/libraries/python
from twilio.rest import Client

# Get your Account SID and Auth Token from https://twilio.com/console
account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
auth_token = 'your_auth_token'
client = Client(account_sid, auth_token)

deployment_sid = 'DLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
deployment = client.preview\
                   .deployed_devices\
                   .deployments(sid=deployment_sid)\
                   .update(friendly_name='My New Device Deployment')

print(deployment.friendly_name)
// Get the Java helper library from https://twilio.com/docs/libraries/java
import com.twilio.Twilio;
import com.twilio.rest.preview.deployedDevices.Deployment;
import com.twilio.rest.preview.deployedDevices.DeploymentUpdater;

public class Example {
    // Get your Account SID and Auth Token from https://twilio.com/console
    public static final String ACCOUNT_SID = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
    public static final String AUTH_TOKEN = "your_auth_token";

    public static void main(String[] args) {
        Twilio.init(ACCOUNT_SID, AUTH_TOKEN);

        String deploymentSid = "DLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";

        Deployment deployment = new DeploymentUpdater(deploymentSid)
                .setFriendlyName("My New Device Deployment")
                .update();

        System.out.println(deployment.getFriendlyName());
    }
}
curl -u 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX:your_auth_token' \
  -X POST https://preview.twilio.com/DeployedDevices/Fleets/FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Deployments/DLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX \
  -d 'FriendlyName=My New Device Deployment' \
  -d 'SyncServiceSid=ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
{
  "sid": "DLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "friendly_name": "My New Device Deployment",
  "fleet_sid": "FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "account_sid": "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "sync_service_sid": "ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "date_created": "2017-08-14T15:44:05Z",
  "date_updated": "2017-08-14T15:55:25Z",
  "url": "https://preview.twilio.com/DeployedDevices/Fleets/FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Deployments/DLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
}
Update a Device Deployment

Deployment handled, next create a Device and Device Key.

Create a Device and Device Key

For Sync for IoT, a Device is one piece of hardware managed through the Device Manager. When connecting to Sync, Twilio identifies your device either through a key or certificate. Today we'll be using a Device Key to authenticate with Sync.

While inside your Fleet, on the left sidebar click the 'Devices' link.  Enter a Unique and Friendly name for the board then hit the 'Create' button.

Create a New ESP8266 Device in Deployed Devices

You can also create and manage a Device through the Twilio API.

Loading Code Samples...
Language
SDK Version:
  • 5.x
Response Format:
  • json
SDK Version:
  • 7.x
SDK Version:
  • 3.x
SDK Version:
  • 5.x
SDK Version:
  • 6.x
SDK Version:
  • 5.x
Format:
  • JSON
// Get the Node helper library from https://twilio.com/docs/libraries/node
const fs = require('fs');
const Twilio = require('twilio').Twilio;

// Get your Account SID and Auth Token from https://twilio.com/console
const accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
const authToken = 'your_auth_token';
const client = new Twilio(accountSid, authToken);

const fleetSid = 'FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
const fleetService = client.preview.deployed_devices.fleets(fleetSid);

fleetService.devices
  .create({
    friendlyName: 'My Device #1',
  })
  .then(response => {
    console.log(response);
  })
  .catch(error => {
    console.log(error);
  });
// Get the Node helper library from https://twilio.com/docs/libraries/csharp
using System;
using System.Collections.Generic;
using Twilio;
using Twilio.Rest.Preview.DeployedDevices.Fleet

public class Example
{
    public static void Main(string[] args)
    {
        // Get your Account SID and Auth Token from https://twilio.com/console
        const string accountSid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
        const string authToken = "your_auth_token";
        TwilioClient.Init(accountSid, authToken);

        var device = DeviceResource.Create(
            pathFleetSid: "FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
            friendlyName: "My Device #1"
        );

        Console.WriteLine(device.Sid);
    }
}
<?php
// Get the Node helper library from https://twilio.com/docs/libraries/php
require_once '/path/to/vendor/autoload.php'; // Loads the library

use Twilio\Rest\Client;

// Get your Account SID and Auth Token from https://twilio.com/console
$accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
$authToken = 'your_auth_token';
$client = new Client($sid, $token);

$fleetSid = 'FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
$fleetService = $client->preview->deployedDevices->fleets($fleetSid);

$device = $fleetService->devices->create([
    'friendlyName' => 'My Device #1'
]);

echo $device->sid;
# Get the Node helper library from https://twilio.com/docs/libraries/ruby
require 'twilio-ruby'

# Get your Account SID and Auth Token from https://twilio.com/console
account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
auth_token = 'your_auth_token'
client = Twilio::REST::Client.new(account_sid, auth_token)

fleet_sid = 'FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
fleet_service = client.preview.deployed_devices.fleets(fleet_sid)

device = fleet_service.devices.create(
  friendly_name: 'My Device #1'
)

puts device.sid
# Get the Node helper library from https://twilio.com/docs/libraries/python
from Twilio.rest import Client

# Get your Account SID and Auth Token from https://twilio.com/console
account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
auth_token = 'your_auth_token'
client = Client(account_sid, auth_token)

fleet_sid = 'FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
fleet_service = client.preview.deployed_devices.fleets(fleet_sid)

device = fleet_service.devices.create(friendly_name='My Device #1')

print(device.sid)
// Get the Node helper library from https://twilio.com/docs/libraries/java
import com.twilio.Twilio;
import com.twilio.base.ResourceSet;
import com.twilio.rest.preview.deployedDevices.fleet;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class Example {
    // Get your Account SID and Auth Token from https://twilio.com/console
    public static final String ACCOUNT_SID = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
    public static final String AUTH_TOKEN = "your_auth_token";

    public static void main(String[] args) {
        Twilio.init(ACCOUNT_SID, AUTH_TOKEN);

        Device device = DeviceCreator("FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
            .setFriendlyName("My Device #1")
            .create();

        System.out.println(device.getSid());
    }
}
curl -u 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX:your_auth_token' \
  -X POST https://preview.twilio.com/DeployedDevices/Fleets/FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Devices \
  -d 'FriendlyName=My Device #1'
{
  "sid": "THXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "friendly_name": "My Device #1",
  "unique_name": null,
  "fleet_sid": "FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "account_sid": "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "deployment_sid": "DLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "identity": null,
  "enabled": true,
  "date_created": "2017-08-14T19:19:30Z",
  "date_updated": "2017-08-14T19:19:30Z",
  "date_authenticated": null,
  "url": "https://preview.twilio.com/DeployedDevices/Fleets/FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Devices/THXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
}
Create a Device

Now (in your new Device configuration) click the 'Keys' link. You'll be presented with the following screen:

Create New Device Key Button

The Device Sid should automagically be populated, so enter a Unique Name and 'Create'.  Note: Save both the Key and the Secret - once the secret is lost, you can't recover it!

Create a Device Key in Sync Deployed Devices

You can create and delete Device Keys using the REST API.  Here's an example:

Loading Code Samples...
Language
SDK Version:
  • 5.x
Response Format:
  • json
SDK Version:
  • 7.x
SDK Version:
  • 3.x
SDK Version:
  • 5.x
SDK Version:
  • 6.x
SDK Version:
  • 5.x
Format:
  • JSON
const accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
const authToken = 'your_auth_token';
const Twilio = require('twilio').Twilio;

const client = new Twilio(accountSid, authToken);
const fleet = client.preview.deployed_devices.fleets(
  'FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
);

fleet.keys
  .create({
    deviceSid: 'THXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
  })
  .then(response => {
    console.log(response);
  })
  .catch(error => {
    console.log(error);
  });
// Get the Node helper library from https://twilio.com/docs/libraries/csharp
using System;
using System.Collections.Generic;
using Twilio;
using Twilio.Rest.Preview.DeployedDevices.Fleet;

public class Example
{
    public static void Main(string[] args)
    {
        // Get your Account SID and Auth Token from https://twilio.com/console
        const string accountSid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
        const string authToken = "your_auth_token";
        TwilioClient.Init(accountSid, authToken);

        const string fleetSid = "FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
        var key = KeyResource.Create(
            fleetSid,
            deviceSid: "THXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
        );

        Console.WriteLine(key.Sid);
    }
}
<?php
// Get the Node helper library from https://twilio.com/docs/libraries/php
require_once '/path/to/vendor/autoload.php'; // Loads the library

use Twilio\Rest\Client;

// Get your Account SID and Auth Token from https://twilio.com/console
$accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
$authToken = 'your_auth_token';
$client = new Client($accountSid, $authToken);

$fleetSid = 'FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
$fleetService = $client->preview->deployedDevices->fleets($fleetSid);

$key = $fleetService->keys->create([
    'deviceSid' => 'THXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
]);

echo $key->sid;
# Get the Node helper library from https://twilio.com/docs/libraries/ruby
require 'twilio-ruby'

# Get your Account SID and Auth Token from https://twilio.com/console
account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
auth_token = 'your_auth_token'
client = Twilio::REST::Client.new(account_sid, auth_token)

fleet_sid = 'FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
fleet_service = client.preview.deployed_devices.fleets(fleet_sid)

key = fleet_service.keys.create(
  device_sid: 'THXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
)

puts key.sid
# Get the Node helper library from https://twilio.com/docs/libraries/python
from twilio.rest import Client

# Get your Account SID and Auth Token from https://twilio.com/console
account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
auth_token = 'your_auth_token'
client = Client(account_sid, auth_token)

fleet_sid = 'FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
fleet_service = client.preview.deployed_devices.fleets(sid=fleet_sid)

key = fleet_service.keys.create(
    device_sid='THXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')

print(key.sid)
// Get the Node helper library from https://twilio.com/docs/libraries/java
import com.twilio.Twilio;
import com.twilio.rest.preview.deployedDevices.fleet.Key;
import com.twilio.rest.preview.deployedDevices.fleet.KeyCreator;

public class Example {
    // Get your Account SID and Auth Token from https://twilio.com/console
    public static final String ACCOUNT_SID = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
    public static final String AUTH_TOKEN = "your_auth_token";

    public static void main(String[] args) {
        Twilio.init(ACCOUNT_SID, AUTH_TOKEN);

        String fleetSid = "FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
        String deviceSid = "THXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";

        KeyCreator keyCreator = new KeyCreator(fleetSid);
        Key key = keyCreator.setDeviceSid(deviceSid)
                .create();

        System.out.println(key.getFleetSid());
    }
}
curl -u 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX:your_auth_token' \
  -X POST https://preview.twilio.com/DeployedDevices/Fleets/FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Keys \
  -d 'DeviceSid=THXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
{
  "sid": "KYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "friendly_name": null,
  "fleet_sid": "FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "account_sid": "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "device_sid": "THXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "secret": "<your_secret>",
  "date_created": "2017-08-14T17:52:00Z",
  "date_updated": "2017-08-14T17:52:00Z",
  "url": "https://preview.twilio.com/DeployedDevices/Fleets/FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Keys/KYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
}
Create a Device Key

In Arm Mbed, you'll be copying the Device Key and Device Secret that you just created. Keep them handy for that step.

Create a Sync Document

A Document is the simplest type of object in Sync (excellent for LED state tracking!). You will have to create a document before you connect to Sync. The Document name will map directly to a MQTT topic name, and you'll subscribe in the code. Name your Document 'BoardLED' (match our capitalization).

Loading Code Samples...
Language
SDK Version:
  • 5.x
Response Format:
  • json
SDK Version:
  • 7.x
SDK Version:
  • 3.x
SDK Version:
  • 5.x
SDK Version:
  • 6.x
SDK Version:
  • 5.x
Format:
  • JSON
const accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
const authToken = 'your_auth_token';
const Twilio = require('twilio').Twilio;

const client = new Twilio(accountSid, authToken);
const service = client.sync.services('default');

service.documents
  .create({
    uniqueName: 'BoardLED',
    data: { led: 'OFF' },
  })
  .then(response => {
    console.log(response);
  })
  .catch(error => {
    console.log(error);
  });
// Download the twilio-csharp library from twilio.com/docs/libraries/csharp
using System;
using Twilio;
using Twilio.Rest.Sync.V1.Service;

public class Example
{
    public static void Main(string[] args)
    {
        // Find your Account SID and Auth Token at twilio.com/console
        const string accountSid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
        const string authToken = "your_auth_token";
        const string serviceSid = "default";

        TwilioClient.Init(accountSid, authToken);

        var data = new
        {
            led = "OFF"
        };

        var doc = DocumentResource.Create(serviceSid,
                                          "BoardLED",
                                          data);

        Console.WriteLine(doc.Sid);
    }
}
<?php
// NOTE: This example uses the next generation Twilio helper library - for more
// information on how to download and install this version, visit
// https://www.twilio.com/docs/libraries/php
require_once 'vendor/autoload.php';

use Twilio\Rest\Client;

// Your Account SID from www.twilio.com/console
$sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
// Your Auth Token from www.twilio.com/console
$token = "your_auth_token";

$client = new Client($sid, $token);

$data = array(
    'led' => "OFF"
);

$doc = $client->sync
    ->services("default")
    ->documents->create(
        array(
            'uniqueName' => "BoardLED",
            'data' => $data
        )
    );

echo $doc->sid, PHP_EOL;
require 'twilio-ruby'

# Initialize the client
account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
auth_token = 'your_auth_token'
client = Twilio::REST::Client.new(account_sid, auth_token)

# Retrieve the service
service = client.sync.v1.services('default')

data = [
  '"led": "OFF"'
]

# Create the Document, data can be any JSON
response = service.documents.create(
  unique_name: 'BoardLED',
  data: "{#{data.join(',')}}"
)

puts response
# Download the Python helper library from twilio.com/docs/python/install
from twilio.rest import Client

# Your Account Sid and Auth Token from twilio.com/user/account
account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
auth_token = "your_auth_token"
client = Client(account_sid, auth_token)

data = {
    'led': "OFF"
}

document = client.sync \
    .services("default") \
    .documents \
    .create(unique_name="BoardLED", data=data)

print(document.sid)
// Install the Java helper library from twilio.com/docs/java/install
import java.util.HashMap;
import java.util.Map;

import com.twilio.Twilio;
import com.twilio.rest.sync.v1.service.Document;

public class Example {
  // Find your Account Sid and Token at twilio.com/user/account
  public static final String ACCOUNT_SID = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
  public static final String AUTH_TOKEN = "your_auth_token";

  public static void main(String[] args) {
    Twilio.init(ACCOUNT_SID, AUTH_TOKEN);

    Map<String, Object> data = new HashMap<>();
    data.put("led", "OFF");

    Document document = Document
        .creator("default")
        .setUniqueName("BoardLED")
        .setData(data)
        .create();

    System.out.println(document.getSid());
  }
}
curl -X POST https://sync.twilio.com/v1/Services/default/Documents \
 -d 'UniqueName=BoardLED' \
 -d 'Data={"led":"OFF"}'  \
 -u 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX:your_auth_token'
{
  "unique_name": "BoardLED",
  "url": "https://sync.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Documents/ETXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "created_by": "system",
  "account_sid": "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "date_created": "2017-09-06T20:53:38Z",
  "date_updated": "2017-09-06T20:53:38Z",
  "sid": "ETXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "service_sid": "ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "data": {
    "led": "OFF"
  },
  "revision": "0",
  "links": {
    "permissions": "https://sync.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Documents/ETXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Permissions"
  }
}
Use the Sync Service Sid from the 'Configure Deployment' Screen, as Shown Above.
Create a Sync Document

Use the Sync Service Sid from the 'Configure Deployment' Screen, as Shown Above.

We initialize led key to value OFF and create a new document BoardLED.

Prerequisites to Use a MultiConnect® Dragonfly™ with Sync

You can grab all of our LinkIt code quickly from Github.

For this guide's development, we used a Multi-Tech MultiConnect® Dragonfly™ with the Arm Mbe IDE. For an overview of connecting to Mbed with this board, please see this page. For help setting up the dev board, SIM, PCB antenna, or modem find Multi-Tech's instructions here.

Add All Our Code to the Arm Mbed IDE

The easiest way to get started with our code is to follow this link:

At that link, simply follow the yellow 'Import into Compiler' button and IDE prompts to load our code into your workspace.

Add Your Device Key and Secret to the Code

Above, you created a new device key and saved the lkey and secret somewhere safe. Now, edit the lines at the top of main.cpp which ask for those credentials.

Loading Code Samples...
Language
#include <mbed.h>
#include <mtsas.h>
#include <ssl.h>
#include <MbedJSONValue.h>
#include <string>
#include "MTSCellularManager.hpp"
#include "TlsMQTTClient.hpp"
#include "certificates.hpp"

/* 
 *  Sync Settings
 *  
 *  Enter a Sync Key & Password, your document unique name, 
 *  and the device name
 */
char* sync_key                          = "KYXXXXXXXXXXXXXXXXXXXX";
char* sync_password                     = "SECRET_HERE";
char* sync_document                     = "sync/docs/BoardLED";
char* sync_device_name                  = "MultiConnect Dragonfly";

/* Sync server and MQTT setup; you probably don't have to change these. */
const char* mqtt_server                 = "mqtt-sync.us1.twilio.com";
const uint16_t mqtt_port                = 8883;
const uint16_t maxMQTTpackageSize       = 512;

TlsMQTTClient client = TlsMQTTClient();
DigitalOut led(D7);
DigitalOut bc_nce(PB_2);
const uint8_t MQTT_HEARTBEAT = 15;

/* 
 * Our Twilio Connected Devices message handling callback.  This is passed as a 
 * callback function when we subscribe to the document, and any messages will 
 * appear here.
 */
void callback(MQTT::MessageData& data) 
{
    if (data.message.payloadlen > maxMQTTpackageSize) {
        return;
    }
    char buf[maxMQTTpackageSize + 1];
    strncpy(buf, (char*)data.message.payload, data.message.payloadlen);
    buf[data.message.payloadlen] = '\0';
    
    logDebug("Received new update %s", buf);
    /* JSON Parse 'led' */
    MbedJSONValue parser;
    parse(parser, buf);
    
    /* The parser will segfault and reset the board if "led" isn't contained. */
    if (parser.hasMember("led")) {
        std::string led_str;
        led_str = parser["led"].get<std::string>();
        
        if (led_str.compare("ON") == 0) {
            logDebug("Turning LED ON");
            led = 0; // Active LOW
        } else {
            logDebug("Turning LED OFF");
            led = 1; // Active LOW
        }
    }
}


/* 
 * This function connects to Sync via MQTT. We connect using the key, password, 
 * and device name defined as constants above, and checks the server
 * certificate.
 * 
 * If everything works, we subscribe to the document topic and return.
 */
void connect_mqtt()
{
    MQTTPacket_connectData conn_data = MQTTPacket_connectData_initializer;
    conn_data.clientID.cstring = sync_device_name;
    conn_data.username.cstring = sync_key;
    conn_data.password.cstring = sync_password;
    int rc = client.connect(
        mqtt_server, 
        mqtt_port, 
        MQTT_GATEWAY_PROD_ROOT_CA_PEM, 
        conn_data
    );
    logInfo("MQTT connect result: %d", rc);
    
    rc = client.subscribe(
        "sync/docs/BoardLED", 
        MQTT::QOS1, 
        callback
    );
    logInfo("MQTT subscription result: %d", rc);
}


/* 
 * Very basic device loop - all we do is reconnect when disconnected
 */
void loop()
{
    if (client.isConnected()) {
        client.yield(MQTT_HEARTBEAT/2.0);
        wait(MQTT_HEARTBEAT);
    } else {
        wait(MQTT_HEARTBEAT*10);
        connect_mqtt();
    }
    
    // Here's an example of publishing from the MultiConnect Dragonfly.
    // Uncomment until the end of the function to send a 'msg' back to Sync
    // every 5 cycles through the loop! (5*MQTT_HEARTBEAT seconds)
    /*
    static uint32_t ticks = 0;
    MQTT::Message message;
    char buf[maxMQTTpackageSize] = "{\"msg\":\"Ahoy!\",\"led\":\"ON\"}";
    message.qos = MQTT::QOS1;
    message.payload = (void*)buf;
    message.payloadlen = strlen(buf) + 1;
    if (ticks++ > 4) {
            logInfo("Sending ON message to Twilio!");
            client.publish(
                    sync_document, 
                    message
            );
            ticks = 0;
    }
    */
}


/* 
 * In main, we configure our LEDs, connect to Twilio Programmable Wireless,
 * and initialize CyaSSL. We then connect our MQTT client for the first time.
 *
 * When done, we pass control to the MQTT loop, which handles yield()s.
 */
int main() 
{
    led = 1;  // Active LOW
    bc_nce = 1;
    Serial debug(USBTX, USBRX);
    debug.baud(115200);
    mts::MTSLog::setLogLevel(mts::MTSLog::TRACE_LEVEL);

    // Be sure your SIM is registered in the Twilio console.
    // https://www.twilio.com/console/wireless/sims/
    logInfo("Initializing Twilio Programmable Wireless");
    MTSCellularManager cellularManager("wireless.twilio.com");   
    if (! cellularManager.init()) {
        while (true) {
            logError("failed to initialize cellular radio"); wait(10);  
        }
    }
    CyaSSL_Init();
    connect_mqtt();

    /* We're done; pass off control to the loop */
    while (1) {
       loop();
    }
}
Paste your generated device key and device secret into Arm Mbed.
Add Your Device Key and Secret

Paste your generated device key and device secret into Arm Mbed.

Excellent - that's all you actually need to do to get the demo going!

Libraries Used in this Quickstart

We used four libraries for this demo today. Please note that while our code is licensed MIT, not all other libraries share this license. Be sure to research the suitability of all relevant licenses when developing using our code.

Burn the Code and Toggle the LED

We're getting close now - it's burning time!

Inside Mbed, click the 'Compile' button. Mbed will compile your code for the Dragonfly™ and produce a binary file for uploading. While your board and dev kit are connected to the computer via USB, upload the binary file to the enumerated USB storage device. When complete, hit the white reset button to load the new binary.

Arm Mbed Compile Program

Optionally, now open up a serial monitor to listen to the board. On Windows we like PuTTY, and on *NIX we prefer screen.

But wait - those newly scrolling messages aren't the demo!  Let's blink one of the LEDs onboard that dev board.  Set 'led' to 'ON' in the Document you created above.

Loading Code Samples...
Language
SDK Version:
  • 5.x
Response Format:
  • json
SDK Version:
  • 7.x
SDK Version:
  • 3.x
SDK Version:
  • 5.x
SDK Version:
  • 6.x
SDK Version:
  • 5.x
Format:
  • JSON
const accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
const authToken = 'your_auth_token';
const Twilio = require('twilio').Twilio;

const client = new Twilio(accountSid, authToken);
const service = client.sync.services('default');

service
  .documents('BoardLED')
  .update({
    data: { led: 'ON' },
  })
  .then(response => {
    console.log(response);
  })
  .catch(error => {
    console.log(error);
  });
// Download the twilio-csharp library from twilio.com/docs/libraries/csharp
using System;
using Twilio;
using Twilio.Rest.Sync.V1.Service;

public class Example
{
    public static void Main(string[] args)
    {
        // Find your Account SID and Auth Token at twilio.com/console
        const string accountSid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
        const string authToken = "your_auth_token";
        const string serviceSid = "default";

        TwilioClient.Init(accountSid, authToken);

        var data = new
        {
            led = "ON"
        };

        var doc = DocumentResource.Update(serviceSid,
                                          "BoardLED",
                                          data);

        Console.WriteLine(doc.Data);
    }
}
<?php
// NOTE: This example uses the next generation Twilio helper library - for more
// information on how to download and install this version, visit
// https://www.twilio.com/docs/libraries/php
require_once 'vendor/autoload.php';

use Twilio\Rest\Client;

// Your Account SID from www.twilio.com/console
$sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
// Your Auth Token from www.twilio.com/console
$token = "your_auth_token";

$client = new Client($sid, $token);

$data = array(
    'led' => "ON"
);

$doc = $client->sync
    ->services("default")
    ->documents("BoardLED")->update(
        array(
            'led' => $data
        )
    );

print_r($doc->data);
echo PHP_EOL;
require 'twilio-ruby'

# Initialize the client
account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
auth_token = 'your_auth_token'
client = Twilio::REST::Client.new(account_sid, auth_token)

# Retreive the service
service = client.sync.v1.services('default')

# Update the Document, data can be any JSON
response = service.documents('BoardLED').update(
  data: '{ "led": "ON" }'
)

puts response
# Download the Python helper library from twilio.com/docs/python/install
from twilio.rest import Client

# Your Account Sid and Auth Token from twilio.com/user/account
account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
auth_token = "your_auth_token"
client = Client(account_sid, auth_token)

new_data = {
    'led': "ON"
}

document = client.sync \
    .services("default") \
    .documents("BoardLED") \
    .update(data=new_data)

print(document.data)
// Install the Java helper library from twilio.com/docs/java/install
import java.util.HashMap;
import java.util.Map;

import com.twilio.Twilio;
import com.twilio.rest.sync.v1.service.Document;

public class Example {
  // Find your Account Sid and Token at twilio.com/user/account
  public static final String ACCOUNT_SID = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
  public static final String AUTH_TOKEN = "your_auth_token";

  public static final String SERVICE_SID = "default";

  public static void main(String[] args) {
    Twilio.init(ACCOUNT_SID, AUTH_TOKEN);

    Map<String, Object> data = new HashMap<>();
    data.put("led", "ON");

    Document document = Document.updater(SERVICE_SID, "BoardLED", data).update();

    System.out.println(document.getData());
  }
}
curl -X POST https://sync.twilio.com/v1/Services/default/Documents/BoardLED \
 -d 'Data={"led":"ON"}'  \
 -u 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX:your_auth_token'
{
  "unique_name": "BoardLED",
  "url": "https://sync.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Documents/ETXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "created_by": "system",
  "account_sid": "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "date_created": "2017-09-06T20:53:38Z",
  "date_updated": "2017-09-06T20:55:21Z",
  "sid": "ETXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "service_sid": "ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "data": {
    "led": "ON"
  },
  "revision": "1",
  "links": {
    "permissions": "https://sync.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Documents/ETXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Permissions"
  }
}
Update a BoardLED Document

You should quickly see three signs your API Request went through:

  • Sync responds to your code or command with a success message
  • The dev board LED will light
  • If you've got PuTTY or Screen going, you'll see a nice message

Multiconnect Dragonfly Blinking LED

Sending Updates Back to Sync from the LinkIt

If you look in main.cpp, there are commented lines which would send updates back to the Document. Remove the comment block to send a msg back to Sync periodically.

Loading Code Samples...
Language
#include <mbed.h>
#include <mtsas.h>
#include <ssl.h>
#include <MbedJSONValue.h>
#include <string>
#include "MTSCellularManager.hpp"
#include "TlsMQTTClient.hpp"
#include "certificates.hpp"

/* 
 *  Sync Settings
 *  
 *  Enter a Sync Key & Password, your document unique name, 
 *  and the device name
 */
char* sync_key                          = "KYXXXXXXXXXXXXXXXXXXXX";
char* sync_password                     = "SECRET_HERE";
char* sync_document                     = "sync/docs/BoardLED";
char* sync_device_name                  = "MultiConnect Dragonfly";

/* Sync server and MQTT setup; you probably don't have to change these. */
const char* mqtt_server                 = "mqtt-sync.us1.twilio.com";
const uint16_t mqtt_port                = 8883;
const uint16_t maxMQTTpackageSize       = 512;

TlsMQTTClient client = TlsMQTTClient();
DigitalOut led(D7);
DigitalOut bc_nce(PB_2);
const uint8_t MQTT_HEARTBEAT = 15;

/* 
 * Our Twilio Connected Devices message handling callback.  This is passed as a 
 * callback function when we subscribe to the document, and any messages will 
 * appear here.
 */
void callback(MQTT::MessageData& data) 
{
    if (data.message.payloadlen > maxMQTTpackageSize) {
        return;
    }
    char buf[maxMQTTpackageSize + 1];
    strncpy(buf, (char*)data.message.payload, data.message.payloadlen);
    buf[data.message.payloadlen] = '\0';
    
    logDebug("Received new update %s", buf);
    /* JSON Parse 'led' */
    MbedJSONValue parser;
    parse(parser, buf);
    
    /* The parser will segfault and reset the board if "led" isn't contained. */
    if (parser.hasMember("led")) {
        std::string led_str;
        led_str = parser["led"].get<std::string>();
        
        if (led_str.compare("ON") == 0) {
            logDebug("Turning LED ON");
            led = 0; // Active LOW
        } else {
            logDebug("Turning LED OFF");
            led = 1; // Active LOW
        }
    }
}


/* 
 * This function connects to Sync via MQTT. We connect using the key, password, 
 * and device name defined as constants above, and checks the server
 * certificate.
 * 
 * If everything works, we subscribe to the document topic and return.
 */
void connect_mqtt()
{
    MQTTPacket_connectData conn_data = MQTTPacket_connectData_initializer;
    conn_data.clientID.cstring = sync_device_name;
    conn_data.username.cstring = sync_key;
    conn_data.password.cstring = sync_password;
    int rc = client.connect(
        mqtt_server, 
        mqtt_port, 
        MQTT_GATEWAY_PROD_ROOT_CA_PEM, 
        conn_data
    );
    logInfo("MQTT connect result: %d", rc);
    
    rc = client.subscribe(
        "sync/docs/BoardLED", 
        MQTT::QOS1, 
        callback
    );
    logInfo("MQTT subscription result: %d", rc);
}


/* 
 * Very basic device loop - all we do is reconnect when disconnected
 */
void loop()
{
    if (client.isConnected()) {
        client.yield(MQTT_HEARTBEAT/2.0);
        wait(MQTT_HEARTBEAT);
    } else {
        wait(MQTT_HEARTBEAT*10);
        connect_mqtt();
    }
    
    // Here's an example of publishing from the MultiConnect Dragonfly.
    // Uncomment until the end of the function to send a 'msg' back to Sync
    // every 5 cycles through the loop! (5*MQTT_HEARTBEAT seconds)
    /*
    static uint32_t ticks = 0;
    MQTT::Message message;
    char buf[maxMQTTpackageSize] = "{\"msg\":\"Ahoy!\",\"led\":\"ON\"}";
    message.qos = MQTT::QOS1;
    message.payload = (void*)buf;
    message.payloadlen = strlen(buf) + 1;
    if (ticks++ > 4) {
            logInfo("Sending ON message to Twilio!");
            client.publish(
                    sync_document, 
                    message
            );
            ticks = 0;
    }
    */
}


/* 
 * In main, we configure our LEDs, connect to Twilio Programmable Wireless,
 * and initialize CyaSSL. We then connect our MQTT client for the first time.
 *
 * When done, we pass control to the MQTT loop, which handles yield()s.
 */
int main() 
{
    led = 1;  // Active LOW
    bc_nce = 1;
    Serial debug(USBTX, USBRX);
    debug.baud(115200);
    mts::MTSLog::setLogLevel(mts::MTSLog::TRACE_LEVEL);

    // Be sure your SIM is registered in the Twilio console.
    // https://www.twilio.com/console/wireless/sims/
    logInfo("Initializing Twilio Programmable Wireless");
    MTSCellularManager cellularManager("wireless.twilio.com");   
    if (! cellularManager.init()) {
        while (true) {
            logError("failed to initialize cellular radio"); wait(10);  
        }
    }
    CyaSSL_Init();
    connect_mqtt();

    /* We're done; pass off control to the loop */
    while (1) {
       loop();
    }
}
Comment out these lines to periodically update the BoardLED Document from the device
Optionally Send Data Back to Sync

Comment out these lines to periodically update the BoardLED Document from the device

Whatever you send back to Sync should be in JSON format.

Wirelessly Expanding Your Internet of Things

4G speeds, blue LEDs, scalable infrastructure - awesome, isn't it?

While we know that your application is going to go a lot further than blinky lights, the same infrastructure you just built can scale to crazy heights with you. Scale far and wide - build dashboards, synchronize hardware, or... well, you decide.

Wherever your business or project takes you hit us with your tweets on Twitter. We can't wait to see what you build!

Need some help?

We all do sometimes; code is hard. Get help now from our support team, or lean on the wisdom of the crowd browsing the Twilio tag on Stack Overflow.

1 / 1
Loading Code Samples...
SDK Version:
  • 5.x
Response Format:
  • json
SDK Version:
  • 7.x
SDK Version:
  • 3.x
SDK Version:
  • 5.x
SDK Version:
  • 6.x
SDK Version:
  • 5.x
Format:
  • JSON
const accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
const authToken = 'your_auth_token';
const Twilio = require('twilio').Twilio;

const client = new Twilio(accountSid, authToken);

client.preview.deployed_devices.fleets
  .create({
    friendlyName: 'My Fleet of Devices',
  })
  .then(response => {
    console.log(response);
  })
  .catch(error => {
    console.log(error);
  });
// Get the Node helper library from https://twilio.com/docs/libraries/csharp
using System;
using System.Collections.Generic;
using Twilio;
using Twilio.Rest.Preview.DeployedDevices;

public class Example
{
    public static void Main(string[] args)
    {
        // Get your Account SID and Auth Token from https://twilio.com/console
        const string accountSid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
        const string authToken = "your_auth_token";
        TwilioClient.Init(accountSid, authToken);

        var fleet = FleetResource.Create(
            friendlyName: "My Fleet of Devices"
        );

        Console.WriteLine(fleet.Sid);
    }
}
<?php
// Get the Node helper library from https://twilio.com/docs/libraries/php
require_once '/path/to/vendor/autoload.php'; // Loads the library

use Twilio\Rest\Client;

// Get your Account SID and Auth Token from https://twilio.com/console
$accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
$authToken = 'your_auth_token';
$client = new Client($accountSid, $authToken);

$fleet = $client->preview->deployedDevices->fleets->create(
  array(
    'friendlyName' => 'My Fleet of Devices'
  )
);

echo $fleet->sid;
# Get the Node helper library from https://twilio.com/docs/libraries/ruby
require 'twilio-ruby'

# Get your Account SID and Auth Token from https://twilio.com/console
account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
auth_token = 'your_auth_token'
client = Twilio::REST::Client.new(account_sid, auth_token)

fleet = client.preview.deployed_devices.fleets.create(
  friendly_name: 'My Fleet of Devices'
)

puts fleet.sid
# Get the Node helper library from https://twilio.com/docs/libraries/python
from twilio.rest import Client

# Get your Account SID and Auth Token from https://twilio.com/console
account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
auth_token = 'your_auth_token'
client = Client(account_sid, auth_token)

fleet = client.preview.deployed_devices.fleets.create(
    friendly_name='My Fleet of Devices')

print(fleet.sid)
// Get the Node helper library from https://twilio.com/docs/libraries/java
import com.twilio.Twilio;
import com.twilio.rest.preview.deployedDevices.Fleet;
import com.twilio.rest.preview.deployedDevices.FleetCreator;

public class Example {
    // Get your Account SID and Auth Token from https://twilio.com/console
    public static final String ACCOUNT_SID = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
    public static final String AUTH_TOKEN = "your_auth_token";

    public static void main(String[] args) {
        Twilio.init(ACCOUNT_SID, AUTH_TOKEN);

        FleetCreator fleetCreator = new FleetCreator();
        Fleet fleet = fleetCreator
                .setFriendlyName("My Fleet of Devices")
                .create();

        System.out.println(fleet.getSid());
    }
}
curl -u 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX:your_auth_token' \
  -X POST https://preview.twilio.com/DeployedDevices/Fleets
{
  "sid": "FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "friendly_name": null,
  "account_sid": "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "default_deployment_sid": "DLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "date_created": "2017-08-14T15:25:45Z",
  "date_updated": "2017-08-14T15:25:45Z",
  "url": "https://preview.twilio.com/DeployedDevices/Fleets/FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "links": {
    "certificates": "https://preview.twilio.com/DeployedDevices/Fleets/FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Certificates",
    "keys": "https://preview.twilio.com/DeployedDevices/Fleets/FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Keys",
    "devices": "https://preview.twilio.com/DeployedDevices/Fleets/FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Devices",
    "deployments": "https://preview.twilio.com/DeployedDevices/Fleets/FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Deployments"
  }
}
SDK Version:
  • 5.x
Response Format:
  • json
SDK Version:
  • 7.x
SDK Version:
  • 3.x
SDK Version:
  • 5.x
SDK Version:
  • 6.x
SDK Version:
  • 5.x
Format:
  • JSON
const accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
const authToken = 'your_auth_token';
const Twilio = require('twilio').Twilio;

const client = new Twilio(accountSid, authToken);
const fleet = client.preview.deployed_devices.fleets(
  'FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
);

fleet
  .deployments('FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
  .update({
    friendlyName: 'My New Device Deployment',
    syncServiceSid: 'ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
  })
  .then(response => {
    console.log(response);
  })
  .catch(error => {
    console.log(error);
  });
// Get the C# helper library from https://twilio.com/docs/libraries/csharp
using System;
using System.Collections.Generic;
using Twilio;
using Twilio.Rest.Preview.DeployedDevices;

public class Example
{
    public static void Main(string[] args)
    {
        // Get your Account SID and Auth Token from https://twilio.com/console
        const string accountSid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
        const string authToken = "your_auth_token";
        TwilioClient.Init(accountSid, authToken);

        const string deploymentSid = "DLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
        var deployment = DeploymentResource.Update(
            deploymentSid,
            friendlyName: "My New Device Deployment");

        Console.WriteLine(deploymentSid.FriendlyName);
    }
}
<?php
// Get the PHP helper library from https://twilio.com/docs/libraries/php
require_once '/path/to/vendor/autoload.php'; // Loads the library

use Twilio\Rest\Client;

// Get your Account SID and Auth Token from https://twilio.com/console
$accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
$authToken = 'your_auth_token';
$client = new Client($accountSid, $authToken);

$deploymentSid = 'DLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
$deployment = $client->preview->deployedDevices->deployments($deploymentSid)->update(
  array(
    'friendlyName' => 'My New Device Deployment'
  )
);

echo $deployment->friendlyName;
# Get the Ruby helper library from https://twilio.com/docs/libraries/ruby
require 'twilio-ruby'

# Get your Account SID and Auth Token from https://twilio.com/console
account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
auth_token = 'your_auth_token'
client = Twilio::REST::Client.new(account_sid, auth_token)

deployment_sid = 'DLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
deployment = client.preview.deployed_devices
                   .deployments(deployment_sid)
                   .update(friendly_name: 'My New Device Deployment')

puts deployment.friendly_name
# Get the Node helper library from https://twilio.com/docs/libraries/python
from twilio.rest import Client

# Get your Account SID and Auth Token from https://twilio.com/console
account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
auth_token = 'your_auth_token'
client = Client(account_sid, auth_token)

deployment_sid = 'DLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
deployment = client.preview\
                   .deployed_devices\
                   .deployments(sid=deployment_sid)\
                   .update(friendly_name='My New Device Deployment')

print(deployment.friendly_name)
// Get the Java helper library from https://twilio.com/docs/libraries/java
import com.twilio.Twilio;
import com.twilio.rest.preview.deployedDevices.Deployment;
import com.twilio.rest.preview.deployedDevices.DeploymentUpdater;

public class Example {
    // Get your Account SID and Auth Token from https://twilio.com/console
    public static final String ACCOUNT_SID = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
    public static final String AUTH_TOKEN = "your_auth_token";

    public static void main(String[] args) {
        Twilio.init(ACCOUNT_SID, AUTH_TOKEN);

        String deploymentSid = "DLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";

        Deployment deployment = new DeploymentUpdater(deploymentSid)
                .setFriendlyName("My New Device Deployment")
                .update();

        System.out.println(deployment.getFriendlyName());
    }
}
curl -u 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX:your_auth_token' \
  -X POST https://preview.twilio.com/DeployedDevices/Fleets/FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Deployments/DLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX \
  -d 'FriendlyName=My New Device Deployment' \
  -d 'SyncServiceSid=ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
{
  "sid": "DLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "friendly_name": "My New Device Deployment",
  "fleet_sid": "FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "account_sid": "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "sync_service_sid": "ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "date_created": "2017-08-14T15:44:05Z",
  "date_updated": "2017-08-14T15:55:25Z",
  "url": "https://preview.twilio.com/DeployedDevices/Fleets/FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Deployments/DLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
}
SDK Version:
  • 5.x
Response Format:
  • json
SDK Version:
  • 7.x
SDK Version:
  • 3.x
SDK Version:
  • 5.x
SDK Version:
  • 6.x
SDK Version:
  • 5.x
Format:
  • JSON
// Get the Node helper library from https://twilio.com/docs/libraries/node
const fs = require('fs');
const Twilio = require('twilio').Twilio;

// Get your Account SID and Auth Token from https://twilio.com/console
const accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
const authToken = 'your_auth_token';
const client = new Twilio(accountSid, authToken);

const fleetSid = 'FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
const fleetService = client.preview.deployed_devices.fleets(fleetSid);

fleetService.devices
  .create({
    friendlyName: 'My Device #1',
  })
  .then(response => {
    console.log(response);
  })
  .catch(error => {
    console.log(error);
  });
// Get the Node helper library from https://twilio.com/docs/libraries/csharp
using System;
using System.Collections.Generic;
using Twilio;
using Twilio.Rest.Preview.DeployedDevices.Fleet

public class Example
{
    public static void Main(string[] args)
    {
        // Get your Account SID and Auth Token from https://twilio.com/console
        const string accountSid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
        const string authToken = "your_auth_token";
        TwilioClient.Init(accountSid, authToken);

        var device = DeviceResource.Create(
            pathFleetSid: "FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
            friendlyName: "My Device #1"
        );

        Console.WriteLine(device.Sid);
    }
}
<?php
// Get the Node helper library from https://twilio.com/docs/libraries/php
require_once '/path/to/vendor/autoload.php'; // Loads the library

use Twilio\Rest\Client;

// Get your Account SID and Auth Token from https://twilio.com/console
$accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
$authToken = 'your_auth_token';
$client = new Client($sid, $token);

$fleetSid = 'FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
$fleetService = $client->preview->deployedDevices->fleets($fleetSid);

$device = $fleetService->devices->create([
    'friendlyName' => 'My Device #1'
]);

echo $device->sid;
# Get the Node helper library from https://twilio.com/docs/libraries/ruby
require 'twilio-ruby'

# Get your Account SID and Auth Token from https://twilio.com/console
account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
auth_token = 'your_auth_token'
client = Twilio::REST::Client.new(account_sid, auth_token)

fleet_sid = 'FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
fleet_service = client.preview.deployed_devices.fleets(fleet_sid)

device = fleet_service.devices.create(
  friendly_name: 'My Device #1'
)

puts device.sid
# Get the Node helper library from https://twilio.com/docs/libraries/python
from Twilio.rest import Client

# Get your Account SID and Auth Token from https://twilio.com/console
account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
auth_token = 'your_auth_token'
client = Client(account_sid, auth_token)

fleet_sid = 'FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
fleet_service = client.preview.deployed_devices.fleets(fleet_sid)

device = fleet_service.devices.create(friendly_name='My Device #1')

print(device.sid)
// Get the Node helper library from https://twilio.com/docs/libraries/java
import com.twilio.Twilio;
import com.twilio.base.ResourceSet;
import com.twilio.rest.preview.deployedDevices.fleet;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class Example {
    // Get your Account SID and Auth Token from https://twilio.com/console
    public static final String ACCOUNT_SID = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
    public static final String AUTH_TOKEN = "your_auth_token";

    public static void main(String[] args) {
        Twilio.init(ACCOUNT_SID, AUTH_TOKEN);

        Device device = DeviceCreator("FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
            .setFriendlyName("My Device #1")
            .create();

        System.out.println(device.getSid());
    }
}
curl -u 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX:your_auth_token' \
  -X POST https://preview.twilio.com/DeployedDevices/Fleets/FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Devices \
  -d 'FriendlyName=My Device #1'
{
  "sid": "THXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "friendly_name": "My Device #1",
  "unique_name": null,
  "fleet_sid": "FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "account_sid": "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "deployment_sid": "DLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "identity": null,
  "enabled": true,
  "date_created": "2017-08-14T19:19:30Z",
  "date_updated": "2017-08-14T19:19:30Z",
  "date_authenticated": null,
  "url": "https://preview.twilio.com/DeployedDevices/Fleets/FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Devices/THXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
}
SDK Version:
  • 5.x
Response Format:
  • json
SDK Version:
  • 7.x
SDK Version:
  • 3.x
SDK Version:
  • 5.x
SDK Version:
  • 6.x
SDK Version:
  • 5.x
Format:
  • JSON
const accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
const authToken = 'your_auth_token';
const Twilio = require('twilio').Twilio;

const client = new Twilio(accountSid, authToken);
const fleet = client.preview.deployed_devices.fleets(
  'FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
);

fleet.keys
  .create({
    deviceSid: 'THXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
  })
  .then(response => {
    console.log(response);
  })
  .catch(error => {
    console.log(error);
  });
// Get the Node helper library from https://twilio.com/docs/libraries/csharp
using System;
using System.Collections.Generic;
using Twilio;
using Twilio.Rest.Preview.DeployedDevices.Fleet;

public class Example
{
    public static void Main(string[] args)
    {
        // Get your Account SID and Auth Token from https://twilio.com/console
        const string accountSid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
        const string authToken = "your_auth_token";
        TwilioClient.Init(accountSid, authToken);

        const string fleetSid = "FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
        var key = KeyResource.Create(
            fleetSid,
            deviceSid: "THXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
        );

        Console.WriteLine(key.Sid);
    }
}
<?php
// Get the Node helper library from https://twilio.com/docs/libraries/php
require_once '/path/to/vendor/autoload.php'; // Loads the library

use Twilio\Rest\Client;

// Get your Account SID and Auth Token from https://twilio.com/console
$accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
$authToken = 'your_auth_token';
$client = new Client($accountSid, $authToken);

$fleetSid = 'FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
$fleetService = $client->preview->deployedDevices->fleets($fleetSid);

$key = $fleetService->keys->create([
    'deviceSid' => 'THXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
]);

echo $key->sid;
# Get the Node helper library from https://twilio.com/docs/libraries/ruby
require 'twilio-ruby'

# Get your Account SID and Auth Token from https://twilio.com/console
account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
auth_token = 'your_auth_token'
client = Twilio::REST::Client.new(account_sid, auth_token)

fleet_sid = 'FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
fleet_service = client.preview.deployed_devices.fleets(fleet_sid)

key = fleet_service.keys.create(
  device_sid: 'THXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
)

puts key.sid
# Get the Node helper library from https://twilio.com/docs/libraries/python
from twilio.rest import Client

# Get your Account SID and Auth Token from https://twilio.com/console
account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
auth_token = 'your_auth_token'
client = Client(account_sid, auth_token)

fleet_sid = 'FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
fleet_service = client.preview.deployed_devices.fleets(sid=fleet_sid)

key = fleet_service.keys.create(
    device_sid='THXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')

print(key.sid)
// Get the Node helper library from https://twilio.com/docs/libraries/java
import com.twilio.Twilio;
import com.twilio.rest.preview.deployedDevices.fleet.Key;
import com.twilio.rest.preview.deployedDevices.fleet.KeyCreator;

public class Example {
    // Get your Account SID and Auth Token from https://twilio.com/console
    public static final String ACCOUNT_SID = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
    public static final String AUTH_TOKEN = "your_auth_token";

    public static void main(String[] args) {
        Twilio.init(ACCOUNT_SID, AUTH_TOKEN);

        String fleetSid = "FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
        String deviceSid = "THXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";

        KeyCreator keyCreator = new KeyCreator(fleetSid);
        Key key = keyCreator.setDeviceSid(deviceSid)
                .create();

        System.out.println(key.getFleetSid());
    }
}
curl -u 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX:your_auth_token' \
  -X POST https://preview.twilio.com/DeployedDevices/Fleets/FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Keys \
  -d 'DeviceSid=THXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
{
  "sid": "KYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "friendly_name": null,
  "fleet_sid": "FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "account_sid": "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "device_sid": "THXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "secret": "<your_secret>",
  "date_created": "2017-08-14T17:52:00Z",
  "date_updated": "2017-08-14T17:52:00Z",
  "url": "https://preview.twilio.com/DeployedDevices/Fleets/FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Keys/KYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
}
SDK Version:
  • 5.x
Response Format:
  • json
SDK Version:
  • 7.x
SDK Version:
  • 3.x
SDK Version:
  • 5.x
SDK Version:
  • 6.x
SDK Version:
  • 5.x
Format:
  • JSON
const accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
const authToken = 'your_auth_token';
const Twilio = require('twilio').Twilio;

const client = new Twilio(accountSid, authToken);
const service = client.sync.services('default');

service.documents
  .create({
    uniqueName: 'BoardLED',
    data: { led: 'OFF' },
  })
  .then(response => {
    console.log(response);
  })
  .catch(error => {
    console.log(error);
  });
// Download the twilio-csharp library from twilio.com/docs/libraries/csharp
using System;
using Twilio;
using Twilio.Rest.Sync.V1.Service;

public class Example
{
    public static void Main(string[] args)
    {
        // Find your Account SID and Auth Token at twilio.com/console
        const string accountSid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
        const string authToken = "your_auth_token";
        const string serviceSid = "default";

        TwilioClient.Init(accountSid, authToken);

        var data = new
        {
            led = "OFF"
        };

        var doc = DocumentResource.Create(serviceSid,
                                          "BoardLED",
                                          data);

        Console.WriteLine(doc.Sid);
    }
}
<?php
// NOTE: This example uses the next generation Twilio helper library - for more
// information on how to download and install this version, visit
// https://www.twilio.com/docs/libraries/php
require_once 'vendor/autoload.php';

use Twilio\Rest\Client;

// Your Account SID from www.twilio.com/console
$sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
// Your Auth Token from www.twilio.com/console
$token = "your_auth_token";

$client = new Client($sid, $token);

$data = array(
    'led' => "OFF"
);

$doc = $client->sync
    ->services("default")
    ->documents->create(
        array(
            'uniqueName' => "BoardLED",
            'data' => $data
        )
    );

echo $doc->sid, PHP_EOL;
require 'twilio-ruby'

# Initialize the client
account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
auth_token = 'your_auth_token'
client = Twilio::REST::Client.new(account_sid, auth_token)

# Retrieve the service
service = client.sync.v1.services('default')

data = [
  '"led": "OFF"'
]

# Create the Document, data can be any JSON
response = service.documents.create(
  unique_name: 'BoardLED',
  data: "{#{data.join(',')}}"
)

puts response
# Download the Python helper library from twilio.com/docs/python/install
from twilio.rest import Client

# Your Account Sid and Auth Token from twilio.com/user/account
account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
auth_token = "your_auth_token"
client = Client(account_sid, auth_token)

data = {
    'led': "OFF"
}

document = client.sync \
    .services("default") \
    .documents \
    .create(unique_name="BoardLED", data=data)

print(document.sid)
// Install the Java helper library from twilio.com/docs/java/install
import java.util.HashMap;
import java.util.Map;

import com.twilio.Twilio;
import com.twilio.rest.sync.v1.service.Document;

public class Example {
  // Find your Account Sid and Token at twilio.com/user/account
  public static final String ACCOUNT_SID = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
  public static final String AUTH_TOKEN = "your_auth_token";

  public static void main(String[] args) {
    Twilio.init(ACCOUNT_SID, AUTH_TOKEN);

    Map<String, Object> data = new HashMap<>();
    data.put("led", "OFF");

    Document document = Document
        .creator("default")
        .setUniqueName("BoardLED")
        .setData(data)
        .create();

    System.out.println(document.getSid());
  }
}
curl -X POST https://sync.twilio.com/v1/Services/default/Documents \
 -d 'UniqueName=BoardLED' \
 -d 'Data={"led":"OFF"}'  \
 -u 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX:your_auth_token'
{
  "unique_name": "BoardLED",
  "url": "https://sync.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Documents/ETXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "created_by": "system",
  "account_sid": "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "date_created": "2017-09-06T20:53:38Z",
  "date_updated": "2017-09-06T20:53:38Z",
  "sid": "ETXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "service_sid": "ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "data": {
    "led": "OFF"
  },
  "revision": "0",
  "links": {
    "permissions": "https://sync.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Documents/ETXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Permissions"
  }
}
#include <mbed.h>
#include <mtsas.h>
#include <ssl.h>
#include <MbedJSONValue.h>
#include <string>
#include "MTSCellularManager.hpp"
#include "TlsMQTTClient.hpp"
#include "certificates.hpp"

/* 
 *  Sync Settings
 *  
 *  Enter a Sync Key & Password, your document unique name, 
 *  and the device name
 */
char* sync_key                          = "KYXXXXXXXXXXXXXXXXXXXX";
char* sync_password                     = "SECRET_HERE";
char* sync_document                     = "sync/docs/BoardLED";
char* sync_device_name                  = "MultiConnect Dragonfly";

/* Sync server and MQTT setup; you probably don't have to change these. */
const char* mqtt_server                 = "mqtt-sync.us1.twilio.com";
const uint16_t mqtt_port                = 8883;
const uint16_t maxMQTTpackageSize       = 512;

TlsMQTTClient client = TlsMQTTClient();
DigitalOut led(D7);
DigitalOut bc_nce(PB_2);
const uint8_t MQTT_HEARTBEAT = 15;

/* 
 * Our Twilio Connected Devices message handling callback.  This is passed as a 
 * callback function when we subscribe to the document, and any messages will 
 * appear here.
 */
void callback(MQTT::MessageData& data) 
{
    if (data.message.payloadlen > maxMQTTpackageSize) {
        return;
    }
    char buf[maxMQTTpackageSize + 1];
    strncpy(buf, (char*)data.message.payload, data.message.payloadlen);
    buf[data.message.payloadlen] = '\0';
    
    logDebug("Received new update %s", buf);
    /* JSON Parse 'led' */
    MbedJSONValue parser;
    parse(parser, buf);
    
    /* The parser will segfault and reset the board if "led" isn't contained. */
    if (parser.hasMember("led")) {
        std::string led_str;
        led_str = parser["led"].get<std::string>();
        
        if (led_str.compare("ON") == 0) {
            logDebug("Turning LED ON");
            led = 0; // Active LOW
        } else {
            logDebug("Turning LED OFF");
            led = 1; // Active LOW
        }
    }
}


/* 
 * This function connects to Sync via MQTT. We connect using the key, password, 
 * and device name defined as constants above, and checks the server
 * certificate.
 * 
 * If everything works, we subscribe to the document topic and return.
 */
void connect_mqtt()
{
    MQTTPacket_connectData conn_data = MQTTPacket_connectData_initializer;
    conn_data.clientID.cstring = sync_device_name;
    conn_data.username.cstring = sync_key;
    conn_data.password.cstring = sync_password;
    int rc = client.connect(
        mqtt_server, 
        mqtt_port, 
        MQTT_GATEWAY_PROD_ROOT_CA_PEM, 
        conn_data
    );
    logInfo("MQTT connect result: %d", rc);
    
    rc = client.subscribe(
        "sync/docs/BoardLED", 
        MQTT::QOS1, 
        callback
    );
    logInfo("MQTT subscription result: %d", rc);
}


/* 
 * Very basic device loop - all we do is reconnect when disconnected
 */
void loop()
{
    if (client.isConnected()) {
        client.yield(MQTT_HEARTBEAT/2.0);
        wait(MQTT_HEARTBEAT);
    } else {
        wait(MQTT_HEARTBEAT*10);
        connect_mqtt();
    }
    
    // Here's an example of publishing from the MultiConnect Dragonfly.
    // Uncomment until the end of the function to send a 'msg' back to Sync
    // every 5 cycles through the loop! (5*MQTT_HEARTBEAT seconds)
    /*
    static uint32_t ticks = 0;
    MQTT::Message message;
    char buf[maxMQTTpackageSize] = "{\"msg\":\"Ahoy!\",\"led\":\"ON\"}";
    message.qos = MQTT::QOS1;
    message.payload = (void*)buf;
    message.payloadlen = strlen(buf) + 1;
    if (ticks++ > 4) {
            logInfo("Sending ON message to Twilio!");
            client.publish(
                    sync_document, 
                    message
            );
            ticks = 0;
    }
    */
}


/* 
 * In main, we configure our LEDs, connect to Twilio Programmable Wireless,
 * and initialize CyaSSL. We then connect our MQTT client for the first time.
 *
 * When done, we pass control to the MQTT loop, which handles yield()s.
 */
int main() 
{
    led = 1;  // Active LOW
    bc_nce = 1;
    Serial debug(USBTX, USBRX);
    debug.baud(115200);
    mts::MTSLog::setLogLevel(mts::MTSLog::TRACE_LEVEL);

    // Be sure your SIM is registered in the Twilio console.
    // https://www.twilio.com/console/wireless/sims/
    logInfo("Initializing Twilio Programmable Wireless");
    MTSCellularManager cellularManager("wireless.twilio.com");   
    if (! cellularManager.init()) {
        while (true) {
            logError("failed to initialize cellular radio"); wait(10);  
        }
    }
    CyaSSL_Init();
    connect_mqtt();

    /* We're done; pass off control to the loop */
    while (1) {
       loop();
    }
}
SDK Version:
  • 5.x
Response Format:
  • json
SDK Version:
  • 7.x
SDK Version:
  • 3.x
SDK Version:
  • 5.x
SDK Version:
  • 6.x
SDK Version:
  • 5.x
Format:
  • JSON
const accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
const authToken = 'your_auth_token';
const Twilio = require('twilio').Twilio;

const client = new Twilio(accountSid, authToken);
const service = client.sync.services('default');

service
  .documents('BoardLED')
  .update({
    data: { led: 'ON' },
  })
  .then(response => {
    console.log(response);
  })
  .catch(error => {
    console.log(error);
  });
// Download the twilio-csharp library from twilio.com/docs/libraries/csharp
using System;
using Twilio;
using Twilio.Rest.Sync.V1.Service;

public class Example
{
    public static void Main(string[] args)
    {
        // Find your Account SID and Auth Token at twilio.com/console
        const string accountSid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
        const string authToken = "your_auth_token";
        const string serviceSid = "default";

        TwilioClient.Init(accountSid, authToken);

        var data = new
        {
            led = "ON"
        };

        var doc = DocumentResource.Update(serviceSid,
                                          "BoardLED",
                                          data);

        Console.WriteLine(doc.Data);
    }
}
<?php
// NOTE: This example uses the next generation Twilio helper library - for more
// information on how to download and install this version, visit
// https://www.twilio.com/docs/libraries/php
require_once 'vendor/autoload.php';

use Twilio\Rest\Client;

// Your Account SID from www.twilio.com/console
$sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
// Your Auth Token from www.twilio.com/console
$token = "your_auth_token";

$client = new Client($sid, $token);

$data = array(
    'led' => "ON"
);

$doc = $client->sync
    ->services("default")
    ->documents("BoardLED")->update(
        array(
            'led' => $data
        )
    );

print_r($doc->data);
echo PHP_EOL;
require 'twilio-ruby'

# Initialize the client
account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
auth_token = 'your_auth_token'
client = Twilio::REST::Client.new(account_sid, auth_token)

# Retreive the service
service = client.sync.v1.services('default')

# Update the Document, data can be any JSON
response = service.documents('BoardLED').update(
  data: '{ "led": "ON" }'
)

puts response
# Download the Python helper library from twilio.com/docs/python/install
from twilio.rest import Client

# Your Account Sid and Auth Token from twilio.com/user/account
account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
auth_token = "your_auth_token"
client = Client(account_sid, auth_token)

new_data = {
    'led': "ON"
}

document = client.sync \
    .services("default") \
    .documents("BoardLED") \
    .update(data=new_data)

print(document.data)
// Install the Java helper library from twilio.com/docs/java/install
import java.util.HashMap;
import java.util.Map;

import com.twilio.Twilio;
import com.twilio.rest.sync.v1.service.Document;

public class Example {
  // Find your Account Sid and Token at twilio.com/user/account
  public static final String ACCOUNT_SID = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
  public static final String AUTH_TOKEN = "your_auth_token";

  public static final String SERVICE_SID = "default";

  public static void main(String[] args) {
    Twilio.init(ACCOUNT_SID, AUTH_TOKEN);

    Map<String, Object> data = new HashMap<>();
    data.put("led", "ON");

    Document document = Document.updater(SERVICE_SID, "BoardLED", data).update();

    System.out.println(document.getData());
  }
}
curl -X POST https://sync.twilio.com/v1/Services/default/Documents/BoardLED \
 -d 'Data={"led":"ON"}'  \
 -u 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX:your_auth_token'
{
  "unique_name": "BoardLED",
  "url": "https://sync.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Documents/ETXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "created_by": "system",
  "account_sid": "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "date_created": "2017-09-06T20:53:38Z",
  "date_updated": "2017-09-06T20:55:21Z",
  "sid": "ETXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "service_sid": "ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "data": {
    "led": "ON"
  },
  "revision": "1",
  "links": {
    "permissions": "https://sync.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Documents/ETXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Permissions"
  }
}
#include <mbed.h>
#include <mtsas.h>
#include <ssl.h>
#include <MbedJSONValue.h>
#include <string>
#include "MTSCellularManager.hpp"
#include "TlsMQTTClient.hpp"
#include "certificates.hpp"

/* 
 *  Sync Settings
 *  
 *  Enter a Sync Key & Password, your document unique name, 
 *  and the device name
 */
char* sync_key                          = "KYXXXXXXXXXXXXXXXXXXXX";
char* sync_password                     = "SECRET_HERE";
char* sync_document                     = "sync/docs/BoardLED";
char* sync_device_name                  = "MultiConnect Dragonfly";

/* Sync server and MQTT setup; you probably don't have to change these. */
const char* mqtt_server                 = "mqtt-sync.us1.twilio.com";
const uint16_t mqtt_port                = 8883;
const uint16_t maxMQTTpackageSize       = 512;

TlsMQTTClient client = TlsMQTTClient();
DigitalOut led(D7);
DigitalOut bc_nce(PB_2);
const uint8_t MQTT_HEARTBEAT = 15;

/* 
 * Our Twilio Connected Devices message handling callback.  This is passed as a 
 * callback function when we subscribe to the document, and any messages will 
 * appear here.
 */
void callback(MQTT::MessageData& data) 
{
    if (data.message.payloadlen > maxMQTTpackageSize) {
        return;
    }
    char buf[maxMQTTpackageSize + 1];
    strncpy(buf, (char*)data.message.payload, data.message.payloadlen);
    buf[data.message.payloadlen] = '\0';
    
    logDebug("Received new update %s", buf);
    /* JSON Parse 'led' */
    MbedJSONValue parser;
    parse(parser, buf);
    
    /* The parser will segfault and reset the board if "led" isn't contained. */
    if (parser.hasMember("led")) {
        std::string led_str;
        led_str = parser["led"].get<std::string>();
        
        if (led_str.compare("ON") == 0) {
            logDebug("Turning LED ON");
            led = 0; // Active LOW
        } else {
            logDebug("Turning LED OFF");
            led = 1; // Active LOW
        }
    }
}


/* 
 * This function connects to Sync via MQTT. We connect using the key, password, 
 * and device name defined as constants above, and checks the server
 * certificate.
 * 
 * If everything works, we subscribe to the document topic and return.
 */
void connect_mqtt()
{
    MQTTPacket_connectData conn_data = MQTTPacket_connectData_initializer;
    conn_data.clientID.cstring = sync_device_name;
    conn_data.username.cstring = sync_key;
    conn_data.password.cstring = sync_password;
    int rc = client.connect(
        mqtt_server, 
        mqtt_port, 
        MQTT_GATEWAY_PROD_ROOT_CA_PEM, 
        conn_data
    );
    logInfo("MQTT connect result: %d", rc);
    
    rc = client.subscribe(
        "sync/docs/BoardLED", 
        MQTT::QOS1, 
        callback
    );
    logInfo("MQTT subscription result: %d", rc);
}


/* 
 * Very basic device loop - all we do is reconnect when disconnected
 */
void loop()
{
    if (client.isConnected()) {
        client.yield(MQTT_HEARTBEAT/2.0);
        wait(MQTT_HEARTBEAT);
    } else {
        wait(MQTT_HEARTBEAT*10);
        connect_mqtt();
    }
    
    // Here's an example of publishing from the MultiConnect Dragonfly.
    // Uncomment until the end of the function to send a 'msg' back to Sync
    // every 5 cycles through the loop! (5*MQTT_HEARTBEAT seconds)
    /*
    static uint32_t ticks = 0;
    MQTT::Message message;
    char buf[maxMQTTpackageSize] = "{\"msg\":\"Ahoy!\",\"led\":\"ON\"}";
    message.qos = MQTT::QOS1;
    message.payload = (void*)buf;
    message.payloadlen = strlen(buf) + 1;
    if (ticks++ > 4) {
            logInfo("Sending ON message to Twilio!");
            client.publish(
                    sync_document, 
                    message
            );
            ticks = 0;
    }
    */
}


/* 
 * In main, we configure our LEDs, connect to Twilio Programmable Wireless,
 * and initialize CyaSSL. We then connect our MQTT client for the first time.
 *
 * When done, we pass control to the MQTT loop, which handles yield()s.
 */
int main() 
{
    led = 1;  // Active LOW
    bc_nce = 1;
    Serial debug(USBTX, USBRX);
    debug.baud(115200);
    mts::MTSLog::setLogLevel(mts::MTSLog::TRACE_LEVEL);

    // Be sure your SIM is registered in the Twilio console.
    // https://www.twilio.com/console/wireless/sims/
    logInfo("Initializing Twilio Programmable Wireless");
    MTSCellularManager cellularManager("wireless.twilio.com");   
    if (! cellularManager.init()) {
        while (true) {
            logError("failed to initialize cellular radio"); wait(10);  
        }
    }
    CyaSSL_Init();
    connect_mqtt();

    /* We're done; pass off control to the loop */
    while (1) {
       loop();
    }
}