Particle Cloud

The defining feature of an IoT device is its ability to send and receive information through the Internet. This allows an IoT device to interact with other apps or with other IoT devices.

The Particle firmware (the operating system) on your Photon device has built-in functions to allow your device to send and receive data through the Particle Cloud service. This will allow your device to interact with web apps that you create.

Particle also has a JavaScript library that provides functions that will allow web apps to send and receive data through Particle Cloud. You can use these functions in your web app's JavaScript code, so that your web app can interact with your Photon device.

The three main ways your Photon device can interact with your web app through Particle Cloud are by:

You can also combine these Particle Cloud interactions in more complex ways. For example, your Photon app could send an event notification to your web app, which then triggers the web app to read the value of a variable in the Photon app.

This reference contains code examples for both your Photon app and your web app. Many of the code examples will need to be modified, in order to be used in your apps. For example, you may have to change the names of variables, add custom code, etc.

Particle JavaScript Library

Particle API JS is a JavaScript library that contains functions that will allow a web app to interact with your Photon device by sending and receiving data through Particle Cloud.

A web app must load the Particle API JS file using a <script> tag in the <head> section of its HTML file.

If possible, you should load the Particle API JS file from a web service like jsDelivr:

Include in Web App HTML file, such as: index.html

<script src="//cdn.jsdelivr.net/particle-api-js/6.4.2/particle.min.js" type="text/javascript"></script>

Alternatively, you can download a copy of the Particle API JS file, and place the file into the same folder as your HTML file. In this case, your <script> tag would load the file directly from the folder:

<script src="particle.min.js" type="text/javascript"></script>

After loading the Particle API JS file (using one of the methods shown above), your web app also needs to load a JavaScript file containing your own code to interact with your Photon device. This will be loaded using another <script> tag. The example below would load a JavaScript file (created by you) called: code.js

Include in Web App HTML file, such as: index.html

<script src="code.js" type="text/javascript"></script>

Photon Device ID and Access Token

If a web app wants to interact with your Photon device through Particle Cloud, the web app has to know your Photon device ID and your Photo access token. These act like a username and password to help protect your Photon data.

  • Your Photon device ID is listed in the "Devices" section of your Particle Build account. Click the arrow to the right of your Photon device name to reveal the device ID. This device ID acts like a username to access your device's data in the Particle Cloud service.

  • Your Photon access token is listed in the "Settings" section of your Particle Build account. This access token acts as a password to access your device's data in the Particle Cloud service.

Your web app will need to include the device ID and access token in its own JavaScript file in order to interact with your Photon device. Usually these are stored in global variables to make it easier to use them repeatedly throughout your web app's JavaScript code.

Include in Web App JS file, such as: code.js

var myDevice = "000000000000000000000000"; // insert your actual Photon device ID
var myToken = "abcdefghijklmnopqrstuvwxyz"; // insert your actual Photon access token

Be sure to modify the code above to insert your actual Photon device ID and access token.

Create Particle Object

In order to use the Particle Cloud functions in the Particle API JS library, your web app's JavaScript file must declare a Particle object variable. This should be a global variable and is usually just called particle.

Include in Web App JS file, such as: code.js

var particle = new Particle();

Your JavaScript code will use this particle object variable to run the Particle Cloud functions.

Share Photon Variable through Particle Cloud

You can share the current values of variables in your Photon app through Particle Cloud, so a web app can read these variables.

For example, your Photon device could measure the air temperature using a sensor, store the measurement in a temperature variable, and then share this variable with a web app.

Particle Cloud will let your Photon device share up to 20 variables at one time. Each cloud variable has to be given a unique name (up to 12 characters in length).

NOTE: The only data types that are allowed to be shared as cloud variables are: int (whole numbers), double (decimal numbers), or String (text, up to 622 characters).

PHOTON APP

A variable is shared through Particle Cloud by including a Particle.variable statement in the setup() function of your Photon app.

This Particle.variable statement has to provide a name for your cloud variable (up to 12 characters) and identify the name of the variable in your Photon app. Usually, these two will have the same name (but they don't have to).

Include within setup() function of Photon App

Particle.variable("roomTemp", roomTemp);

In the example above, the first name (in quotation marks) will become the name of your cloud variable. The second name identifies the variable in your Photon app that will be shared through the cloud. Modify this code to match your variable's name.

WEB APP

Your web app can read the current value of a cloud variable by using a particle.getVariable statement in its JavaScript file.

This particle.getVariable statement needs to provide your Photon device ID, the name of your cloud variable, and your Photon access token.

The value of your cloud variable gets temporarily stored in a local JS variable called data.body.result that you can use in your JavaScript code.

For example, if you want to display the value in your web app, you could insert the value by using a JavaScript statement to find an HTML element with a specific id name and then changing its HTML content to include data.body.result. In the code example below, assume that your web app HTML file contains a paragraph tag identified as: <p id="room-temp"></p>

Include in Web App JS file, such as: code.js

particle.getVariable({ deviceId: myDevice, name: "roomTemp", auth: myToken }).then(function(data) {
    // insert code to do something with data.body.result
    document.getElementById("room-temp").innerHTML = "Temperature is " + data.body.result);
}, function(err) {
        console.log("An error occurred retrieving data:", err);
});

Web apps are frequently updating their HTML through JavaScript statements that identify HTML elements using an id name or class name.

jQuery is a JavaScript library that makes it easier to update your HTML (and your CSS). jQuery statements start with $ and are usually shorter than using regular JavaScript. You can combine jQuery statements and regular JavaScript statements in the same code.

Here's an alternate example of the previous code that uses a jQuery statement instead.

// alternate example using jQuery to update html
particle.getVariable({ deviceId: myDevice, name: "roomTemp", auth: myToken }).then(function(data) {
    $("#room-temp").html("Temperature is " + data.body.result);
}, function(err) {
        console.log("An error occurred retrieving data:", err);
});

If your web app needs to keep checking the current value of the variable, you can place the particle.getVariable statement inside another custom function and then have your JavaScript code repeatedly run that custom function on a time interval (such as every 0.5 seconds, etc.).

// run checkTemp function every 0.5 seconds
window.setInterval(checkTemp, 500);

function checkTemp(){
    particle.getVariable({ deviceId: myDevice, name: "roomTemp", auth: myToken }).then(function(data) {
        $("#room-temp").html("Temperature is " + data.body.result);
    }, function(err) {
            console.log("An error occurred retrieving data:", err);
    });
}

If your web app needs to save the value of the Photon variable, you should create a global variable in your JavaScript that will be used to store the value. After getting the value of the Photon variable from the Particle Cloud, assign the data.body.result to the JS global variable.

// global variable
var roomTemp;

function checkTemp(){
    particle.getVariable({ deviceId: myDevice, name: "roomTemp", auth: myToken }).then(function(data) {
        roomTemp = data.body.result;
        // add other code to do something or call another JS function
    }, function(err) {
            console.log("An error occurred retrieving data:", err);
    });
}

// can add other function(s) to do something with roomTemp variable

Your web app can get the values of several Photon variables from Particle Cloud. You just need to include a particle.getVariable statement for each variable. However, you can put these statements inside the same custom function in your JavaScript. This next example runs a checkLocation() function every 5 seconds to get the latitude and longitude values from Particle Cloud.

// global variables
var latitude, longitude;

// run checkLocation function every 5 seconds
window.setInterval(checkLocation, 5000);

function checkLocation(){
    particle.getVariable({ deviceId: myDevice, name: "latitude", auth: myToken }).then(function(data) {
        latitude = data.body.result;
    }, function(err) {
        console.log("An error occurred retrieving data:", err);
    });

    particle.getVariable({ deviceId: myDevice, name: "longitude", auth: myToken }).then(function(data) {
        longitude = data.body.result;
    }, function(err) {
        console.log("An error occurred retrieving data:", err);
    });
}

Share Photon Function through Particle Cloud

You can share a custom function in your Photon app through Particle Cloud, so a web app can call this function to make it run on your Photon device. The web app also sends data (as a text String up to 63 characters) when calling the function. This is how your web app can send commands and/or data to your Photon app.

For example, your Photon app could share a custom function to turn an LED light on or off. A web app would be able to call this function to make it run on the Photon device.

Particle Cloud will let your Photon device share up to 15 functions at one time. Each cloud function has to be given a unique name (up to 12 characters in length). You get to decide what to name your cloud function – but use a name that will make sense to someone reading your code. (Your web app will have to refer to this same cloud function name, in order to call the function.)

PHOTON APP

A custom function is shared through Particle Cloud by including a Particle.function statement in the setup() function of your Photon app.

This Particle.function statement has to provide a name for your cloud function (up to 12 characters) and identify the name of the custom function in your Photon app. Usually, these two will have the same name (but they don't have to).

Include within setup() function

Particle.function("ledToggle", ledToggle);

In the example above, the first name (in quotation marks) will become the name of your cloud function. The second name identifies the custom function in your Photon app that will be shared through the cloud. Modify this code to match your function's name.

In order to share a custom function through Particle Cloud, the function must return an integer value and must accept a String value as an argument.

However, you do not necessarily have to do any with the function's return value. You also do not necessarily have to do anything inside the function with the String value. They just need to be present in the function for it to be shared with Particle Cloud.

Example of custom function in Photon App

int ledToggle(String data){
    if (ledStatus == "off") {
        digitalWrite(led, HIGH);
        ledStatus = "on";
    } else {
        digitalWrite(led, LOW);
        ledStatus = "off";
    }
    return 1;
}

When you want to use this custom function in your Photon app, you must pass a String value (text) to the function. Notice in the example below that we pass the text "switch" when we call the ledToggle() function, even though the ledToggle() function above doesn't actually use this String data.

void loop(){
    // check button
    int buttonState = digitalRead(button);

    // LOW means button is being pushed
    if(buttonState == LOW) {
        ledToggle("switch");
    }
    // wait 0.2 seconds before checking button again
    delay(200);
}

However, you can design your custom function to use the String data that is passed into it. The code examples below show a modified version of the ledToggle() function for a device that has separate push buttons to turn the LED on and off. The String data passed into ledToggle() function determines whether it will turn the light on, turn the light off, or do nothing.

void loop(){
    int redButtonState = digitalRead(redButton);
    // LOW means button is being pushed
    if(redButtonState == LOW) {
        ledToggle("off");
    }
    int greenButtonState = digitalRead(greenButton);
    // LOW means button is being pushed
    if(greenButtonState == LOW) {
        ledToggle("on");
    }
    // wait 0.2 seconds before checking buttons again
    delay(200);
}

int ledToggle(String data){
    if (data == "on") {
        digitalWrite(led, HIGH);
        return 1;
    } else if (data == "off") {
        digitalWrite(led, LOW);
        return 0;
    } else {
        return -1;
    }
}

If your Photon app needs to save the data sent by the web app when it calls the function, you should create a global variable in your Photon app that will be used to store the data. Then within the custom function called by the web app, assign the String data to the Photon global variable.

String userName;

int getName(String data){
    userName = data;
    // can add other code to do something with userName
    return 1;
}

The Photon app receives data from the web app in the form of a String (text). However, if the data is actually a number (which was converted to a String by the web app), then you can convert the String data back into a number using either the .toInt() or .toFloat() method, depending on whether the number is supposed to be a whole number (integer) or a decimal number (float).

int userID; // variable that can store whole numbers

int getUserID(String data){
    userID = data.toInt();
    // can add other code to do something with userID, such as:
    // if(userID == fingerprintID) digitalWrite(greenLED, HIGH);
    return 1;
}

float accountBalance; // variable that can store decimal numbers

int getBalance(String data){
    accountBalance = data.toFloat();
    // can add other code to do something with accountBalance, such as:
    // if(accountBalance <= 0.99) digitalWrite(redLED, HIGH);
    return 1;
}

WEB APP

Your web app can call a cloud function to make it run on your Photon device by using a particle.callFunction statement in its JavaScript file.

This particle.callFunction statement needs to provide your Photon device ID, the name of your cloud function, an argument (text String) to pass to the function, and your Photon access token.

Include in Web App JS file, such as: code.js

particle.callFunction({ deviceId: myDevice, name: "ledToggle", argument: "switch", auth: myToken });

The argument is the data that your web app sends to the Photon app. This argument data must be in the form of a text String. You can either list the String directly as text inside quotes, or you can use a String variable to store the text.

Often this particle.callFunction statement will be included inside another JavaScript function. For example, your web app might have an onscreen button that can be clicked to toggle the LED light on or off.

For example, this code adds an onscreen button to your web app HTML that will run a JavaScript function called switchLight() when the button is clicked:

<button onclick="switchLight()">Toggle Light</button>

This next code shows that the switchLight() function in your JavaScript simply contains the particle.callFunction statement.

function switchLight(){
    particle.callFunction({ deviceId: myDevice, name: "ledToggle", argument: "switch", auth: myToken });
}

You can also use a String variable to store the argument data sent to your Photon app. For example, imagine our web app HTML had two different onscreen buttons: one to turn the light on, and a second to turn the light off.

<button onclick="turnLightOff()">OFF</button>
<button onclick="turnLightOn()">ON</button>

In the JavaScript, you would declare a global variable to store the String data that will be sent to the Photon app as the argument data. The example below creates a variable called myData and sends either "off" or "on" to the Photon app depending on which onscreen button is clicked.

var myData;

function turnLightOff() {
    myData = "off";
    switchLight();
}

function turnLightOn() {
    myData = "on";
    switchLight();
}

function switchLight(){
    particle.callFunction({ deviceId: myDevice, name: "ledToggle", argument: myData, auth: myToken });
}

If the JavaScript data that you want to send is not already a String (text), then you need to convert the data into a String to send it. Numbers can be converted into a String using the .toString() method. In this example, a variable containing a number is converted into a text string, in order to send it to the web app.

var myNumber; // variable storing numerical data

function sendData(){
    var myData = myNumber.toString();
    particle.callFunction({ deviceId: myDevice, name: "getWebData", argument: myData, auth: myToken });
}

Share Photon Event through Particle Cloud

You can share an event condition that occurs in your Photon app through Particle Cloud, so a web app can be notified when the event occurs. You also have the option for the event notification to include data.

For example, if your Photon device detects movement using a motion sensor, it could send an event notification to a web app. The notification could also include data, such as which motion sensor was triggered.

Particle Cloud will let your Photon device send about one event notification per second. Sending more frequent event notifications can result in Particle Cloud temporarily slowing down your event notifications (which can make your web app become non-responsive).

TIP: To avoid a slowdown by Particle Cloud, you should add an intentional 1 second delay to your Photon code immediately after sending an event notification. (A one second delay in your Photon app is better than your web app becoming non-responsive.)

Each event notification is automatically cleared from Particle Cloud after 60 seconds (to prevent your web app from receiving outdated notifications).

PHOTON APP

An event notification is shared through Particle Cloud by including a Particle.publish statement in your Photon app after the event condition occurs.

This Particle.publish statement has to provide a name for your cloud event (up to 63 characters). You get to decide what to name your event – but use a name that will make sense to someone reading your code. (Your web app will have to use this same event name, in order to receive the notification.) The event can also send additional data as a String (text up to 255 characters), but this is optional.

Include within loop() or custom function

// send event notification without additional data - "motion-detected" is name of event
Particle.publish("motion-detected");

// add 1 second delay before sending another event notification
delay(1000);

When publishing an event notification, you can also send additional data as a text String (up to 255 characters), but this is optional. The String data can either be sent directly as text inside quotes (as the example below shows) or through a String variable (as the next example shows).

// send event notification plus String data - "Front Hallway" is the data
Particle.publish("motion-detected", "Front Hallway");

// need 1 second delay before sending another event notification
delay(1000);

This next example shows how a variable can be used to store the String data that will be sent through the event notification. In this example, the status of two magnetic switch sensors determines which text string is sent to the web app.

String doorStatus; // text representing status of doors (open, closed, etc.)

// check magnetic switches on doors
int door1 = digitalRead(magnetPin1); // front door
int door2 = digitalRead(magnetPin2); // back door

// HIGH means switch is open, LOW means switch is closed 
if(door1 == HIGH && door2 == LOW) {
    doorStatus = "Front Door Open";
} else if(door1 == HIGH && door2 == HIGH) {
    doorStatus = "Back Door Open";
} else if(door1 == HIGH && door2 == HIGH) {
    doorStatus = "Both Doors Open";
} else {
    doorStatus = "Both Doors Closed";
}

// send event notification, along with String data stored in variable
Particle.publish("door-status", doorStatus);

// need 1 second delay before sending another event notification
delay(1000);

If the Photon data that you want to send is not already a String (text), then you need to convert the data into a String to send it. This can be done simply by listing the variable inside a String() statement. In this example, a fingerprint ID number is converted to a text string, in order to send it to the web app.

int fingerprintID; // number representing fingerprint ID

// if finger presses on fingerprint scanner
if(fps.IsPressFinger()) {
    // capture fingerprint (false = faster low-res image)
    fps.CaptureFinger(false);
    // identify by comparing against all stored fingerprints
    fingerprintID = fps.Identify1_N();
}

// send event notification, along with variable converted to String data
Particle.publish("fingerprint-scanned", String(fingerprintID));

// need 1 second delay before sending another event notification
delay(1000);

WEB APP

Your web app can listen for a cloud event by using a particle.getEventStream statement in its JavaScript file.

This particle.getEventStream statement needs to provide your Photon device ID, the name of your cloud event, and your Photon access token. Be sure that your Photon app and web app are using the same name for the cloud event; otherwise, the web app will not receive the event notifications.

If an event notification includes optional String data, this gets temporarily stored in a local variable called feed.data that you can use in your JavaScript.

Include in Web App JS file, such as: code.js

particle.getEventStream({ deviceId: myDevice, name: "door-status", auth: myToken }).then(function(stream) {
  stream.on('event', function(feed) {
    // insert code to do something with feed.data
    $("#alert").html("Door Status: " + feed.data);
  });
});

This particle.getEventStream statement can be placed directly after your JavaScript statements that declare the variables for your device ID, access token, and Particle object. (Do not place inside another function.)

The event stream will automatically keep listening for new event notifications. Every time an event notification occurs, it will automatically run the code inserted inside your particle.getEventStream statement.

If your web app needs to save the data from Photon event notification, you should create a global variable in your JavaScript that will be used to store the data. After getting the event notification from the Particle Cloud, assign the feed.data to the JavaScript global variable.

var idCard; // variable to save feed data from event notification

particle.getEventStream({ deviceId: myDevice, name: "idCard-scanned", auth: myToken }).then(function(stream) {
  stream.on('event', function(feed) {
    idCard = feed.data;
    // add other code to do something or call JS custom function
  });
});

// can add other function(s) to do something with idCard

Combine Particle Cloud Interactions

You can also combine these Particle Cloud interactions in more complex ways, depending on what is needed for your IoT system.

For example, your Photon app could send an event notification to your web app, which then triggers the web app to read the value of one or more variables in the Photon app.

Imagine a Photon device that is designed to act like a location tracker. Maybe the Photon device is installed in a vehicle, so you can track where the vehicle is parked.

In this example code, the Photon device uses a GPS receiver to determine the latitude and longitude of its location. The latitude and longitude are stored in variables, which are shared with a web app through Particle Cloud. The Photon device also has a push button. When the button is pushed, the Photon app notifies the web app to track the location of the Photon device. When the notification is received, the web app gets the updated values of the latitude and longitude variables from Particle Cloud. Then the web app displays the location on Google Maps using the latitude and longitude.

PHOTON APP

// variables for GPS location data
double latitude, longitude;

// add other variables for GPS receiver and push button

void setup() {
    // share variables through Particle Cloud
    Particle.variable("latitude", latitude);
    Particle.variable("longitude", longitude);

    // add other setup code for GPS receiver and push button
}

void loop() {

    // add code to read GPS location

    // if button is pushed, send event notification
    if (buttonState == LOW) {
        Particle.publish("track-location");
        delay(1000);
    }
}

WEB APP

Include in Web App JS file, such as: code.js

// JavaScript variables for GPS location data
var latitude, longitude;

particle.getEventStream({ deviceId: myDevice, name: "track-location", auth: myToken }).then(function(stream) {
  stream.on('event', function(feed) {
    getLocation(); // read variables from Particle Cloud
    displayMap(); // do something with variables
  });
});

function getLocation() {
    particle.getVariable({ deviceId: myDevice, name: "latitude", auth: myToken }).then(function(data) {
        latitude = data.body.result;
    }, function(err) {
            console.log("An error occurred retrieving data:", err);
    });

    particle.getVariable({ deviceId: myDevice, name: "longitude", auth: myToken }).then(function(data) {
        longitude = data.body.result;
    }, function(err) {
            console.log("An error occurred retrieving data:", err);
    });
}

function displayMap() {
    // add code to display GPS location on Google Maps using latitude and longitude
}

Last updated