ParticleJS is JavaScript library for the Particle Device Cloud API for Node.js and the browser. It's open source so you can edit, change or even send in pull requests if you want to share!
This page contains examples to get started using the library.
For more details, see the detailed reference below and check the examples folder on GitHub.
First, make sure you have node.js installed!
Next, open a command prompt or terminal, and install by typing:
$ npm install particle-api-js
Particle API JS can be included using bower:
$ bower install particle-api-js
Alternately, you can pull in Particle API JS from the JSDelivr and simply include the script in your HTML.
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/particle-api-js@7/dist/particle.min.js">
</script>
Now you will have a Particle
object available that you can use in your application.
All functions in this library return promises.
particle.login({username: 'email@example.com', password: 'pass'}).then(
function(data){
console.log('API call completed on promise resolve: ', data.body.access_token);
},
function(err) {
console.log('API call completed on promise fail: ', err);
}
);
Here are some common use cases of using the functions in the Javascript library.
You can create an account here. Use the token from login
as the auth
parameter in other calls.
var Particle = require('particle-api-js');
var particle = new Particle();
var token;
particle.login({username: 'user@email.com', password: 'pass'}).then(
function(data) {
token = data.body.access_token;
},
function (err) {
console.log('Could not log in.', err);
}
);
List devices for a user with listDevices
.
var token; // from result of particle.login
var devicesPr = particle.listDevices({ auth: token });
devicesPr.then(
function(devices){
console.log('Devices: ', devices);
},
function(err) {
console.log('List devices call failed: ', err);
}
);
Call a function in device with callFunction
.
var fnPr = particle.callFunction({ deviceId: 'DEVICE_ID', name: 'brew', argument: 'D0:HIGH', auth: token });
fnPr.then(
function(data) {
console.log('Function called succesfully:', data);
}, function(err) {
console.log('An error occurred:', err);
});
The function needs to be defined in the firmware uploaded to the device and registered to the Particle cloud.
You pass along the name of the function and the params.
If the function call succeeds, data.return_value
is the value returned by the function call on the Particle device.
Claims device and adds it to the user account with claimDevice
particle.claimDevice({ deviceId: 'DEVICE_ID', auth: token }).then(function(data) {
console.log('device claim data:', data);
}, function(err) {
console.log('device claim err:', err);
});
Flash firmware to device with flashDevice
particle.flashDevice({ deviceId: 'DEVICE_ID', files: { file1: './path/file1' }, auth: token }).then(function(data) {
console.log('Device flashing started successfully:', data);
}, function(err) {
console.log('An error occurred while flashing the device:', err);
});
Gets all attributes for the device with getDevice
var devicesPr = particle.getDevice({ deviceId: 'DEVICE_ID', auth: token });
devicesPr.then(
function(data){
console.log('Device attrs retrieved successfully:', data);
},
function(err) {
console.log('API call failed: ', err);
}
);
Gets a variable value for the device with getVariable
particle.getVariable({ deviceId: 'DEVICE_ID', name: 'temp', auth: token }).then(function(data) {
console.log('Device variable retrieved successfully:', data);
}, function(err) {
console.log('An error occurred while getting attrs:', err);
});
The variable needs to be defined in your device's code.
If getting the variable succeeds, data.body.result
is the value of the variable on the Particle device.
Removes device from the user account with removeDevice
particle.removeDevice({ deviceId: 'DEVICE_ID', auth: token }).then(function(data) {
console.log('remove call response:', data);
}, function(err) {
console.log('An error occurred while removing:', err);
});
Renames device for the user account with renameDevice
particle.renameDevice({ deviceId: 'DEVICE_ID', name: 'new-name', auth: token }).then(function(data) {
console.log('Device renamed successfully:', data);
}, function(err) {
console.log('An error occurred while renaming device:', err);
});
Send a signal to the device to shout rainbows with signalDevice
particle.signalDevice({ deviceId: 'DEVICE_ID', signal: true, auth: token }).then(function(data) {
console.log('Device is shouting rainbows:', data);
}, function(err) {
console.log('Error sending a signal to the device:', err);
});
Send a signal to the device to stop shouting rainbows
particle.signalDevice({ deviceId: 'DEVICE_ID', signal: false, auth: token }).then(function(data) {
console.log('The LED is back to normal:', data);
}, function(err) {
console.log('Error sending a signal to the device:', err);
});
Send public key for a device to the cloud with sendPublicKey
particle.sendPublicKey({ deviceId: 'DEVICE_ID', key: 'key', auth: token }).then(function(data) {
console.log('Public key sent successfully:', data);
}, function(err) {
console.log('Error sending public key to the device:', err);
});
Get event listener to an stream in the Particle cloud with getEventStream
//Get all events
particle.getEventStream({ auth: token}).then(function(stream) {
stream.on('event', function(data) {
console.log("Event: ", data);
});
});
//Get your devices events
particle.getEventStream({ deviceId: 'mine', auth: token }).then(function(stream) {
stream.on('event', function(data) {
console.log("Event: ", data);
});
});
//Get test event for specific device
particle.getEventStream({ deviceId: 'DEVICE_ID', name: 'test', auth: token }).then(function(stream) {
stream.on('event', function(data) {
console.log("Event: ", data);
});
});
data
is an object with the following properties
{
"name":"Uptime",
"data":"5:28:54",
"ttl":"60",
"published_at":"2014-MM-DDTHH:mm:ss.000Z",
"coreid":"012345678901234567890123"
}
Register an event stream in the Particle cloud with publishEvent
var publishEventPr = particle.publishEvent({ name: 'test', data: {}, auth: token });
publishEventPr.then(
function(data) {
if (data.body.ok) { console.log("Event published succesfully") }
},
function(err) {
console.log("Failed to publish event: " + err)
}
);
Compiles files in the Particle cloud with compileCode
var ccPr = particle.compileCode({ files: { 'main.cpp': './project/main.cpp', 'my_lib/lib.cpp': './project/my_lib/lib.cpp' }, auth: token });
ccPr.then(
function(data) {
console.log('Code compilation started successfully:', data);
}, function(err) {
console.log('An error occurred while compiling the code:', err);
});
Flash firmware to a device with flashDevice
Creates a user in the Particle cloud with createUser
particle.createUser({ username: 'example@email.com', password: 'pass' }).then(function(data) {
We try to login and get back an accessToken to verify user creation
var loginPromise = particle.login('example@email.com', 'pass');
We'll use promises to check the result of the login process
loginPromise.then(
function(data) {
console.log('Login successful! access_token:', data.access_token);
},
function(err) {
console.log('Login failed:', err);
}
);
}
});
Lists access tokens from the Particle cloud for the specified user with listAccessTokens
particle.listAccessTokens({ username: 'u@m.com', password: 'pass' }).then(function(data) {
console.log('data on listing access tokens: ', data);
}, function(err) {
console.log('error on listing access tokens: ', err);
});
Removes an access token from the Particle cloud for the specified user with deleteAccessToken
particle.deleteAccessToken({ username: 'u@m.com', password: 'pass', token: 'token' }).then(function(data) {
console.log('data on deleting accessToken: ', data);
}, function(err) {
console.log('error on deleting accessToken: ', err);
});
If you are a product creator you can use the Javascript library to manage devices, firmware, integrations, and more.
Many of the functions in the Javascript library accept a product
parameter. Pass your product ID number (such as 4567) or the slug (such as myproduct-v100
) to make that function act on that product.
Here a full reference of every function available in the Javascript client library.
Contructor for the Cloud API wrapper.
Create a new Particle object and call methods below on it.
Parameters
options
Object Options for this API call Options to be used for all requests (see Defaults) (optional, default {}
)Login to Particle Cloud using an existing Particle acccount.
Parameters
options
Object Options for this API call
Returns Promise
If login failed with an 'mfa_required' error, this must be called with a valid OTP code to login
Parameters
options
Object Options for this API call
Returns Promise
Enable MFA on the currently logged in user
Parameters
options
Object Options for this API call
Returns Promise
Confirm MFA for the user. This must be called with current TOTP code, determined from the results of enableMfa(). You will be prompted to enter an OTP code every time you login after enrollment is confirmed.
Parameters
options
Object Options for this API call
Returns Promise
Disable MFA for the user.
Parameters
options
Object Options for this API call
Returns Promise
Create Customer for Product.
Parameters
options
Object Options for this API call
Returns Promise
Login to Particle Cloud using an OAuth client.
Parameters
Returns Promise
Create a user account for the Particle Cloud
Parameters
options
Object Options for this API call
Returns Promise
Verify new user account via verification email
Parameters
options
Object Options for this API calloptions.token
String the string token sent in the verification emailoptions.context
Returns Promise
Send reset password email for a Particle Cloud user account
Parameters
Returns Promise
Revoke an access token
Parameters
options
Object Options for this API call
Returns Promise
Revoke the current session access token
Parameters
Returns Promise
List all valid access tokens for a Particle Cloud account
Parameters
options
Object Options for this API call
Returns Promise
Retrieves the information that is used to identify the current login for tracking.
Parameters
options
Object Options for this API call (optional, default {}
)
Returns Promise<Object> Resolve the tracking identify of the current login
List devices claimed to the account or product
Parameters
options
Object Options for this API calloptions.deviceId
String? (Product only) Filter results to devices with this ID (partial matching)options.deviceName
String? (Product only) Filter results to devices with this name (partial matching)options.sortAttr
String? (Product only) The attribute by which to sort results. See API docs for options.options.sortDir
String? (Product only) The direction of sorting. See API docs for options.options.page
Number? (Product only) Current page of resultsoptions.perPage
Number? (Product only) Records per pageoptions.product
String? List devices in this product ID or slugoptions.auth
String Access Tokenoptions.context
Returns Promise
Get detailed informationa about a device
Parameters
options
Object Options for this API call
Returns Promise
Claim a device to the account. The device must be online and unclaimed.
Parameters
options
Object Options for this API call
Returns Promise
Add a device to a product or move device out of quarantine.
Parameters
options
Object Options for this API call
Returns Promise
Unclaim / Remove a device from your account or product, or deny quarantine
Parameters
options
Object Options for this API call
Returns Promise
Unclaim a product device its the owner, but keep it in the product
Parameters
options
Object Options for this API call
Returns Promise
Rename a device
Parameters
options
Object Options for this API call
Returns Promise
Instruct the device to turn on/off the LED in a rainbow pattern
Parameters
options
Object Options for this API call
Returns Promise
Store some notes about device
Parameters
options
Object Options for this API call
Returns Promise
Mark device as being used in development of a product so it opts out of automatic firmware updates
Parameters
options
Object Options for this API call
Returns Promise
Mark device as being used in development of a product so it opts out of automatic firmware updates
Parameters
options
Object Options for this API call
Returns Promise
Mark device as receiving automatic firmware updates
Parameters
options
Object Options for this API call
Returns Promise
Update multiple device attributes at the same time
Parameters
options
Object Options for this API calloptions.deviceId
String Device ID or Nameoptions.name
String? Desired Nameoptions.signal
Boolean Signal device on or offoptions.development
Boolean? (Product only) Set to true to mark as development, false to return to product fleetoptions.product
String? Device in this product ID or slugoptions.auth
String Access Tokenoptions.notes
options.desiredFirmwareVersion
options.flash
options.context
Returns Promise
Provision a new device for products that allow self-provisioning
Parameters
options
Object Options for this API call
Returns Promise
Generate a claim code to use in the device claiming process. To generate a claim code for a product, the access token MUST belong to a customer of the product.
Parameters
options
Object Options for this API call
Returns Promise
Get the value of a device variable
Parameters
options
Object Options for this API call
Returns Promise
Compile and flash application firmware to a device. Pass a pre-compiled binary to flash it directly to the device.
Parameters
options
Object Options for this API calloptions.deviceId
String Device ID or Nameoptions.product
String Flash device in this product ID or slugoptions.files
Object Object containing files to be compiled and flashed. Keys should be the filenames, including relative path, and the values should be a path or Buffer of the file contents in Node, or a File or Blob in the browser.options.targetVersion
String System firmware version to compile against (optional, default latest
)options.auth
String Stringoptions.context
Returns Promise
DEPRECATED: Flash the Tinker application to a device. Instead compile and flash the Tinker source code.
Parameters
options
Object Options for this API call
Returns Promise
Compile firmware using the Particle Cloud
Parameters
options
Object Options for this API calloptions.files
Object Object containing files to be compiled. Keys should be the filenames, including relative path, and the values should be a path or Buffer of the file contents in Node, or a File or Blob in the browser.options.platformId
Number? Platform id number of the device you are compiling for. Common values are 0=Core, 6=Photon, 10=Electron.options.targetVersion
String System firmware version to compile against (optional, default latest
)options.auth
String Access Tokenoptions.context
Returns Promise
Download a firmware binary
Parameters
options
Object Options for this API call
Returns Request
Send a new device public key to the Particle Cloud
Parameters
options
Object Options for this API call
Returns Promise
Call a device function
Parameters
options
Object Options for this API call
Returns Promise
Get a stream of events
Parameters
options
Object Options for this API call
Returns Promise If the promise resolves, the resolution value will be an EventStream object that will emit 'event' events, as well as the specific named event.
Publish a event to the Particle Cloud
Parameters
options
Object Options for this API call
Returns Promise
Create a webhook
Parameters
options
Object Options for this API calloptions.deviceId
String Trigger webhook only for this device ID or Nameoptions.name
String Webhook nameoptions.url
String URL the webhook should hitoptions.requestType
String HTTP method to use (optional, default POST
)options.headers
Object? Additional headers to add to the webhookoptions.json
Object? JSON dataoptions.query
Object? Query string dataoptions.body
String? Custom webhook request bodyoptions.responseTemplate
Object? Webhook response templateoptions.responseTopic
Object? Webhook response topicoptions.rejectUnauthorized
Boolean? Reject invalid HTTPS certificatesoptions.webhookAuth
Object? HTTP Basic Auth informationoptions.form
Object? Form dataoptions.product
String? Webhook for this product ID or slugoptions.auth
String Access Tokenoptions.noDefaults
options.context
Returns Promise
Delete a webhook
Parameters
options
Object Options for this API call
Returns Promise
List all webhooks owned by the account or product
Parameters
options
Object Options for this API call
Returns Promise
Create an integration to send events to an external service
See the API docs for details https://docs.particle.io/reference/api/#integrations-webhooks-
Parameters
options
Object Options for this API calloptions.integrationType
String The kind of external integration. One of Webhook, AzureIotHub, GoogleCloudPubSub, GoogleMapsoptions.event
String Event that triggers the integrationoptions.deviceId
String? Trigger integration only for this device ID or Nameoptions.product
String? Integration for this product ID or slugoptions.auth
String Access Tokenoptions.settings
options.context
Returns Promise
Edit an integration to send events to an external service
See the API docs for details https://docs.particle.io/reference/api/#integrations-webhooks-
Parameters
options
Object Options for this API calloptions.integrationId
String The integration to editoptions.event
String? Change the event that triggers the integrationoptions.deviceId
String? Trigger integration only for this device ID or Nameoptions.product
String? Integration for this product ID or slugoptions.auth
String Access Tokenoptions.settings
options.context
Returns Promise
Delete an integration to send events to an external service
Parameters
options
Object Options for this API call
Returns Promise
List all integrations owned by the account or product
Parameters
options
Object Options for this API call
Returns Promise
Get details about the current user
Parameters
Returns Promise
Set details on the current user
Parameters
options
Object Options for this API call
Returns Promise
Change username (i.e, email)
Parameters
options
Object Options for this API call
Returns Promise
Change user's password
Parameters
options
Object Options for this API call
Returns Promise
List SIM cards owned by a user or product
Parameters
options
Object Options for this API calloptions.iccid
String? (Product only) Filter to SIM cards matching this ICCIDoptions.deviceId
String? (Product only) Filter to SIM cards matching this device IDoptions.deviceName
String? (Product only) Filter to SIM cards matching this device nameoptions.page
Number? (Product only) Current page of resultsoptions.perPage
Number? (Product only) Records per pageoptions.product
String? SIM cards for this product ID or slugoptions.auth
String Access Tokenoptions.context
Returns Promise
Get data usage for one SIM card for the current billing period
Parameters
options
Object Options for this API call
Returns Promise
Get data usage for all SIM cards in a product the current billing period
Parameters
options
Object Options for this API call
Returns Promise
Activate and add SIM cards to an account or product
Parameters
options
Object Options for this API calloptions.iccid
String ICCID of the SIM cardoptions.iccids
Array<String> (Product only) ICCID of multiple SIM cards to importoptions.country
String The ISO country code for the SIM cardsoptions.product
String? SIM cards for this product ID or slugoptions.auth
String Access Tokenoptions.promoCode
options.context
Returns Promise
Deactivate a SIM card so it doesn't incur data usage in future months.
Parameters
options
Object Options for this API call
Returns Promise
Reactivate a SIM card the was deactivated or unpause a SIM card that was automatically paused
Parameters
options
Object Options for this API call
Returns Promise
Update SIM card data limit
Parameters
options
Object Options for this API call
Returns Promise
Remove a SIM card from an account so it can be activated by a different account
Parameters
options
Object Options for this API call
Returns Promise
List valid build targets to be used for compiling
Parameters
options
Object Options for this API call
Returns Promise
List firmware libraries
Parameters
options
Object Options for this API calloptions.page
Number Page index (default, first page)options.limit
Number Number of items per pageoptions.filter
String Search term for the librariesoptions.sort
String Ordering key for the library listoptions.architectures
Array<String> List of architectures to filteroptions.category
String Category to filteroptions.scope
String The library scope to list. Default is 'all'. Other values are- 'all' - list public libraries and my private librariesoptions.excludeScopes
String list of scopes to excludeoptions.auth
String Access Tokenoptions.context
Returns Promise
Get firmware library details
Parameters
options
Object Options for this API call
Returns Promise
Firmware library details for each version
Parameters
options
Object Options for this API call
Returns Promise
Contribute a new library version from a compressed archive
Parameters
options
Object Options for this API call
Returns Promise
Publish the latest version of a library to the public
Parameters
options
Object Options for this API call
Returns Promise
Delete one version of a library or an entire private library
Parameters
options
Object Options for this API call
Returns Promise
Download an external file that may not be on the API
Parameters
Returns Promise Resolves to a buffer with the file data
List OAuth client created by the account
Parameters
options
Object Options for this API call
Returns Promise
Create an OAuth client
Parameters
options
Object Options for this API calloptions.name
String Name of the OAuth clientoptions.type
String web, installed or weboptions.redirect_uri
String? URL to redirect after OAuth flow. Only for type web.options.scope
Object? Limits what the access tokens created by this client can do.options.product
String? Create client for this product ID or slugoptions.auth
String Access Tokenoptions.context
Returns Promise
Update an OAuth client
Parameters
options
Object Options for this API call
Returns Promise
Delete an OAuth client
Parameters
options
Object Options for this API call
Returns Promise
List products the account has access to
Parameters
Returns Promise
Get detailed information about a product
Parameters
options
Object Options for this API call
Returns Promise
List product firmware versions
Parameters
options
Object Options for this API call
Returns Promise
List product firmware versions
Parameters
options
Object Options for this API calloptions.file
Object Path or Buffer of the new firmware file Either a path or Buffer of the file contents in Node, or a File or Blob in the browser.
options.version
Number Version number of new firmwareoptions.title
String Short identifier for the new firmwareoptions.description
String? Longer description for the new firmwareoptions.product
String Firmware for this product ID or slugoptions.auth
String Access Tokenoptions.context
Returns Promise
Get information about a product firmware version
Parameters
options
Object Options for this API call
Returns Promise
Update information for a product firmware version
Parameters
options
Object Options for this API call
Returns Promise
Download a product firmware binary
Parameters
options
Object Options for this API call
Returns Request
Release a product firmware version as the default version
Parameters
options
Object Options for this API call
Returns Promise
List product team members
Parameters
options
Object Options for this API call
Returns Promise
Invite Particle user to a product team
Parameters
options
Object Options for this API call
Returns Promise
Remove Particle user to a product team
Parameters
options
Object Options for this API call
Returns Promise
Fetch details about a serial number
Parameters
options
Object Options for this API call
Returns Promise
Create a mesh network
Parameters
options
Object Options for this API call
Remove a mesh network.
Parameters
options
Object Options for this API call
List all mesh networks
Parameters
options
Object Options for this API call
Get information about a mesh network.
Parameters
options
Object Options for this API call
Modify a mesh network.
Parameters
options
Object Options for this API call
Add a device to a mesh network.
Parameters
options
Object Options for this API call
Remove a device from a mesh network.
Parameters
options
Object Options for this API call
List all devices of a mesh network.
Parameters
options
Object Options for this API call