Using Twilio Sync with MQTT on an ESP8266

In this guide, we'll show you how to use the lightweight messaging protocol MQTT with Twilio Sync for IoT, an Espressif ESP8266, and the Arduino IDE.  We'll show how to use the Twilio Device Manager and set up a Device Fleet as well as how to connect your ESP8266 to Sync and make API calls to control an LED.

Yes, that's right, blinky lights! Sound good?  Let's dive in...

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 Into - or Register For - a Twilio Account

Create a new Twilio account (sign up for a free Twilio trial here), or sign into your existing Twilio account.

Once you are logged in, navigate to Twilio Device Manager.

Deploy a Fleet of ESP8266 Things

In Sync parlance, a Device Fleet is a collection of devices, keys, certificates, and configurations.  You can have more than one fleet, but fleets themselves are isolated - a sometimes necessary feature when you need to keep collections of things from inadvertantly interacting with each other.

A default Fleet is already provisioned for you automatically, get started by navigating to it in the Device Management console:

Locating the default Ffleet in the Twilio Console

Optionally, you can also provision a new fleet using 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
// Download the helper library from https://www.twilio.com/docs/node/install
// Your Account Sid and Auth Token from twilio.com/console
const accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
const authToken = 'your_auth_token';
const client = require('twilio')(accountSid, authToken);

client.preview.deployed_devices.fleets
                               .create({friendlyName: 'My Fleet of Devices'})
                               .then(fleet => console.log(fleet.sid))
                               .done();
// Install the C# / .NET helper library from twilio.com/docs/csharp/install

using System;
using Twilio;
using Twilio.Rest.Preview.DeployedDevices;


class Program 
{
    static void Main(string[] args)
    {
        // Find your Account Sid and Token at 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

// Update the path below to your autoload.php,
// see https://getcomposer.org/doc/01-basic-usage.md
require_once '/path/to/vendor/autoload.php';

use Twilio\Rest\Client;

// Your Account Sid and Auth Token from twilio.com/console
$sid    = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
$token  = "your_auth_token";
$twilio = new Client($sid, $token);

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

print($fleet->sid);
# Download the helper library from https://www.twilio.com/docs/ruby/install
require 'rubygems'
require 'twilio-ruby'

# Your Account Sid and Auth Token from 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
# Download the helper library from https://www.twilio.com/docs/python/install
from twilio.rest import Client


# Your Account Sid and Auth Token from 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)
// Install the Java helper library from twilio.com/docs/java/install

import com.twilio.Twilio;
import com.twilio.rest.preview.deployedDevices.Fleet;

public class Example {
    // Find your Account Sid and Token at 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);
        Fleet fleet = Fleet.creator()
            .setFriendlyName("My Fleet of Devices").create();

        System.out.println(fleet.getSid());
    }
}
curl -X POST https://preview.twilio.com/DeployedDevices/Fleets \
--data-urlencode "FriendlyName=My Fleet of Devices" \
-u ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX:your_auth_token
{
  "sid": "THXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "unique_name": "unique_name",
  "friendly_name": "My Fleet of Devices",
  "account_sid": "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "default_deployment_sid": "DLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "date_created": "2016-07-30T20:00:00Z",
  "date_updated": null,
  "url": "https://preview.twilio.com/DeployedDevices/Fleets/FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "links": {
    "devices": "https://preview.twilio.com/DeployedDevices/Fleets/FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Devices",
    "deployments": "https://preview.twilio.com/DeployedDevices/Fleets/FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Deployments",
    "certificates": "https://preview.twilio.com/DeployedDevices/Fleets/FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Certificates",
    "keys": "https://preview.twilio.com/DeployedDevices/Fleets/FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Keys"
  }
}
Using the API to create a Device Fleet in Ma.
Create a Device Fleet

Using the API to create a Device Fleet in Ma.

Once you are familiar with how Fleets work, we're ready to proceed with a Deployment.

Configure the New Fleet's Deployment

As soon as your fleet is set up, Twilio will automatically configure a default Deployment. You'll see that the 'Default Deployment' field in your Fleet is now populated, as in the following picture:

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

Click through to the new deployment by clicking the link labeled 'Configure the Deployment'.

Every deployment is configured with a default Service Instance.

As you can see in the above screenshot, Twilio also has automatically linked your deployment with a default Sync Service Instance. Instances are similar to databases in a manner; all of the data from the 'conversation' you'll have with the ESP8266 (or any other device in the Deployment we just created) will be stored in this one Sync instance.

You can also configure a new Deployment through the API, as shown in this snippet.

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
// Download the helper library from https://www.twilio.com/docs/node/install
// Your Account Sid and Auth Token from twilio.com/console
const accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
const authToken = 'your_auth_token';
const client = require('twilio')(accountSid, authToken);

client.preview.deployed_devices.fleets('FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
              .deployments('DLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
              .update({friendlyName: 'My New Device Deployment'})
              .then(deployment => console.log(deployment.friendlyName))
              .done();
// Install the C# / .NET helper library from twilio.com/docs/csharp/install

using System;
using Twilio;
using Twilio.Rest.Preview.DeployedDevices.Fleet;


class Program 
{
    static void Main(string[] args)
    {
        // Find your Account Sid and Token at twilio.com/console
        const string accountSid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
        const string authToken = "your_auth_token";

        TwilioClient.Init(accountSid, authToken);

        var deployment = DeploymentResource.Update(
            friendlyName: "My New Device Deployment",
            pathFleetSid: "FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
            pathSid: "DLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
        );

        Console.WriteLine(deployment.FriendlyName);
    }
}
<?php

// Update the path below to your autoload.php,
// see https://getcomposer.org/doc/01-basic-usage.md
require_once '/path/to/vendor/autoload.php';

use Twilio\Rest\Client;

// Your Account Sid and Auth Token from twilio.com/console
$sid    = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
$token  = "your_auth_token";
$twilio = new Client($sid, $token);

$deployment = $twilio->preview->deployedDevices->fleets("FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
                                               ->deployments("DLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
                                               ->update(array(
                                                            "friendlyName" => "My New Device Deployment"
                                                        )
                                               );

print($deployment->friendlyName);
# Download the helper library from https://www.twilio.com/docs/ruby/install
require 'rubygems'
require 'twilio-ruby'

# Your Account Sid and Auth Token from twilio.com/console
account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
auth_token = 'your_auth_token'
@client = Twilio::REST::Client.new(account_sid, auth_token)

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

puts deployment.friendly_name
# Download the helper library from https://www.twilio.com/docs/python/install
from twilio.rest import Client


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

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

print(deployment.friendly_name)
// Install the Java helper library from twilio.com/docs/java/install

import com.twilio.Twilio;
import com.twilio.rest.preview.deployedDevices.fleet.Deployment;

public class Example {
    // Find your Account Sid and Token at 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);
        Deployment deployment = Deployment.updater(
                "FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
                "DLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
            .setFriendlyName("My New Device Deployment").update();

        System.out.println(deployment.getFriendlyName());
    }
}
curl -X POST https://preview.twilio.com/DeployedDevices/Fleets/FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Deployments/DLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX \
--data-urlencode "FriendlyName=My New Device Deployment" \
-u ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX:your_auth_token
{
  "sid": "DLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "friendly_name": "My New Device Deployment",
  "account_sid": "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "fleet_sid": "FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "sync_service_sid": "ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "date_created": "2016-07-30T20:00:00Z",
  "date_updated": "2016-07-30T20:00:00Z",
  "url": "https://preview.twilio.com/DeployedDevices/Fleets/FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Deployments/DLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
}
Update a Device Deployment

Once you've got a handle on the Deployment (and a pointer to the instance), you're ready to create your first Device and a Key for its authentication.

Create an ESP8266 Device and a Device Key

In the Device Manager, a Device refers to a particular piece of hardware. When that hardware connects, Twilio determines which Device it matches based on the credential it provides, either a certificate or a key. We'll set up a Key for our ESP8266, since they're easier to use with the resource constraints of the ESP.

When inside your Fleet, click the 'Devices' link on the left sidebar. Enter a Friendly name or Unique name if you'd like, then hit the 'Create' button.

Create a New ESP8266 Device in Deployed Devices

You can also provision an new Device using the API, as illustrated in this code snippet.

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
// Download the helper library from https://www.twilio.com/docs/node/install
// Your Account Sid and Auth Token from twilio.com/console
const accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
const authToken = 'your_auth_token';
const client = require('twilio')(accountSid, authToken);

client.preview.deployed_devices.fleets('FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
                               .devices
                               .create({friendlyName: 'My Device #1'})
                               .then(device => console.log(device.sid))
                               .done();
// Install the C# / .NET helper library from twilio.com/docs/csharp/install

using System;
using Twilio;
using Twilio.Rest.Preview.DeployedDevices.Fleet;


class Program 
{
    static void Main(string[] args)
    {
        // Find your Account Sid and Token at twilio.com/console
        const string accountSid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
        const string authToken = "your_auth_token";

        TwilioClient.Init(accountSid, authToken);

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

        Console.WriteLine(device.Sid);
    }
}
<?php

// Update the path below to your autoload.php,
// see https://getcomposer.org/doc/01-basic-usage.md
require_once '/path/to/vendor/autoload.php';

use Twilio\Rest\Client;

// Your Account Sid and Auth Token from twilio.com/console
$sid    = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
$token  = "your_auth_token";
$twilio = new Client($sid, $token);

$device = $twilio->preview->deployedDevices->fleets("FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
                                           ->devices
                                           ->create(array(
                                                        "friendlyName" => "My Device #1"
                                                    )
                                           );

print($device->sid);
# Download the helper library from https://www.twilio.com/docs/ruby/install
require 'rubygems'
require 'twilio-ruby'

# Your Account Sid and Auth Token from twilio.com/console
account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
auth_token = 'your_auth_token'
@client = Twilio::REST::Client.new(account_sid, auth_token)

device = @client.preview.deployed_devices
                        .fleets('FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
                        .devices
                        .create(friendly_name: 'My Device #1')

puts device.sid
# Download the helper library from https://www.twilio.com/docs/python/install
from twilio.rest import Client


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

device = client.preview.deployed_devices \
                       .fleets('FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \
                       .devices \
                       .create(friendly_name='My Device #1')

print(device.sid)
// Install the Java helper library from twilio.com/docs/java/install

import com.twilio.Twilio;
import com.twilio.rest.preview.deployedDevices.fleet.Device;

public class Example {
    // Find your Account Sid and Token at 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 = Device.creator("FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
            .setFriendlyName("My Device #1").create();

        System.out.println(device.getSid());
    }
}
curl -X POST https://preview.twilio.com/DeployedDevices/Fleets/FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Devices \
--data-urlencode "FriendlyName=My Device #1" \
-u ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX:your_auth_token
{
  "sid": "THXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "unique_name": "unique_name",
  "friendly_name": "My Device #1",
  "account_sid": "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "fleet_sid": "FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "enabled": true,
  "deployment_sid": "DLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "identity": "bob@twilio.com",
  "date_created": "2016-07-30T20:00:00Z",
  "date_updated": "2016-07-30T20:00:00Z",
  "date_authenticated": null,
  "url": "https://preview.twilio.com/DeployedDevices/Fleets/FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Devices/THXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
}
Create a Device

Next, when in your Device configuration, click the 'Keys' link in the left sidebar followed by the red 'Create a Key' button to create a new Device Key.

Create New Device Key Button

Assign a new friendly name to the Device Key; the Device SID should automatically be populated (but can always be recovered in the console by navigating back into the Deployment to your Device).  Save both the Key and the Secret once your key is created - you cannot recover the secret once it is shown!

Create a Device Key in Sync Deployed Devices

Note that you can also create and delete Device Keys using the API.  This code sample shows you how to do this programmatically.

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
// Download the helper library from https://www.twilio.com/docs/node/install
// Your Account Sid and Auth Token from twilio.com/console
const accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
const authToken = 'your_auth_token';
const client = require('twilio')(accountSid, authToken);

client.preview.deployed_devices.fleets('FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
              .keys
              .create({deviceSid: 'THXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'})
              .then(key => console.log(key.sid))
              .done();
// Install the C# / .NET helper library from twilio.com/docs/csharp/install

using System;
using Twilio;
using Twilio.Rest.Preview.DeployedDevices.Fleet;


class Program 
{
    static void Main(string[] args)
    {
        // Find your Account Sid and Token at twilio.com/console
        const string accountSid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
        const string authToken = "your_auth_token";

        TwilioClient.Init(accountSid, authToken);

        var key = KeyResource.Create(
            deviceSid: "THXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
            pathFleetSid: "FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
        );

        Console.WriteLine(key.Sid);
    }
}
<?php

// Update the path below to your autoload.php,
// see https://getcomposer.org/doc/01-basic-usage.md
require_once '/path/to/vendor/autoload.php';

use Twilio\Rest\Client;

// Your Account Sid and Auth Token from twilio.com/console
$sid    = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
$token  = "your_auth_token";
$twilio = new Client($sid, $token);

$key = $twilio->preview->deployedDevices->fleets("FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
                                        ->keys
                                        ->create(array(
                                                     'deviceSid' => "THXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
                                                 )
                                        );

print($key->sid);
# Download the helper library from https://www.twilio.com/docs/ruby/install
require 'rubygems'
require 'twilio-ruby'

# Your Account Sid and Auth Token from twilio.com/console
account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
auth_token = 'your_auth_token'
@client = Twilio::REST::Client.new(account_sid, auth_token)

key = @client.preview.deployed_devices
                     .fleets('FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
                     .keys
                     .create(device_sid: 'THXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')

puts key.sid
# Download the helper library from https://www.twilio.com/docs/python/install
from twilio.rest import Client


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

key = client.preview.deployed_devices \
                    .fleets('FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \
                    .keys \
                    .create(device_sid='THXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')

print(key.sid)
// Install the Java helper library from twilio.com/docs/java/install

import com.twilio.Twilio;
import com.twilio.rest.preview.deployedDevices.fleet.Key;

public class Example {
    // Find your Account Sid and Token at 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);
        Key key = Key.creator("FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
            .setDeviceSid("THXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").create();

        System.out.println(key.getSid());
    }
}
curl -X POST https://preview.twilio.com/DeployedDevices/Fleets/FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Keys \
--data-urlencode "DeviceSid=THXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" \
-u ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX:your_auth_token
{
  "sid": "KYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "friendly_name": "friendly_name",
  "account_sid": "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "fleet_sid": "FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "device_sid": "THXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "secret": null,
  "date_created": "2016-07-30T20:00:00Z",
  "date_updated": null,
  "url": "https://preview.twilio.com/DeployedDevices/Fleets/FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Keys/KYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
}
Create a Device Key

In the C++ Arduino code, 'KEY' will take the value of sync_key, while 'SECRET' will take sync_password.

Create a Sync Document

A Document is a simple type of Sync object which is perfect for sharing state in a small application such as this.  Note that you have to create a Document before you connect your ESP8266 to Sync; the document's name will become the MQTT topic to which the ESP8266 will subscribe.

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
// Download the helper library from https://www.twilio.com/docs/node/install
// Your Account Sid and Auth Token from twilio.com/console
const accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
const authToken = 'your_auth_token';
const client = require('twilio')(accountSid, authToken);

client.sync.services('default').documents
                               .create({data: {
                                    led: "OFF"
                                }, uniqueName: 'BoardLED'})
                               .then(document => console.log(document.sid))
                               .done();
// Install the C# / .NET helper library from twilio.com/docs/csharp/install

using System;
using Twilio;
using Twilio.Rest.Sync.V1.Service;


class Program 
{
    static void Main(string[] args)
    {
        // Find your Account Sid and Token at twilio.com/console
        const string accountSid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
        const string authToken = "your_auth_token";

        TwilioClient.Init(accountSid, authToken);

        var document = DocumentResource.Create(
            data: "{\"led\": \"OFF\"}",
            uniqueName: "BoardLED",
            pathServiceSid: "default"
        );

        Console.WriteLine(document.Sid);
    }
}
<?php

// Update the path below to your autoload.php,
// see https://getcomposer.org/doc/01-basic-usage.md
require_once '/path/to/vendor/autoload.php';

use Twilio\Rest\Client;

// Your Account Sid and Auth Token from twilio.com/console
$sid    = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
$token  = "your_auth_token";
$twilio = new Client($sid, $token);

$document = $twilio->sync->v1->services("default")
                             ->documents
                             ->create(array(
                                          'data' => array(
                                              "led" => "OFF"
                                          ),
                                          'uniqueName' => "BoardLED"
                                      )
                             );

print($document->sid);
# Download the helper library from https://www.twilio.com/docs/ruby/install
require 'rubygems'
require 'twilio-ruby'

# Your Account Sid and Auth Token from twilio.com/console
account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
auth_token = 'your_auth_token'
@client = Twilio::REST::Client.new(account_sid, auth_token)

document = @client.sync.services('default').documents.create(
                                                        data: {
                                                          "led" => "OFF"
                                                      },
                                                        unique_name: 'BoardLED'
                                                      )

puts document.sid
# Download the helper library from https://www.twilio.com/docs/python/install
from twilio.rest import Client


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

document = client.sync.services('default').documents.create(data={
                                                         'led': 'OFF'
                                                     }, unique_name='BoardLED')

print(document.sid)
// Install the Java helper library from twilio.com/docs/java/install

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

import java.util.HashMap;

public class Example {
    // Find your Account Sid and Token at 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);
        Document document = Document.creator("default")
            .setData(new HashMap<String, Object>()
            {{ put(&quot;led&quot;, &quot;OFF&quot;); }})
            .setUniqueName("BoardLED")
            .create();

        System.out.println(document.getSid());
    }
}
DATA=$(cat << EOF
{
    "led": "OFF"
}
EOF
)

curl -X POST https://sync.twilio.com/v1/Services/default/Documents \
--data-urlencode "Data=$DATA" \
--data-urlencode "UniqueName=BoardLED" \
-u ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX:your_auth_token
{
  "account_sid": "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "created_by": "created_by",
  "data": "{\"led\": \"OFF\"}",
  "date_expires": "2015-07-30T21:00:00Z",
  "date_created": "2015-07-30T20:00:00Z",
  "date_updated": "2015-07-30T20:00:00Z",
  "revision": "revision",
  "service_sid": "default",
  "sid": "ETXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "unique_name": "BoardLED",
  "url": "https://sync.twilio.com/v1/Services/default/Documents/ETXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "links": {
    "permissions": "https://sync.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Documents/ETXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Permissions"
  }
}
Create a BoardLED Document

While creating it, also initialize 'led' to 'OFF'; we'll use that in the code to... keep the LED off when your ESP first connects.

Prerequisites to Use an ESP8266 with Sync

Grab our code for the ESP8266 here.

For this quickstart's development, we used a NodeMCU ESP8266 development board with the Arduino IDE.  Any other suitable ESP8266 with a LED defined as LED_BUILTIN would work (as would moving outside of the Arduino ecosystem) but is beyond the scope of this guide.

In the Arduino IDE, install two libraries:

  • ArduinoJSON (by Benoit Blanchon - GitHub)
  • PubSubClient (by Nick O'Leary - GitHub)

In recent versions of the IDE the Library Manager can be reached by a menu path similar to 'Sketch' -> 'Include Library' -> 'Library Manager'.  Both libraries can be installed an managed through the Arduino IDE.

Edit the Code for Your WiFi Network and For Sync

You'll need to make edits to the C++ sketch in order to get it to work on your network and with your deployment, device, and keys.  First, ensure your ESP8266 can connect to a friendly Wireless Network by changing:

  • ssid
  • password

Next, you will need to change two variables and an optional two more to connect to your deployment.

Loading Code Samples...
Language
#include "ESP8266WiFi.h"
#include "WiFiClientSecure.h"
#include <PubSubClient.h>
#include <ArduinoJson.h>

/* WiFi SSID and Password */
const char* ssid                        = "YOUR_SSID";
const char* password                    = "WIFI_PASSWORD";

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

/* 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;

void callback(char *, byte*, unsigned int);
WiFiClientSecure espClient;
PubSubClient client(mqtt_server, mqtt_port, callback, espClient);

/* 
 * Only use the fingerprint if you have a certificate rotation strategy in place.
 * It can be enabled by setting the use_fingerprint boolean to 'true'
 *  
 * SHA1 Fingerprint valid as of August 2017, but if it expires:
 * On *NIX systems with openssl installed, you can check the fingerprint with
 * 
 * echo | openssl s_client -connect mqtt-sync.us1.twilio.com:8883 | openssl x509 -fingerprint
 * 
 * ... and look for the 'SHA1 Fingerprint' line.
 */
const char* fingerprint         = \
        "4E:D6:B4:16:83:9F:86:86:0E:8B:BA:47:F6:FC:3F:65:29:B6:E1:13";
const bool use_fingerprint      = false;


/* 
 * 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(char* topic, byte* payload, unsigned int length) 
{
        std::unique_ptr<char []> msg(new char[length+1]());
        memcpy (msg.get(), payload, length);

        Serial.print("Message arrived on topic "); Serial.println(msg.get());
        
        StaticJsonBuffer<maxMQTTpackageSize> jsonBuffer;
        JsonObject& root = jsonBuffer.parseObject(msg.get());
        String led_command           = root["led"];

        if (led_command == "ON") {
                digitalWrite(BUILTIN_LED, LOW);
                Serial.println("LED turned on!");
        } else {
                digitalWrite(BUILTIN_LED, HIGH);
                Serial.println("LED turned off!");
        }
}

/* 
 * This function connects to Sync via MQTT. We connect using the key, password, and 
 * device name defined as constants above, and immediately check the server's 
 * certificate fingerprint (if desired).
 * 
 * If everything works, we subscribe to the document topic and return.
 */
void connect_mqtt() 
{
        while (!client.connected()) {
                Serial.println("Attempting to connect to Twilio Sync...");
                if (client.connect(sync_device_name, sync_key, sync_password)) {
                        /* Verify you are talking to Twilio */
                        if (!use_fingerprint || espClient.verify(fingerprint, mqtt_server)) {
                                Serial.print("Connected!  Subscribing to "); Serial.println(sync_document);
                                client.subscribe(sync_document);
                        } else {
                                Serial.println("Certificate mismatch!  Check fingerprint.");
                                client.disconnect();
                                while(1);
                        }
                } else {
                        Serial.print("failed, rc=");
                        Serial.print(client.state());
                        delay(10000);
                }
        }
}

/* In setup, we configure our LED for output, turn it off, and connect to WiFi */
void setup() 
{
        pinMode(BUILTIN_LED, OUTPUT);
        digitalWrite(BUILTIN_LED, HIGH); // Active LOW LED
        
        Serial.begin(115200);
        WiFi.begin(ssid, password);

        while (WiFi.status() != WL_CONNECTED) {
                delay(1000);
                Serial.print(".");
        }

        randomSeed(micros());

        Serial.print("\nWiFi connected!  IP address: ");
        Serial.println(WiFi.localIP());
}

/* Our loop constantly checks we are still connected.  On disconnects we try again. */
void loop() 
{
        if (!client.connected()) {
                connect_mqtt();
        }
        client.loop();
        
        // Here's an example of publishing from the ESP8266.
        // Uncomment until the end of the function to send a 'msg' back to Sync
        // every 2 minutes!
        /*
        static uint32_t now = millis();
        if (millis() > now + (2*(1000*60))) {
                Serial.println("Sending 2 minute ON message to Twilio!");
                client.publish(
                        sync_document, 
                        "{\"msg\":\"Ahoy!\",\"led\":\"ON\"}\0"
                );
                now = millis();
        }
        */
}
Modify SSID and WiFi password for a friendly network, and add your Sync for IoT credentials.
Edit your WiFi and Sync Credentials

Modify SSID and WiFi password for a friendly network, and add your Sync for IoT credentials.

 Matching the instructions above, change:

  • sync_key
  • sync_password

The next two may not have to change; if you didn't name your Sync Document 'BoardLED' you will have to change it here though.

  • sync_document
  • sync_device_name

Once all the variables are set, you're ready to rock.  Upload the code to the board and open the Arduino Serial Monitor ('Tools' -> 'Serial Monitor').  If all goes well, you should see a happy message log similar to the following:

.......
WiFi connected!  IP address: 192.168.1.169
Attempting to connect to Twilio Sync...
Connected!  Subscribing to sync/docs/BoardLED
Message arrived on topic {"led":"OFF"}
LED turned off!

But there's one more step... blinking that LED!  Modify the above Document with the Update command, now setting 'led' to 'ON'.

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
// Download the helper library from https://www.twilio.com/docs/node/install
// Your Account Sid and Auth Token from twilio.com/console
const accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
const authToken = 'your_auth_token';
const client = require('twilio')(accountSid, authToken);

client.sync.services('default').documents('BoardLED')
           .update({data: {
                led: "ON"
            }})
           .then(document => console.log(document.uniqueName))
           .done();
// Install the C# / .NET helper library from twilio.com/docs/csharp/install

using System;
using Twilio;
using Twilio.Rest.Sync.V1.Service;


class Program 
{
    static void Main(string[] args)
    {
        // Find your Account Sid and Token at twilio.com/console
        const string accountSid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
        const string authToken = "your_auth_token";

        TwilioClient.Init(accountSid, authToken);

        var document = DocumentResource.Update(
            data: "{\"led\": \"ON\"}",
            pathServiceSid: "default",
            pathSid: "BoardLED"
        );

        Console.WriteLine(document.UniqueName);
    }
}
<?php

// Update the path below to your autoload.php,
// see https://getcomposer.org/doc/01-basic-usage.md
require_once '/path/to/vendor/autoload.php';

use Twilio\Rest\Client;

// Your Account Sid and Auth Token from twilio.com/console
$sid    = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
$token  = "your_auth_token";
$twilio = new Client($sid, $token);

$document = $twilio->sync->v1->services("default")
                             ->documents("BoardLED")
                             ->update(array(
                                          'data' => array(
                                              "led" => "ON"
                                          )
                                      )
                             );

print($document->uniqueName);
# Download the helper library from https://www.twilio.com/docs/ruby/install
require 'rubygems'
require 'twilio-ruby'

# Your Account Sid and Auth Token from twilio.com/console
account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
auth_token = 'your_auth_token'
@client = Twilio::REST::Client.new(account_sid, auth_token)

document = @client.sync.services('default').documents('BoardLED')
                                           .update(data: {
                                                "led" => "ON"
                                            })

puts document.unique_name
# Download the helper library from https://www.twilio.com/docs/python/install
from twilio.rest import Client


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

document = client.sync.services('default').documents('BoardLED') \
                                          .update(data={
                                               'led': 'ON'
                                           })

print(document.unique_name)
// Install the Java helper library from twilio.com/docs/java/install

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

import java.util.HashMap;

public class Example {
    // Find your Account Sid and Token at 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);
        Document document = Document.updater("default", "BoardLED")
            .setData(new HashMap<String, Object>()
            {{ put(&quot;led&quot;, &quot;ON&quot;); }})
            .update();

        System.out.println(document.getUniqueName());
    }
}
DATA=$(cat << EOF
{
    "led": "ON"
}
EOF
)

curl -X POST https://sync.twilio.com/v1/Services/default/Documents/BoardLED \
--data-urlencode "Data=$DATA" \
-u ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX:your_auth_token
{
  "account_sid": "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "created_by": "created_by",
  "data": "{\"led\": \"ON\"}",
  "date_expires": "2015-07-30T21:00:00Z",
  "date_created": "2015-07-30T20:00:00Z",
  "date_updated": "2015-07-30T20:00:00Z",
  "revision": "revision",
  "service_sid": "default",
  "sid": "BoardLED",
  "unique_name": "unique_name",
  "url": "https://sync.twilio.com/v1/Services/default/Documents/BoardLED",
  "links": {
    "permissions": "https://sync.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Documents/ETXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Permissions"
  }
}
Update a BoardLED Document

You should see two updates - one from Sync informing you the update went through, and another on the device - both lighting the LED and sending a message over serial.

ESP8266 Connected to Sync over MQTT

Updating Sync from the ESP8266

We've also included some commented out lines which show how to send information back to Sync from the ESP8266.  Remove the comment here to send a msg back to Sync!

Loading Code Samples...
Language
#include "ESP8266WiFi.h"
#include "WiFiClientSecure.h"
#include <PubSubClient.h>
#include <ArduinoJson.h>

/* WiFi SSID and Password */
const char* ssid                        = "YOUR_SSID";
const char* password                    = "WIFI_PASSWORD";

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

/* 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;

void callback(char *, byte*, unsigned int);
WiFiClientSecure espClient;
PubSubClient client(mqtt_server, mqtt_port, callback, espClient);

/* 
 * Only use the fingerprint if you have a certificate rotation strategy in place.
 * It can be enabled by setting the use_fingerprint boolean to 'true'
 *  
 * SHA1 Fingerprint valid as of August 2017, but if it expires:
 * On *NIX systems with openssl installed, you can check the fingerprint with
 * 
 * echo | openssl s_client -connect mqtt-sync.us1.twilio.com:8883 | openssl x509 -fingerprint
 * 
 * ... and look for the 'SHA1 Fingerprint' line.
 */
const char* fingerprint         = \
        "4E:D6:B4:16:83:9F:86:86:0E:8B:BA:47:F6:FC:3F:65:29:B6:E1:13";
const bool use_fingerprint      = false;


/* 
 * 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(char* topic, byte* payload, unsigned int length) 
{
        std::unique_ptr<char []> msg(new char[length+1]());
        memcpy (msg.get(), payload, length);

        Serial.print("Message arrived on topic "); Serial.println(msg.get());
        
        StaticJsonBuffer<maxMQTTpackageSize> jsonBuffer;
        JsonObject& root = jsonBuffer.parseObject(msg.get());
        String led_command           = root["led"];

        if (led_command == "ON") {
                digitalWrite(BUILTIN_LED, LOW);
                Serial.println("LED turned on!");
        } else {
                digitalWrite(BUILTIN_LED, HIGH);
                Serial.println("LED turned off!");
        }
}

/* 
 * This function connects to Sync via MQTT. We connect using the key, password, and 
 * device name defined as constants above, and immediately check the server's 
 * certificate fingerprint (if desired).
 * 
 * If everything works, we subscribe to the document topic and return.
 */
void connect_mqtt() 
{
        while (!client.connected()) {
                Serial.println("Attempting to connect to Twilio Sync...");
                if (client.connect(sync_device_name, sync_key, sync_password)) {
                        /* Verify you are talking to Twilio */
                        if (!use_fingerprint || espClient.verify(fingerprint, mqtt_server)) {
                                Serial.print("Connected!  Subscribing to "); Serial.println(sync_document);
                                client.subscribe(sync_document);
                        } else {
                                Serial.println("Certificate mismatch!  Check fingerprint.");
                                client.disconnect();
                                while(1);
                        }
                } else {
                        Serial.print("failed, rc=");
                        Serial.print(client.state());
                        delay(10000);
                }
        }
}

/* In setup, we configure our LED for output, turn it off, and connect to WiFi */
void setup() 
{
        pinMode(BUILTIN_LED, OUTPUT);
        digitalWrite(BUILTIN_LED, HIGH); // Active LOW LED
        
        Serial.begin(115200);
        WiFi.begin(ssid, password);

        while (WiFi.status() != WL_CONNECTED) {
                delay(1000);
                Serial.print(".");
        }

        randomSeed(micros());

        Serial.print("\nWiFi connected!  IP address: ");
        Serial.println(WiFi.localIP());
}

/* Our loop constantly checks we are still connected.  On disconnects we try again. */
void loop() 
{
        if (!client.connected()) {
                connect_mqtt();
        }
        client.loop();
        
        // Here's an example of publishing from the ESP8266.
        // Uncomment until the end of the function to send a 'msg' back to Sync
        // every 2 minutes!
        /*
        static uint32_t now = millis();
        if (millis() > now + (2*(1000*60))) {
                Serial.println("Sending 2 minute ON message to Twilio!");
                client.publish(
                        sync_document, 
                        "{\"msg\":\"Ahoy!\",\"led\":\"ON\"}\0"
                );
                now = millis();
        }
        */
}
Remove the commented lines to send data back through Sync on a timer.
Optionally Send Data Back to Sync

Remove the commented lines to send data back through Sync on a timer.

Note that we're sending back valid JSON, in string form.  Snce you also have it installed, you can also generate JSON through the ArduinoJSON library.

A Fully Synced Internet of Things!

And with that, you've got blinking lights on the ESP8266 all driven through a Sync Document over MQTT!  With your new infrastructure, you can scale up to many devices or go deep on a single one - Twilio's Sync for IoT is ready for whatever you throw at it.

We can't wait to see where you take it - let us know what you've built by sending us pictures on Twitter!

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.

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
// Download the helper library from https://www.twilio.com/docs/node/install
// Your Account Sid and Auth Token from twilio.com/console
const accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
const authToken = 'your_auth_token';
const client = require('twilio')(accountSid, authToken);

client.preview.deployed_devices.fleets
                               .create({friendlyName: 'My Fleet of Devices'})
                               .then(fleet => console.log(fleet.sid))
                               .done();
// Install the C# / .NET helper library from twilio.com/docs/csharp/install

using System;
using Twilio;
using Twilio.Rest.Preview.DeployedDevices;


class Program 
{
    static void Main(string[] args)
    {
        // Find your Account Sid and Token at 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

// Update the path below to your autoload.php,
// see https://getcomposer.org/doc/01-basic-usage.md
require_once '/path/to/vendor/autoload.php';

use Twilio\Rest\Client;

// Your Account Sid and Auth Token from twilio.com/console
$sid    = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
$token  = "your_auth_token";
$twilio = new Client($sid, $token);

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

print($fleet->sid);
# Download the helper library from https://www.twilio.com/docs/ruby/install
require 'rubygems'
require 'twilio-ruby'

# Your Account Sid and Auth Token from 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
# Download the helper library from https://www.twilio.com/docs/python/install
from twilio.rest import Client


# Your Account Sid and Auth Token from 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)
// Install the Java helper library from twilio.com/docs/java/install

import com.twilio.Twilio;
import com.twilio.rest.preview.deployedDevices.Fleet;

public class Example {
    // Find your Account Sid and Token at 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);
        Fleet fleet = Fleet.creator()
            .setFriendlyName("My Fleet of Devices").create();

        System.out.println(fleet.getSid());
    }
}
curl -X POST https://preview.twilio.com/DeployedDevices/Fleets \
--data-urlencode "FriendlyName=My Fleet of Devices" \
-u ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX:your_auth_token
{
  "sid": "THXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "unique_name": "unique_name",
  "friendly_name": "My Fleet of Devices",
  "account_sid": "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "default_deployment_sid": "DLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "date_created": "2016-07-30T20:00:00Z",
  "date_updated": null,
  "url": "https://preview.twilio.com/DeployedDevices/Fleets/FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "links": {
    "devices": "https://preview.twilio.com/DeployedDevices/Fleets/FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Devices",
    "deployments": "https://preview.twilio.com/DeployedDevices/Fleets/FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Deployments",
    "certificates": "https://preview.twilio.com/DeployedDevices/Fleets/FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Certificates",
    "keys": "https://preview.twilio.com/DeployedDevices/Fleets/FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Keys"
  }
}
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
// Download the helper library from https://www.twilio.com/docs/node/install
// Your Account Sid and Auth Token from twilio.com/console
const accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
const authToken = 'your_auth_token';
const client = require('twilio')(accountSid, authToken);

client.preview.deployed_devices.fleets('FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
              .deployments('DLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
              .update({friendlyName: 'My New Device Deployment'})
              .then(deployment => console.log(deployment.friendlyName))
              .done();
// Install the C# / .NET helper library from twilio.com/docs/csharp/install

using System;
using Twilio;
using Twilio.Rest.Preview.DeployedDevices.Fleet;


class Program 
{
    static void Main(string[] args)
    {
        // Find your Account Sid and Token at twilio.com/console
        const string accountSid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
        const string authToken = "your_auth_token";

        TwilioClient.Init(accountSid, authToken);

        var deployment = DeploymentResource.Update(
            friendlyName: "My New Device Deployment",
            pathFleetSid: "FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
            pathSid: "DLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
        );

        Console.WriteLine(deployment.FriendlyName);
    }
}
<?php

// Update the path below to your autoload.php,
// see https://getcomposer.org/doc/01-basic-usage.md
require_once '/path/to/vendor/autoload.php';

use Twilio\Rest\Client;

// Your Account Sid and Auth Token from twilio.com/console
$sid    = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
$token  = "your_auth_token";
$twilio = new Client($sid, $token);

$deployment = $twilio->preview->deployedDevices->fleets("FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
                                               ->deployments("DLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
                                               ->update(array(
                                                            "friendlyName" => "My New Device Deployment"
                                                        )
                                               );

print($deployment->friendlyName);
# Download the helper library from https://www.twilio.com/docs/ruby/install
require 'rubygems'
require 'twilio-ruby'

# Your Account Sid and Auth Token from twilio.com/console
account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
auth_token = 'your_auth_token'
@client = Twilio::REST::Client.new(account_sid, auth_token)

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

puts deployment.friendly_name
# Download the helper library from https://www.twilio.com/docs/python/install
from twilio.rest import Client


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

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

print(deployment.friendly_name)
// Install the Java helper library from twilio.com/docs/java/install

import com.twilio.Twilio;
import com.twilio.rest.preview.deployedDevices.fleet.Deployment;

public class Example {
    // Find your Account Sid and Token at 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);
        Deployment deployment = Deployment.updater(
                "FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
                "DLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
            .setFriendlyName("My New Device Deployment").update();

        System.out.println(deployment.getFriendlyName());
    }
}
curl -X POST https://preview.twilio.com/DeployedDevices/Fleets/FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Deployments/DLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX \
--data-urlencode "FriendlyName=My New Device Deployment" \
-u ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX:your_auth_token
{
  "sid": "DLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "friendly_name": "My New Device Deployment",
  "account_sid": "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "fleet_sid": "FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "sync_service_sid": "ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "date_created": "2016-07-30T20:00:00Z",
  "date_updated": "2016-07-30T20:00:00Z",
  "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
// Download the helper library from https://www.twilio.com/docs/node/install
// Your Account Sid and Auth Token from twilio.com/console
const accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
const authToken = 'your_auth_token';
const client = require('twilio')(accountSid, authToken);

client.preview.deployed_devices.fleets('FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
                               .devices
                               .create({friendlyName: 'My Device #1'})
                               .then(device => console.log(device.sid))
                               .done();
// Install the C# / .NET helper library from twilio.com/docs/csharp/install

using System;
using Twilio;
using Twilio.Rest.Preview.DeployedDevices.Fleet;


class Program 
{
    static void Main(string[] args)
    {
        // Find your Account Sid and Token at twilio.com/console
        const string accountSid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
        const string authToken = "your_auth_token";

        TwilioClient.Init(accountSid, authToken);

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

        Console.WriteLine(device.Sid);
    }
}
<?php

// Update the path below to your autoload.php,
// see https://getcomposer.org/doc/01-basic-usage.md
require_once '/path/to/vendor/autoload.php';

use Twilio\Rest\Client;

// Your Account Sid and Auth Token from twilio.com/console
$sid    = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
$token  = "your_auth_token";
$twilio = new Client($sid, $token);

$device = $twilio->preview->deployedDevices->fleets("FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
                                           ->devices
                                           ->create(array(
                                                        "friendlyName" => "My Device #1"
                                                    )
                                           );

print($device->sid);
# Download the helper library from https://www.twilio.com/docs/ruby/install
require 'rubygems'
require 'twilio-ruby'

# Your Account Sid and Auth Token from twilio.com/console
account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
auth_token = 'your_auth_token'
@client = Twilio::REST::Client.new(account_sid, auth_token)

device = @client.preview.deployed_devices
                        .fleets('FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
                        .devices
                        .create(friendly_name: 'My Device #1')

puts device.sid
# Download the helper library from https://www.twilio.com/docs/python/install
from twilio.rest import Client


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

device = client.preview.deployed_devices \
                       .fleets('FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \
                       .devices \
                       .create(friendly_name='My Device #1')

print(device.sid)
// Install the Java helper library from twilio.com/docs/java/install

import com.twilio.Twilio;
import com.twilio.rest.preview.deployedDevices.fleet.Device;

public class Example {
    // Find your Account Sid and Token at 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 = Device.creator("FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
            .setFriendlyName("My Device #1").create();

        System.out.println(device.getSid());
    }
}
curl -X POST https://preview.twilio.com/DeployedDevices/Fleets/FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Devices \
--data-urlencode "FriendlyName=My Device #1" \
-u ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX:your_auth_token
{
  "sid": "THXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "unique_name": "unique_name",
  "friendly_name": "My Device #1",
  "account_sid": "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "fleet_sid": "FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "enabled": true,
  "deployment_sid": "DLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "identity": "bob@twilio.com",
  "date_created": "2016-07-30T20:00:00Z",
  "date_updated": "2016-07-30T20:00:00Z",
  "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
// Download the helper library from https://www.twilio.com/docs/node/install
// Your Account Sid and Auth Token from twilio.com/console
const accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
const authToken = 'your_auth_token';
const client = require('twilio')(accountSid, authToken);

client.preview.deployed_devices.fleets('FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
              .keys
              .create({deviceSid: 'THXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'})
              .then(key => console.log(key.sid))
              .done();
// Install the C# / .NET helper library from twilio.com/docs/csharp/install

using System;
using Twilio;
using Twilio.Rest.Preview.DeployedDevices.Fleet;


class Program 
{
    static void Main(string[] args)
    {
        // Find your Account Sid and Token at twilio.com/console
        const string accountSid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
        const string authToken = "your_auth_token";

        TwilioClient.Init(accountSid, authToken);

        var key = KeyResource.Create(
            deviceSid: "THXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
            pathFleetSid: "FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
        );

        Console.WriteLine(key.Sid);
    }
}
<?php

// Update the path below to your autoload.php,
// see https://getcomposer.org/doc/01-basic-usage.md
require_once '/path/to/vendor/autoload.php';

use Twilio\Rest\Client;

// Your Account Sid and Auth Token from twilio.com/console
$sid    = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
$token  = "your_auth_token";
$twilio = new Client($sid, $token);

$key = $twilio->preview->deployedDevices->fleets("FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
                                        ->keys
                                        ->create(array(
                                                     'deviceSid' => "THXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
                                                 )
                                        );

print($key->sid);
# Download the helper library from https://www.twilio.com/docs/ruby/install
require 'rubygems'
require 'twilio-ruby'

# Your Account Sid and Auth Token from twilio.com/console
account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
auth_token = 'your_auth_token'
@client = Twilio::REST::Client.new(account_sid, auth_token)

key = @client.preview.deployed_devices
                     .fleets('FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
                     .keys
                     .create(device_sid: 'THXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')

puts key.sid
# Download the helper library from https://www.twilio.com/docs/python/install
from twilio.rest import Client


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

key = client.preview.deployed_devices \
                    .fleets('FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \
                    .keys \
                    .create(device_sid='THXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')

print(key.sid)
// Install the Java helper library from twilio.com/docs/java/install

import com.twilio.Twilio;
import com.twilio.rest.preview.deployedDevices.fleet.Key;

public class Example {
    // Find your Account Sid and Token at 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);
        Key key = Key.creator("FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
            .setDeviceSid("THXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").create();

        System.out.println(key.getSid());
    }
}
curl -X POST https://preview.twilio.com/DeployedDevices/Fleets/FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Keys \
--data-urlencode "DeviceSid=THXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" \
-u ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX:your_auth_token
{
  "sid": "KYXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "friendly_name": "friendly_name",
  "account_sid": "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "fleet_sid": "FLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "device_sid": "THXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "secret": null,
  "date_created": "2016-07-30T20:00:00Z",
  "date_updated": null,
  "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
// Download the helper library from https://www.twilio.com/docs/node/install
// Your Account Sid and Auth Token from twilio.com/console
const accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
const authToken = 'your_auth_token';
const client = require('twilio')(accountSid, authToken);

client.sync.services('default').documents
                               .create({data: {
                                    led: "OFF"
                                }, uniqueName: 'BoardLED'})
                               .then(document => console.log(document.sid))
                               .done();
// Install the C# / .NET helper library from twilio.com/docs/csharp/install

using System;
using Twilio;
using Twilio.Rest.Sync.V1.Service;


class Program 
{
    static void Main(string[] args)
    {
        // Find your Account Sid and Token at twilio.com/console
        const string accountSid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
        const string authToken = "your_auth_token";

        TwilioClient.Init(accountSid, authToken);

        var document = DocumentResource.Create(
            data: "{\"led\": \"OFF\"}",
            uniqueName: "BoardLED",
            pathServiceSid: "default"
        );

        Console.WriteLine(document.Sid);
    }
}
<?php

// Update the path below to your autoload.php,
// see https://getcomposer.org/doc/01-basic-usage.md
require_once '/path/to/vendor/autoload.php';

use Twilio\Rest\Client;

// Your Account Sid and Auth Token from twilio.com/console
$sid    = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
$token  = "your_auth_token";
$twilio = new Client($sid, $token);

$document = $twilio->sync->v1->services("default")
                             ->documents
                             ->create(array(
                                          'data' => array(
                                              "led" => "OFF"
                                          ),
                                          'uniqueName' => "BoardLED"
                                      )
                             );

print($document->sid);
# Download the helper library from https://www.twilio.com/docs/ruby/install
require 'rubygems'
require 'twilio-ruby'

# Your Account Sid and Auth Token from twilio.com/console
account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
auth_token = 'your_auth_token'
@client = Twilio::REST::Client.new(account_sid, auth_token)

document = @client.sync.services('default').documents.create(
                                                        data: {
                                                          "led" => "OFF"
                                                      },
                                                        unique_name: 'BoardLED'
                                                      )

puts document.sid
# Download the helper library from https://www.twilio.com/docs/python/install
from twilio.rest import Client


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

document = client.sync.services('default').documents.create(data={
                                                         'led': 'OFF'
                                                     }, unique_name='BoardLED')

print(document.sid)
// Install the Java helper library from twilio.com/docs/java/install

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

import java.util.HashMap;

public class Example {
    // Find your Account Sid and Token at 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);
        Document document = Document.creator("default")
            .setData(new HashMap<String, Object>()
            {{ put(&quot;led&quot;, &quot;OFF&quot;); }})
            .setUniqueName("BoardLED")
            .create();

        System.out.println(document.getSid());
    }
}
DATA=$(cat << EOF
{
    "led": "OFF"
}
EOF
)

curl -X POST https://sync.twilio.com/v1/Services/default/Documents \
--data-urlencode "Data=$DATA" \
--data-urlencode "UniqueName=BoardLED" \
-u ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX:your_auth_token
{
  "account_sid": "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "created_by": "created_by",
  "data": "{\"led\": \"OFF\"}",
  "date_expires": "2015-07-30T21:00:00Z",
  "date_created": "2015-07-30T20:00:00Z",
  "date_updated": "2015-07-30T20:00:00Z",
  "revision": "revision",
  "service_sid": "default",
  "sid": "ETXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "unique_name": "BoardLED",
  "url": "https://sync.twilio.com/v1/Services/default/Documents/ETXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "links": {
    "permissions": "https://sync.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Documents/ETXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Permissions"
  }
}
#include "ESP8266WiFi.h"
#include "WiFiClientSecure.h"
#include <PubSubClient.h>
#include <ArduinoJson.h>

/* WiFi SSID and Password */
const char* ssid                        = "YOUR_SSID";
const char* password                    = "WIFI_PASSWORD";

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

/* 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;

void callback(char *, byte*, unsigned int);
WiFiClientSecure espClient;
PubSubClient client(mqtt_server, mqtt_port, callback, espClient);

/* 
 * Only use the fingerprint if you have a certificate rotation strategy in place.
 * It can be enabled by setting the use_fingerprint boolean to 'true'
 *  
 * SHA1 Fingerprint valid as of August 2017, but if it expires:
 * On *NIX systems with openssl installed, you can check the fingerprint with
 * 
 * echo | openssl s_client -connect mqtt-sync.us1.twilio.com:8883 | openssl x509 -fingerprint
 * 
 * ... and look for the 'SHA1 Fingerprint' line.
 */
const char* fingerprint         = \
        "4E:D6:B4:16:83:9F:86:86:0E:8B:BA:47:F6:FC:3F:65:29:B6:E1:13";
const bool use_fingerprint      = false;


/* 
 * 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(char* topic, byte* payload, unsigned int length) 
{
        std::unique_ptr<char []> msg(new char[length+1]());
        memcpy (msg.get(), payload, length);

        Serial.print("Message arrived on topic "); Serial.println(msg.get());
        
        StaticJsonBuffer<maxMQTTpackageSize> jsonBuffer;
        JsonObject& root = jsonBuffer.parseObject(msg.get());
        String led_command           = root["led"];

        if (led_command == "ON") {
                digitalWrite(BUILTIN_LED, LOW);
                Serial.println("LED turned on!");
        } else {
                digitalWrite(BUILTIN_LED, HIGH);
                Serial.println("LED turned off!");
        }
}

/* 
 * This function connects to Sync via MQTT. We connect using the key, password, and 
 * device name defined as constants above, and immediately check the server's 
 * certificate fingerprint (if desired).
 * 
 * If everything works, we subscribe to the document topic and return.
 */
void connect_mqtt() 
{
        while (!client.connected()) {
                Serial.println("Attempting to connect to Twilio Sync...");
                if (client.connect(sync_device_name, sync_key, sync_password)) {
                        /* Verify you are talking to Twilio */
                        if (!use_fingerprint || espClient.verify(fingerprint, mqtt_server)) {
                                Serial.print("Connected!  Subscribing to "); Serial.println(sync_document);
                                client.subscribe(sync_document);
                        } else {
                                Serial.println("Certificate mismatch!  Check fingerprint.");
                                client.disconnect();
                                while(1);
                        }
                } else {
                        Serial.print("failed, rc=");
                        Serial.print(client.state());
                        delay(10000);
                }
        }
}

/* In setup, we configure our LED for output, turn it off, and connect to WiFi */
void setup() 
{
        pinMode(BUILTIN_LED, OUTPUT);
        digitalWrite(BUILTIN_LED, HIGH); // Active LOW LED
        
        Serial.begin(115200);
        WiFi.begin(ssid, password);

        while (WiFi.status() != WL_CONNECTED) {
                delay(1000);
                Serial.print(".");
        }

        randomSeed(micros());

        Serial.print("\nWiFi connected!  IP address: ");
        Serial.println(WiFi.localIP());
}

/* Our loop constantly checks we are still connected.  On disconnects we try again. */
void loop() 
{
        if (!client.connected()) {
                connect_mqtt();
        }
        client.loop();
        
        // Here's an example of publishing from the ESP8266.
        // Uncomment until the end of the function to send a 'msg' back to Sync
        // every 2 minutes!
        /*
        static uint32_t now = millis();
        if (millis() > now + (2*(1000*60))) {
                Serial.println("Sending 2 minute ON message to Twilio!");
                client.publish(
                        sync_document, 
                        "{\"msg\":\"Ahoy!\",\"led\":\"ON\"}\0"
                );
                now = millis();
        }
        */
}
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
// Download the helper library from https://www.twilio.com/docs/node/install
// Your Account Sid and Auth Token from twilio.com/console
const accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
const authToken = 'your_auth_token';
const client = require('twilio')(accountSid, authToken);

client.sync.services('default').documents('BoardLED')
           .update({data: {
                led: "ON"
            }})
           .then(document => console.log(document.uniqueName))
           .done();
// Install the C# / .NET helper library from twilio.com/docs/csharp/install

using System;
using Twilio;
using Twilio.Rest.Sync.V1.Service;


class Program 
{
    static void Main(string[] args)
    {
        // Find your Account Sid and Token at twilio.com/console
        const string accountSid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
        const string authToken = "your_auth_token";

        TwilioClient.Init(accountSid, authToken);

        var document = DocumentResource.Update(
            data: "{\"led\": \"ON\"}",
            pathServiceSid: "default",
            pathSid: "BoardLED"
        );

        Console.WriteLine(document.UniqueName);
    }
}
<?php

// Update the path below to your autoload.php,
// see https://getcomposer.org/doc/01-basic-usage.md
require_once '/path/to/vendor/autoload.php';

use Twilio\Rest\Client;

// Your Account Sid and Auth Token from twilio.com/console
$sid    = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
$token  = "your_auth_token";
$twilio = new Client($sid, $token);

$document = $twilio->sync->v1->services("default")
                             ->documents("BoardLED")
                             ->update(array(
                                          'data' => array(
                                              "led" => "ON"
                                          )
                                      )
                             );

print($document->uniqueName);
# Download the helper library from https://www.twilio.com/docs/ruby/install
require 'rubygems'
require 'twilio-ruby'

# Your Account Sid and Auth Token from twilio.com/console
account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
auth_token = 'your_auth_token'
@client = Twilio::REST::Client.new(account_sid, auth_token)

document = @client.sync.services('default').documents('BoardLED')
                                           .update(data: {
                                                "led" => "ON"
                                            })

puts document.unique_name
# Download the helper library from https://www.twilio.com/docs/python/install
from twilio.rest import Client


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

document = client.sync.services('default').documents('BoardLED') \
                                          .update(data={
                                               'led': 'ON'
                                           })

print(document.unique_name)
// Install the Java helper library from twilio.com/docs/java/install

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

import java.util.HashMap;

public class Example {
    // Find your Account Sid and Token at 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);
        Document document = Document.updater("default", "BoardLED")
            .setData(new HashMap<String, Object>()
            {{ put(&quot;led&quot;, &quot;ON&quot;); }})
            .update();

        System.out.println(document.getUniqueName());
    }
}
DATA=$(cat << EOF
{
    "led": "ON"
}
EOF
)

curl -X POST https://sync.twilio.com/v1/Services/default/Documents/BoardLED \
--data-urlencode "Data=$DATA" \
-u ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX:your_auth_token
{
  "account_sid": "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "created_by": "created_by",
  "data": "{\"led\": \"ON\"}",
  "date_expires": "2015-07-30T21:00:00Z",
  "date_created": "2015-07-30T20:00:00Z",
  "date_updated": "2015-07-30T20:00:00Z",
  "revision": "revision",
  "service_sid": "default",
  "sid": "BoardLED",
  "unique_name": "unique_name",
  "url": "https://sync.twilio.com/v1/Services/default/Documents/BoardLED",
  "links": {
    "permissions": "https://sync.twilio.com/v1/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Documents/ETXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Permissions"
  }
}
#include "ESP8266WiFi.h"
#include "WiFiClientSecure.h"
#include <PubSubClient.h>
#include <ArduinoJson.h>

/* WiFi SSID and Password */
const char* ssid                        = "YOUR_SSID";
const char* password                    = "WIFI_PASSWORD";

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

/* 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;

void callback(char *, byte*, unsigned int);
WiFiClientSecure espClient;
PubSubClient client(mqtt_server, mqtt_port, callback, espClient);

/* 
 * Only use the fingerprint if you have a certificate rotation strategy in place.
 * It can be enabled by setting the use_fingerprint boolean to 'true'
 *  
 * SHA1 Fingerprint valid as of August 2017, but if it expires:
 * On *NIX systems with openssl installed, you can check the fingerprint with
 * 
 * echo | openssl s_client -connect mqtt-sync.us1.twilio.com:8883 | openssl x509 -fingerprint
 * 
 * ... and look for the 'SHA1 Fingerprint' line.
 */
const char* fingerprint         = \
        "4E:D6:B4:16:83:9F:86:86:0E:8B:BA:47:F6:FC:3F:65:29:B6:E1:13";
const bool use_fingerprint      = false;


/* 
 * 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(char* topic, byte* payload, unsigned int length) 
{
        std::unique_ptr<char []> msg(new char[length+1]());
        memcpy (msg.get(), payload, length);

        Serial.print("Message arrived on topic "); Serial.println(msg.get());
        
        StaticJsonBuffer<maxMQTTpackageSize> jsonBuffer;
        JsonObject& root = jsonBuffer.parseObject(msg.get());
        String led_command           = root["led"];

        if (led_command == "ON") {
                digitalWrite(BUILTIN_LED, LOW);
                Serial.println("LED turned on!");
        } else {
                digitalWrite(BUILTIN_LED, HIGH);
                Serial.println("LED turned off!");
        }
}

/* 
 * This function connects to Sync via MQTT. We connect using the key, password, and 
 * device name defined as constants above, and immediately check the server's 
 * certificate fingerprint (if desired).
 * 
 * If everything works, we subscribe to the document topic and return.
 */
void connect_mqtt() 
{
        while (!client.connected()) {
                Serial.println("Attempting to connect to Twilio Sync...");
                if (client.connect(sync_device_name, sync_key, sync_password)) {
                        /* Verify you are talking to Twilio */
                        if (!use_fingerprint || espClient.verify(fingerprint, mqtt_server)) {
                                Serial.print("Connected!  Subscribing to "); Serial.println(sync_document);
                                client.subscribe(sync_document);
                        } else {
                                Serial.println("Certificate mismatch!  Check fingerprint.");
                                client.disconnect();
                                while(1);
                        }
                } else {
                        Serial.print("failed, rc=");
                        Serial.print(client.state());
                        delay(10000);
                }
        }
}

/* In setup, we configure our LED for output, turn it off, and connect to WiFi */
void setup() 
{
        pinMode(BUILTIN_LED, OUTPUT);
        digitalWrite(BUILTIN_LED, HIGH); // Active LOW LED
        
        Serial.begin(115200);
        WiFi.begin(ssid, password);

        while (WiFi.status() != WL_CONNECTED) {
                delay(1000);
                Serial.print(".");
        }

        randomSeed(micros());

        Serial.print("\nWiFi connected!  IP address: ");
        Serial.println(WiFi.localIP());
}

/* Our loop constantly checks we are still connected.  On disconnects we try again. */
void loop() 
{
        if (!client.connected()) {
                connect_mqtt();
        }
        client.loop();
        
        // Here's an example of publishing from the ESP8266.
        // Uncomment until the end of the function to send a 'msg' back to Sync
        // every 2 minutes!
        /*
        static uint32_t now = millis();
        if (millis() > now + (2*(1000*60))) {
                Serial.println("Sending 2 minute ON message to Twilio!");
                client.publish(
                        sync_document, 
                        "{\"msg\":\"Ahoy!\",\"led\":\"ON\"}\0"
                );
                now = millis();
        }
        */
}