A new AWS IoT Device SDK is now available. It is a complete rework, built to improve reliability, performance, and security. We invite your feedback!
This SDK will no longer receive feature updates, but will receive security updates.
The aws-iot-device-sdk.js package allows developers to write JavaScript applications which access the AWS IoT Platform via MQTT or MQTT over the Secure WebSocket Protocol. It can be used in Node.js environments as well as in browser applications.
This document provides instructions on how to install and configure the AWS IoT device SDK for JavaScript, and includes examples demonstrating use of the SDK APIs.
This package is built on top of mqtt.js and provides three classes: 'device', 'thingShadow' and 'jobs'. The 'device' class wraps mqtt.js to provide a secure connection to the AWS IoT platform and expose the mqtt.js interfaces upward. It provides features to simplify handling of intermittent connections, including progressive backoff retries, automatic re-subscription upon connection, and queued offline publishing with configurable drain rate.
Beginning with Release v2.2.0 of the SDK, AWS collects usage metrics indicating which language and version of the SDK is being used. This allows us to prioritize our resources towards addressing issues faster in SDKs that see the most and is an important data point. However, we do understand that not all customers would want to report this data by default. In that case, the sending of usage metrics can be easily disabled by set options.enableMetrics to false.
The 'thingShadow' class implements additional functionality for accessing Thing Shadows via the AWS IoT API; the thingShadow class allows devices to update, be notified of changes to, get the current state of, or delete Thing Shadows from AWS IoT. Thing Shadows allow applications and devices to synchronize their state on the AWS IoT platform. For example, a remote device can update its Thing Shadow in AWS IoT, allowing a user to view the device's last reported state via a mobile app. The user can also update the device's Thing Shadow in AWS IoT and the remote device will synchronize with the new state. The 'thingShadow' class supports multiple Thing Shadows per mqtt connection and allows pass-through of non-Thing-Shadow topics and mqtt events.
The 'jobs' class implements functionality to interact with the AWS IoT Jobs service. The IoT Job service manages deployment of IoT fleet wide tasks such as device software/firmware deployments and updates, rotation of security certificates, device reboots, and custom device specific management tasks.
Included in this package is an example 'agent'. The agent can be used either as a stand-alone program to manage installation and maintenance of files and other running processes or it can be incorporated into a customized agent to meet specific application needs.
NOTE: AWS IoT Node.js SDK will only support Node version 8.17 or above.
You can check your node version by
node -v
Installing with npm:
npm install aws-iot-device-sdk
Installing from github:
git clone https://github.com/aws/aws-iot-device-sdk-js.git
cd aws-iot-device-sdk-js
npm install
Please note that on Mac, once a private key is used with a certificate, that certificate-key pair is imported into the Mac Keychain. All subsequent uses of that certificate will use the stored private key and ignore anything passed in programmatically.
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT-0
var awsIot = require('aws-iot-device-sdk');
//
// Replace the values of '<YourUniqueClientIdentifier>' and '<YourCustomEndpoint>'
// with a unique client identifier and custom host endpoint provided in AWS IoT.
// NOTE: client identifiers must be unique within your AWS account; if a client attempts
// to connect with a client identifier which is already in use, the existing
// connection will be terminated.
//
var device = awsIot.device({
keyPath: <YourPrivateKeyPath>,
certPath: <YourCertificatePath>,
caPath: <YourRootCACertificatePath>,
clientId: <YourUniqueClientIdentifier>,
host: <YourCustomEndpoint>
});
//
// Device is an instance returned by mqtt.Client(), see mqtt.js for full
// documentation.
//
device
.on('connect', function() {
console.log('connect');
device.subscribe('topic_1');
device.publish('topic_2', JSON.stringify({ test_data: 1}));
});
device
.on('message', function(topic, payload) {
console.log('message', topic, payload.toString());
});
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT-0
var awsIot = require('aws-iot-device-sdk');
//
// Replace the values of '<YourUniqueClientIdentifier>' and '<YourCustomEndpoint>'
// with a unique client identifier and custom host endpoint provided in AWS IoT cloud
// NOTE: client identifiers must be unique within your AWS account; if a client attempts
// to connect with a client identifier which is already in use, the existing
// connection will be terminated.
//
var thingShadows = awsIot.thingShadow({
keyPath: <YourPrivateKeyPath>,
certPath: <YourCertificatePath>,
caPath: <YourRootCACertificatePath>,
clientId: <YourUniqueClientIdentifier>,
host: <YourCustomEndpoint>
});
//
// Client token value returned from thingShadows.update() operation
//
var clientTokenUpdate;
//
// Simulated device values
//
var rval = 187;
var gval = 114;
var bval = 222;
thingShadows.on('connect', function() {
//
// After connecting to the AWS IoT platform, register interest in the
// Thing Shadow named 'RGBLedLamp'.
//
thingShadows.register( 'RGBLedLamp', {}, function() {
// Once registration is complete, update the Thing Shadow named
// 'RGBLedLamp' with the latest device state and save the clientToken
// so that we can correlate it with status or timeout events.
//
// Thing shadow state
//
var rgbLedLampState = {"state":{"desired":{"red":rval,"green":gval,"blue":bval}}};
clientTokenUpdate = thingShadows.update('RGBLedLamp', rgbLedLampState );
//
// The update method returns a clientToken; if non-null, this value will
// be sent in a 'status' event when the operation completes, allowing you
// to know whether or not the update was successful. If the update method
// returns null, it's because another operation is currently in progress and
// you'll need to wait until it completes (or times out) before updating the
// shadow.
//
if (clientTokenUpdate === null)
{
console.log('update shadow failed, operation still in progress');
}
});
});
thingShadows.on('status',
function(thingName, stat, clientToken, stateObject) {
console.log('received '+stat+' on '+thingName+': '+
JSON.stringify(stateObject));
//
// These events report the status of update(), get(), and delete()
// calls. The clientToken value associated with the event will have
// the same value which was returned in an earlier call to get(),
// update(), or delete(). Use status events to keep track of the
// status of shadow operations.
//
});
thingShadows.on('delta',
function(thingName, stateObject) {
console.log('received delta on '+thingName+': '+
JSON.stringify(stateObject));
});
thingShadows.on('timeout',
function(thingName, clientToken) {
console.log('received timeout on '+thingName+
' with token: '+ clientToken);
//
// In the event that a shadow operation times out, you'll receive
// one of these events. The clientToken value associated with the
// event will have the same value which was returned in an earlier
// call to get(), update(), or delete().
//
});
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT-0
var awsIot = require('aws-iot-device-sdk');
//
// Replace the values of '<YourUniqueClientIdentifier>' and '<YourCustomEndpoint>'
// with a unique client identifier and custom host endpoint provided in AWS IoT cloud
// NOTE: client identifiers must be unique within your AWS account; if a client attempts
// to connect with a client identifier which is already in use, the existing
// connection will be terminated.
//
var jobs = awsIot.jobs({
keyPath: <YourPrivateKeyPath>,
certPath: <YourCertificatePath>,
caPath: <YourRootCACertificatePath>,
clientId: <YourUniqueClientIdentifier>,
host: <YourCustomEndpoint>
});
//
// Jobs is built on top of awsIot.device and inherits all of the same functionality.
//
jobs
.on('connect', function() {
console.log('connect');
device.subscribe('topic_1');
device.publish('topic_2', JSON.stringify({ test_data: 1}));
});
jobs
.on('message', function(topic, payload) {
console.log('message', topic, payload.toString());
});
//
// To subscribe to job execution events call the subscribeToJobs method which takes
// a callback that will be invoked when a job execution is available or an error
// occurs. The job object passed to the callback contains information about the job
// execution and methods for updating the job execution status. Details covered
// in the API documentation below.
//
jobs.subscribeToJobs(thingName, function(err, job) {
if (isUndefined(err)) {
console.log('default job handler invoked, jobId: ' + job.id.toString());
console.log('job document: ' + job.document);
}
else {
console.error(err);
}
});
jobs.subscribeToJobs(thingName, 'customJob', function(err, job) {
if (isUndefined(err)) {
console.log('customJob operation handler invoked, jobId: ' + job.id.toString());
console.log('job document: ' + job.document);
}
else {
console.error(err);
}
});
//
// After calling subscribeToJobs for each operation on a particular thing call
// startJobNotifications to cause any existing queued job executions for the given
// thing to be published to the appropriate subscribeToJobs handler. Only needs
// to be called once per thing.
//
jobs.startJobNotifications(thingName, function(err) {
if (isUndefined(err)) {
console.log('job notifications initiated for thing: ' + thingName);
}
else {
console.error(err);
}
});
awsIot.device()awsIot.thingShadow()awsIot.jobs()awsIot.thingShadow#register()awsIot.thingShadow#unregister()awsIot.thingShadow#update()awsIot.thingShadow#get()awsIot.thingShadow#delete()awsIot.thingShadow#publish()awsIot.thingShadow#subscribe()awsIot.thingShadow#unsubscribe()awsIot.thingShadow#end()awsIot.jobs#subscribeToJobs()awsIot.jobs#unsubscribeFromJobs()awsIot.jobs#startJobNotifications()jobjob#documentjob#idjob#operationjob#statusjob#inProgress()job#failed()job#succeeded()Returns a wrapper for the mqtt.Client()
class, configured for a TLS connection with the AWS IoT platform and with
arguments as specified in options. The AWSIoT-specific arguments are as
follows:
host: the AWS IoT endpoint you will use to connectclientId: the client ID you will use to connect to AWS IoTcertPath: path of the client certificate filekeyPath: path of the private key file associated with the client certificatecaPath: path of your CA certificate fileclientCert: same as certPath, but can also accept a buffer containing client certificate dataprivateKey: same as keyPath, but can also accept a buffer containing private key datacaCert: same as caPath, but can also accept a buffer containing CA certificate dataautoResubscribe: set to 'true' to $ claude mcp add aws-iot-device-sdk-js \
-- python -m otcore.mcp_server <graph>