Using Twilio Sync with MQTT on a Particle Electron

In this guide, we'll show you how to use the lightweight messaging protocol MQTT with Twilio Sync for IoT and Particle's cellular IoT platform, the Electron. We'll cover the Twilio Device Manager and Device Fleets, then cover connecting to Sync with your Electron to blink an LED through API calls.

Cut the cord, we're going to wirelessly blink an LED!

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 Up For) a Twilio Account

Sign up for a free Twilio trial here if you need a Twilio account, or sign into your existing Twilio account.

Once logged in, visit the console for Twilio Device Manager.

Deploy a Fleet of Particle Electrons

In Sync, a Device Fleet is a collection of devices, keys, certificates, and configurations. While you can create multiple fleets, every fleet will be isolated from every other fleet.

One Default Fleet is automatically created for you; navigate to it in the Device Management console.

Locating the default Ffleet in the Twilio Console

You can also deploy a 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
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 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);

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

        Console.WriteLine(fleet.Sid);
    }
}
<?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);

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

echo $fleet->sid;
# 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)

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

puts fleet.sid
# Get the Python 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 Java 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.

Once you are familiar with Fleets, it's time to move to Deployments.

Configure the Default Fleet Deployment

As soon as the Default Fleet is built, Twilio will also configure a default Deployment. The 'Default Deployment' field in your Default Fleet is populated, echoing the following screenshot:

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

Click through to the new deployment through the 'Configure the Deployment' link.

Every deployment is configured with a default Service Instance.

Twilio also has also automatically linked your deployment with a default Sync Service Instance.

Instances are like databases. All of the data from the 'conversation' you'll have with the Electron (or any other device in this Deployment) will only be stored in this one Sync instance.

You can also (of course) configure a new Deployment through 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 Python 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'
deployment_sid = 'DLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
deployment = client.preview\
                   .deployed_devices\
                   .fleets(fleet_sid)\
                   .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

Deployments down, you're now ready to create your first Device and a Key to authenticate your Electron!

Create a Particle Electron Device and a Device Key

A Device is any single piece of hardware registered in Twilio's Device Manager.

A piece of hardware connects and authenticates, then Twilio determines which Device it should match based on the credential it provides - certificate or key. We'll be using Device Keys today with the Particle Electron, but where possible you should use Device Certificates.

Inside your Fleet on the sidebar, click the 'Devices' link, then 'Create a Device'. Enter a Friendly and Unique name, then hit the red 'Create' button:

Create a New ESP8266 Device in Deployed Devices

 You can also provision new Devices using the API, as illustrated here.

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 C# 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 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($sid, $token);

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

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

echo $device->sid;
# 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)

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 Python 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 Java 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

In your Device configuration, click the 'Keys' link in the left sidebar then the red plus sign (+) to start creating a new Device Key:

Create New Device Key Button

The appropriate field should auto-populate a device key (or find it by navigating back into the Deployment to your Device).  Enter a Unique Name then 'Create' the Key. Important: both the Key and the Secret must be saved once your key is created. The secret can't be recovered after this!

Create a Device Key in Sync Deployed Devices

You can also create and delete Device Keys using the API. Here's a programatic 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 C# 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 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);

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

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

echo $key->sid;
# 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)

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 Python 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 Java 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

Inside the C++ Electron code, 'KEY' will go inside sync_key, while 'SECRET' will map to sync_password.

Create a Sync Document

The Document is the most basic Sync object - perfect for sharing state in a small LED-blinking application. The MQTT topic the Electron subscribes to is based on the document name - we highly suggest you call your first document BoardLED to match our code.

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 also set the key 'led' to 'OFF'. Logic on the Electron will then keep that LED unlit when it connects.

Prerequisites to Use a Particle Electron with Sync

For this guide's development, we used a Particle Electron with the Particle Web IDE.

Ready to run? Here is a link to the code (if you are logged into the Particle IDE, cloning comes by default!). Optionally, you can also grab it on Github.

Here's all you need to do to sync with Sync:

  • Edit sync_key and sync_password
  • (Optionally) change the topic (ONLY if you renamed the Document)
  • Flash your Electron!
Loading Code Samples...
Language
#include <ArduinoJson.h>
#include <MQTT-TLS.h>
#include "certificate.h"

/*  License: MIT
 *  Sync Settings
 *  
 *  Enter a Sync Key & Password, your document unique name, 
 *  and a device name.
 */
const char* sync_key                    = "KYxxxxxxxxxxxx";
const char* sync_password               = "SECRET_PASSWORD_HERE";
const char* sync_document               = "sync/docs/BoardLED";
const char* sync_device_name            = "Particle_Electron";

/* LED Setting - on the Electron, the LED is Pin 7 */
const uint8_t LED_PIN                    = 7;

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

void callback(char* topic, byte* payload, unsigned int length);
MQTT client(
    mqtt_server, 
    mqtt_port, 
    callback
);

/* 
 * 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());
        const char* led_command_raw = root["led"];
        String led_command(led_command_raw);

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

/* 
 * This function connects to Sync via MQTT. We connect using the device keys
 * from above, and immediately check the server's certificate fingerprint.
 * 
 * If everything works, we subscribe to the document topic and return.
 */
void connect_mqtt()
{
    // Ensure we are talking to Twilio
    client.enableTls(root_ca, sizeof(root_ca));
    
    // Connect to Sync
    Serial.println("Connecting to Sync...");
    Serial.println(client.connect(
        "Particle_Electron",
        sync_key,
        sync_password
    ));
    
    if (client.isConnected()) {
        client.subscribe(sync_document);
        Serial.print("Subscribed to "); Serial.println(sync_document);
    }
}

/* In setup, we configure our LED, enabled serial, and connect to Sync */
void setup() 
{
    pinMode(LED_PIN, OUTPUT);
    digitalWrite(LED_PIN, LOW);
    Serial.begin(115200);
    connect_mqtt();
}

/* 
 * Our loop constantly checks we are still connected and runs the 
 * heartbeat/yield function.  
 */
void loop() 
{
    if (client.isConnected()) {
        client.loop();
    } else {
        delay(1000);
        connect_mqtt();
    }
    delay(1000);
    // Here's an example of publishing from the Particle Electron.
    // 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 World!\",\"led\":\"ON\"}"
        );
        now = millis();
    }
}
Change your key and password in the code to connect your Electron to Sync for IoT.
Edit Credentials on the Electron to Connect

Change your key and password in the code to connect your Electron to Sync for IoT.

Let's take a closer look at how this works.

Library Inclusiuon

We installed two libraries in the Particlde Web IDE:

  • ArduinoJSON (by Benoit Blanchon - GitHub)
  • MQTT-TLS (by Hirotaka - GitHub)

You can manually install libraries by clicking the 'Libraries' button on the left sidebar:

Install Libraries in the Particle IDE

A dialog will appear that will guide you to choose the application.

How to Update Sync from the Electron

You can also choose to send updates back to Sync with our code. We're just sending back a "Hello, World!" message - surely you'll eventually be editing this to send back sensor readings and event values.

Loading Code Samples...
Language
#include <ArduinoJson.h>
#include <MQTT-TLS.h>
#include "certificate.h"

/*  License: MIT
 *  Sync Settings
 *  
 *  Enter a Sync Key & Password, your document unique name, 
 *  and a device name.
 */
const char* sync_key                    = "KYxxxxxxxxxxxx";
const char* sync_password               = "SECRET_PASSWORD_HERE";
const char* sync_document               = "sync/docs/BoardLED";
const char* sync_device_name            = "Particle_Electron";

/* LED Setting - on the Electron, the LED is Pin 7 */
const uint8_t LED_PIN                    = 7;

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

void callback(char* topic, byte* payload, unsigned int length);
MQTT client(
    mqtt_server, 
    mqtt_port, 
    callback
);

/* 
 * 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());
        const char* led_command_raw = root["led"];
        String led_command(led_command_raw);

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

/* 
 * This function connects to Sync via MQTT. We connect using the device keys
 * from above, and immediately check the server's certificate fingerprint.
 * 
 * If everything works, we subscribe to the document topic and return.
 */
void connect_mqtt()
{
    // Ensure we are talking to Twilio
    client.enableTls(root_ca, sizeof(root_ca));
    
    // Connect to Sync
    Serial.println("Connecting to Sync...");
    Serial.println(client.connect(
        "Particle_Electron",
        sync_key,
        sync_password
    ));
    
    if (client.isConnected()) {
        client.subscribe(sync_document);
        Serial.print("Subscribed to "); Serial.println(sync_document);
    }
}

/* In setup, we configure our LED, enabled serial, and connect to Sync */
void setup() 
{
    pinMode(LED_PIN, OUTPUT);
    digitalWrite(LED_PIN, LOW);
    Serial.begin(115200);
    connect_mqtt();
}

/* 
 * Our loop constantly checks we are still connected and runs the 
 * heartbeat/yield function.  
 */
void loop() 
{
    if (client.isConnected()) {
        client.loop();
    } else {
        delay(1000);
        connect_mqtt();
    }
    delay(1000);
    // Here's an example of publishing from the Particle Electron.
    // 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 World!\",\"led\":\"ON\"}"
        );
        now = millis();
    }
}
Leave the lines uncommented to send data back through Sync on a timer.
Optionally Send Data Back to Sync

Leave the lines uncommented to send data back through Sync on a timer.

Every (2*(1000*60)) milliseconds (2 seconds) the Electron will send a message back to Sync, updating the 'led' back to 'ON' (insert your joke here about Electrons flowing!).

We've added some properly formatted JSON in that example, but note you can also use ArduinoJSON to format a JSON string for you. As your updates become more complex, we suggest using the library.

Flash the Electron and Send Electrons Through the LED

Flash the code to the Electron and optionally open a serial monitor. For *NIX we like screen, on Windows we like PuTTY.

Assuming you entered everything correctly, you should see some happy messages scroll by, ending with a notice about subscribing to Sync (and then the current state of the document). We've also added some minor debugging serial output which can assist in the non-happy case.

But if it's working? Make that LED blink!

Modify the Document using the UPDATE api call, 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
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

Quickly, you'll see two updates:

  • A response to curl, informing you your update went through
  • Light from the LED

Particle Electron Deployed Devices

Wow - look at those electrons flow from the Electron!

A Fully Synced Internet of Things!

While you won't be stopping with a blinking LED, you've now got an internet controlled light source all backed up by Sync for IoT and Twilio's powerful and scalable infrastructure. Whatever you've got in store, we're ready to scale and expand - up or out - with your business.

We're very interested in where you're planning on taking things - please contact us on Twitter and let us know! We can't wait to see what you build. Especially if it blinks.

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 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);

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

        Console.WriteLine(fleet.Sid);
    }
}
<?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);

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

echo $fleet->sid;
# 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)

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

puts fleet.sid
# Get the Python 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 Java 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 Python 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'
deployment_sid = 'DLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
deployment = client.preview\
                   .deployed_devices\
                   .fleets(fleet_sid)\
                   .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 C# 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 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($sid, $token);

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

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

echo $device->sid;
# 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)

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 Python 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 Java 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 C# 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 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);

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

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

echo $key->sid;
# 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)

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 Python 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 Java 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 <ArduinoJson.h>
#include <MQTT-TLS.h>
#include "certificate.h"

/*  License: MIT
 *  Sync Settings
 *  
 *  Enter a Sync Key & Password, your document unique name, 
 *  and a device name.
 */
const char* sync_key                    = "KYxxxxxxxxxxxx";
const char* sync_password               = "SECRET_PASSWORD_HERE";
const char* sync_document               = "sync/docs/BoardLED";
const char* sync_device_name            = "Particle_Electron";

/* LED Setting - on the Electron, the LED is Pin 7 */
const uint8_t LED_PIN                    = 7;

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

void callback(char* topic, byte* payload, unsigned int length);
MQTT client(
    mqtt_server, 
    mqtt_port, 
    callback
);

/* 
 * 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());
        const char* led_command_raw = root["led"];
        String led_command(led_command_raw);

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

/* 
 * This function connects to Sync via MQTT. We connect using the device keys
 * from above, and immediately check the server's certificate fingerprint.
 * 
 * If everything works, we subscribe to the document topic and return.
 */
void connect_mqtt()
{
    // Ensure we are talking to Twilio
    client.enableTls(root_ca, sizeof(root_ca));
    
    // Connect to Sync
    Serial.println("Connecting to Sync...");
    Serial.println(client.connect(
        "Particle_Electron",
        sync_key,
        sync_password
    ));
    
    if (client.isConnected()) {
        client.subscribe(sync_document);
        Serial.print("Subscribed to "); Serial.println(sync_document);
    }
}

/* In setup, we configure our LED, enabled serial, and connect to Sync */
void setup() 
{
    pinMode(LED_PIN, OUTPUT);
    digitalWrite(LED_PIN, LOW);
    Serial.begin(115200);
    connect_mqtt();
}

/* 
 * Our loop constantly checks we are still connected and runs the 
 * heartbeat/yield function.  
 */
void loop() 
{
    if (client.isConnected()) {
        client.loop();
    } else {
        delay(1000);
        connect_mqtt();
    }
    delay(1000);
    // Here's an example of publishing from the Particle Electron.
    // 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 World!\",\"led\":\"ON\"}"
        );
        now = millis();
    }
}
#include <ArduinoJson.h>
#include <MQTT-TLS.h>
#include "certificate.h"

/*  License: MIT
 *  Sync Settings
 *  
 *  Enter a Sync Key & Password, your document unique name, 
 *  and a device name.
 */
const char* sync_key                    = "KYxxxxxxxxxxxx";
const char* sync_password               = "SECRET_PASSWORD_HERE";
const char* sync_document               = "sync/docs/BoardLED";
const char* sync_device_name            = "Particle_Electron";

/* LED Setting - on the Electron, the LED is Pin 7 */
const uint8_t LED_PIN                    = 7;

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

void callback(char* topic, byte* payload, unsigned int length);
MQTT client(
    mqtt_server, 
    mqtt_port, 
    callback
);

/* 
 * 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());
        const char* led_command_raw = root["led"];
        String led_command(led_command_raw);

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

/* 
 * This function connects to Sync via MQTT. We connect using the device keys
 * from above, and immediately check the server's certificate fingerprint.
 * 
 * If everything works, we subscribe to the document topic and return.
 */
void connect_mqtt()
{
    // Ensure we are talking to Twilio
    client.enableTls(root_ca, sizeof(root_ca));
    
    // Connect to Sync
    Serial.println("Connecting to Sync...");
    Serial.println(client.connect(
        "Particle_Electron",
        sync_key,
        sync_password
    ));
    
    if (client.isConnected()) {
        client.subscribe(sync_document);
        Serial.print("Subscribed to "); Serial.println(sync_document);
    }
}

/* In setup, we configure our LED, enabled serial, and connect to Sync */
void setup() 
{
    pinMode(LED_PIN, OUTPUT);
    digitalWrite(LED_PIN, LOW);
    Serial.begin(115200);
    connect_mqtt();
}

/* 
 * Our loop constantly checks we are still connected and runs the 
 * heartbeat/yield function.  
 */
void loop() 
{
    if (client.isConnected()) {
        client.loop();
    } else {
        delay(1000);
        connect_mqtt();
    }
    delay(1000);
    // Here's an example of publishing from the Particle Electron.
    // 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 World!\",\"led\":\"ON\"}"
        );
        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
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"
  }
}