Gathering detailed insights and metrics for aws-iot-device-sdk
Gathering detailed insights and metrics for aws-iot-device-sdk
Gathering detailed insights and metrics for aws-iot-device-sdk
Gathering detailed insights and metrics for aws-iot-device-sdk
@types/aws-iot-device-sdk
TypeScript definitions for aws-iot-device-sdk
aws-iot-device-sdk-v2
NodeJS API for the AWS IoT service
@aws-sdk/client-iot
AWS SDK for JavaScript Iot Client for Node.js, Browser and React Native
@aws-sdk/client-iot-data-plane
AWS SDK for JavaScript Iot Data Plane Client for Node.js, Browser and React Native
SDK for connecting to AWS IoT from a device using JavaScript/Node.js
npm install aws-iot-device-sdk
v2.2.15
Published on 03 Jul 2024
Fix region validation, allow Gov Cloud and other aws regions
Published on 04 Jun 2024
Dependency Update and Bug Fixes
Published on 27 Oct 2023
Dependency Update
Published on 31 Mar 2022
Restore examples in npm
Published on 30 Jul 2021
Custom auth query support
Published on 09 Jul 2021
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
966 Stars
87 Commits
384 Forks
75 Watching
7 Branches
45 Contributors
Updated on 21 Nov 2024
JavaScript (88.76%)
Shell (10.45%)
Batchfile (0.79%)
Cumulative downloads
Total Downloads
Last day
11.2%
28,637
Compared to previous day
Last week
9%
154,360
Compared to previous week
Last month
6.2%
628,247
Compared to previous month
Last year
58.7%
6,784,295
Compared to previous year
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
1node -v
Installing with npm:
1npm install aws-iot-device-sdk
Installing from github:
1git clone https://github.com/aws/aws-iot-device-sdk-js.git 2cd aws-iot-device-sdk-js 3npm 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.
1// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2// SPDX-License-Identifier: MIT-0 3var awsIot = require('aws-iot-device-sdk'); 4 5// 6// Replace the values of '<YourUniqueClientIdentifier>' and '<YourCustomEndpoint>' 7// with a unique client identifier and custom host endpoint provided in AWS IoT. 8// NOTE: client identifiers must be unique within your AWS account; if a client attempts 9// to connect with a client identifier which is already in use, the existing 10// connection will be terminated. 11// 12var device = awsIot.device({ 13 keyPath: <YourPrivateKeyPath>, 14 certPath: <YourCertificatePath>, 15 caPath: <YourRootCACertificatePath>, 16 clientId: <YourUniqueClientIdentifier>, 17 host: <YourCustomEndpoint> 18}); 19 20// 21// Device is an instance returned by mqtt.Client(), see mqtt.js for full 22// documentation. 23// 24device 25 .on('connect', function() { 26 console.log('connect'); 27 device.subscribe('topic_1'); 28 device.publish('topic_2', JSON.stringify({ test_data: 1})); 29 }); 30 31device 32 .on('message', function(topic, payload) { 33 console.log('message', topic, payload.toString()); 34 });
1// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2// SPDX-License-Identifier: MIT-0 3var awsIot = require('aws-iot-device-sdk'); 4 5// 6// Replace the values of '<YourUniqueClientIdentifier>' and '<YourCustomEndpoint>' 7// with a unique client identifier and custom host endpoint provided in AWS IoT cloud 8// NOTE: client identifiers must be unique within your AWS account; if a client attempts 9// to connect with a client identifier which is already in use, the existing 10// connection will be terminated. 11// 12var thingShadows = awsIot.thingShadow({ 13 keyPath: <YourPrivateKeyPath>, 14 certPath: <YourCertificatePath>, 15 caPath: <YourRootCACertificatePath>, 16 clientId: <YourUniqueClientIdentifier>, 17 host: <YourCustomEndpoint> 18}); 19 20// 21// Client token value returned from thingShadows.update() operation 22// 23var clientTokenUpdate; 24 25// 26// Simulated device values 27// 28var rval = 187; 29var gval = 114; 30var bval = 222; 31 32thingShadows.on('connect', function() { 33// 34// After connecting to the AWS IoT platform, register interest in the 35// Thing Shadow named 'RGBLedLamp'. 36// 37 thingShadows.register( 'RGBLedLamp', {}, function() { 38 39// Once registration is complete, update the Thing Shadow named 40// 'RGBLedLamp' with the latest device state and save the clientToken 41// so that we can correlate it with status or timeout events. 42// 43// Thing shadow state 44// 45 var rgbLedLampState = {"state":{"desired":{"red":rval,"green":gval,"blue":bval}}}; 46 47 clientTokenUpdate = thingShadows.update('RGBLedLamp', rgbLedLampState ); 48// 49// The update method returns a clientToken; if non-null, this value will 50// be sent in a 'status' event when the operation completes, allowing you 51// to know whether or not the update was successful. If the update method 52// returns null, it's because another operation is currently in progress and 53// you'll need to wait until it completes (or times out) before updating the 54// shadow. 55// 56 if (clientTokenUpdate === null) 57 { 58 console.log('update shadow failed, operation still in progress'); 59 } 60 }); 61}); 62thingShadows.on('status', 63 function(thingName, stat, clientToken, stateObject) { 64 console.log('received '+stat+' on '+thingName+': '+ 65 JSON.stringify(stateObject)); 66// 67// These events report the status of update(), get(), and delete() 68// calls. The clientToken value associated with the event will have 69// the same value which was returned in an earlier call to get(), 70// update(), or delete(). Use status events to keep track of the 71// status of shadow operations. 72// 73 }); 74 75thingShadows.on('delta', 76 function(thingName, stateObject) { 77 console.log('received delta on '+thingName+': '+ 78 JSON.stringify(stateObject)); 79 }); 80 81thingShadows.on('timeout', 82 function(thingName, clientToken) { 83 console.log('received timeout on '+thingName+ 84 ' with token: '+ clientToken); 85// 86// In the event that a shadow operation times out, you'll receive 87// one of these events. The clientToken value associated with the 88// event will have the same value which was returned in an earlier 89// call to get(), update(), or delete(). 90// 91 }); 92
1// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2// SPDX-License-Identifier: MIT-0 3var awsIot = require('aws-iot-device-sdk'); 4 5// 6// Replace the values of '<YourUniqueClientIdentifier>' and '<YourCustomEndpoint>' 7// with a unique client identifier and custom host endpoint provided in AWS IoT cloud 8// NOTE: client identifiers must be unique within your AWS account; if a client attempts 9// to connect with a client identifier which is already in use, the existing 10// connection will be terminated. 11// 12var jobs = awsIot.jobs({ 13 keyPath: <YourPrivateKeyPath>, 14 certPath: <YourCertificatePath>, 15 caPath: <YourRootCACertificatePath>, 16 clientId: <YourUniqueClientIdentifier>, 17 host: <YourCustomEndpoint> 18}); 19 20// 21// Jobs is built on top of awsIot.device and inherits all of the same functionality. 22// 23jobs 24 .on('connect', function() { 25 console.log('connect'); 26 device.subscribe('topic_1'); 27 device.publish('topic_2', JSON.stringify({ test_data: 1})); 28 }); 29 30jobs 31 .on('message', function(topic, payload) { 32 console.log('message', topic, payload.toString()); 33 }); 34 35// 36// To subscribe to job execution events call the subscribeToJobs method which takes 37// a callback that will be invoked when a job execution is available or an error 38// occurs. The job object passed to the callback contains information about the job 39// execution and methods for updating the job execution status. Details covered 40// in the API documentation below. 41// 42jobs.subscribeToJobs(thingName, function(err, job) { 43 if (isUndefined(err)) { 44 console.log('default job handler invoked, jobId: ' + job.id.toString()); 45 console.log('job document: ' + job.document); 46 } 47 else { 48 console.error(err); 49 } 50}); 51 52jobs.subscribeToJobs(thingName, 'customJob', function(err, job) { 53 if (isUndefined(err)) { 54 console.log('customJob operation handler invoked, jobId: ' + job.id.toString()); 55 console.log('job document: ' + job.document); 56 } 57 else { 58 console.error(err); 59 } 60}); 61 62// 63// After calling subscribeToJobs for each operation on a particular thing call 64// startJobNotifications to cause any existing queued job executions for the given 65// thing to be published to the appropriate subscribeToJobs handler. Only needs 66// to be called once per thing. 67// 68jobs.startJobNotifications(thingName, function(err) { 69 if (isUndefined(err)) { 70 console.log('job notifications initiated for thing: ' + thingName); 71 } 72 else { 73 console.error(err); 74 } 75}); 76
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()
job
job#document
job#id
job#operation
job#status
job#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 automatically re-subscribe to topics after reconnection (default 'true')offlineQueueing
: set to 'true' to automatically queue published messages while offline (default 'true')offlineQueueMaxSize
: enforce a maximum size for the offline message queue (default 0, e.g. no maximum)offlineQueueDropBehavior
: set to 'oldest' or 'newest' to define drop behavior on a full queue when offlineQueueMaxSize > 0drainTimeMs
: the minimum time in milliseconds between publishes when draining after reconnection (default 250)baseReconnectTimeMs
: the base reconnection time in milliseconds (default 1000)maximumReconnectTimeMs
: the maximum reconnection time in milliseconds (default 128000)minimumConnectionTimeMs
: the minimum time in milliseconds that a connection must be maintained in order to be considered stable (default 20000)protocol
: the connection type, either 'mqtts' (default), 'wss' (WebSocket/TLS), or 'wss-custom-auth' (WebSocket/TLS with custom authentication). Note that when set to 'wss', values must be provided for the Access Key ID and Secret Key in either the following options or in environment variables as specified in WebSocket Configuration. When set to 'wss-custom-auth', valid headers must be provided as specified in Custom AuthwebsocketOptions
: if protocol
is set to 'wss', you can use this parameter to pass additional options to the underlying WebSocket object; these options are documented here.filename
: used to load credentials from the file different than the default location when protocol
is set to 'wss'. Default value is '~/.aws/credentials'profile
: used to specify which credential profile to be used when protocol
is set to 'wss'. Default value is 'default'accessKeyId
: used to specify the Access Key ID when protocol
is set to 'wss'. Overrides the environment variable AWS_ACCESS_KEY_ID
and AWS_ACCESS_KEY_ID
from filename
if set.secretKey
: used to specify the Secret Key when protocol
is set to 'wss'. Overrides the environment variable AWS_SECRET_ACCESS_KEY
and AWS_SECRET_ACCESS_KEY
from filename
if set.sessionToken
: (required when authenticating via Cognito, optional otherwise) used to specify the Session Token when protocol
is set to 'wss'. Overrides the environment variable AWS_SESSION_TOKEN
if set.region
: used to specify AWS account region (e.g. 'us-east-1') when protocol
is set to wss
. If undefined, a value is derived from host
.customAuthHeaders
: used to specify your custom authorization headers when protocol
is set to 'wss-custom-auth'. The fields 'X-Amz-CustomAuthorizer-Name', 'X-Amz-CustomAuthorizer-Signature', and the field for your token name are required.servername
: used for SNI. If undefined, a value is derived from host
.port
: used to specify which port to connect to. If undefined, 443 or 8883 will be chosen depending on protocol
.customAuthQueryString
: used to specify the token credentials in a query string for custom authorization when protocol
is set to wss-custom-auth
. More info can be found here.keepalive
: used to specify the time interval for each ping request. Default is set to 300 seconds to connect to AWS IoT.enableMetrics
: used to report SDK version usage metrics. It is set to true by default. To disable metrics collection, set value to false.debug
: set to 'true' for verbose logging (default 'false').All certificates and keys must be in PEM format.
options
also contains arguments specific to mqtt. See [the mqtt client documentation]
(https://github.com/mqttjs/MQTT.js/blob/master/README.md#client) for details
of these arguments. Note, AWS IoT doesn't support retained messages; setting retain
flag to
'true' for message publishing, including Last Will and Testament messages, will result in
connection termination. For AWS IoT protocol specifics, please visit here.
Supports all events emitted by the mqtt.Client() class.
Update the credentials set used to authenticate via WebSocket/SigV4. This method is designed to be invoked during the callback of the getCredentialsForIdentity method in the AWS SDK for JavaScript.
accessKeyId
: the latest Access Key to use when connecting via WebSocket/SigV4secretKey
: the latest Secret Key to use when connecting via WebSocket/SigV4sessionToken
: the latest Session Token to use when connecting via WebSocket/SigV4expiration
: the time this credentials set will expireThe thingShadow
class wraps an instance of the device
class with additional
functionality to operate on Thing Shadows via the AWS IoT API. The
arguments in deviceOptions
include all those in the device class.
thingShadowOptions has the addition of the following arguments specific to the thingShadow
class:
operationTimeout
: the timeout for thing operations (default 10 seconds)Supports all events emitted by the mqtt.Client() class; however, the semantics for the
message
event are slightly different and additional events are available
as described below:
'message'
function(topic, message) {}
Emitted when a message is received on a topic not related to any Thing Shadows:
topic
topic of the received packetmessage
payload of the received packet'status'
function(thingName, stat, clientToken, stateObject) {}
Emitted when an operation update|get|delete
completes.
thingName
name of the Thing Shadow for which the operation has completedstat
status of the operation accepted|rejected
clientToken
the operation's clientTokenstateObject
the stateObject returned for the operationApplications can use clientToken values to correlate status events with the operations that they are associated with by saving the clientTokens returned from each operation.
'delta'
function(thingName, stateObject) {}
Emitted when a delta has been received for a registered Thing Shadow.
thingName
name of the Thing Shadow that has received a deltastateObject
the stateObject returned for the operation'foreignStateChange'
function(thingName, operation, stateObject) {}
Emitted when a different client's update or delete operation is accepted on the shadow.
thingName
name of the Thing Shadow for which the operation has completedoperation
operation performed by the foreign client update|delete
stateObject
the stateObject returned for the operationThis event allows an application to be aware of successful update or delete operations performed by different clients.
'timeout'
function(thingName, clientToken) {}
Emitted when an operation update|get|delete
has timed out.
thingName
name of the Thing Shadow that has received a timeoutclientToken
the operation's clientTokenApplications can use clientToken values to correlate timeout events with the operations that they are associated with by saving the clientTokens returned from each operation.
Register interest in the Thing Shadow named thingName
. The thingShadow class will
subscribe to any applicable topics, and will fire events for the Thing Shadow
until awsIot.thingShadow#unregister() is called with thingName
. options
can contain the following arguments to modify how this Thing Shadow is processed:
ignoreDeltas
: set to true
to not subscribe to the delta
sub-topic for this Thing Shadow; used in cases where the application is not interested in changes (e.g. update only.) (default false
)persistentSubscribe
: set to false
to unsubscribe from all operation sub-topics while not performing an operation (default true
)discardStale
: set to false
to allow receiving messages with old version numbers (default true
)enableVersioning
: set to true
to send version numbers with shadow updates (default true
)The persistentSubscribe
argument allows an application to get faster operation
responses at the expense of potentially receiving more irrelevant response
traffic (i.e., response traffic for other clients who have registered interest
in the same Thing Shadow). When persistentSubscribe
is set to false
, operation
sub-topics are only subscribed to during the scope of that operation;
note that in this mode, update, get, and delete operations will be much slower;
however, the application will be less likely to receive irrelevant response traffic.
The discardStale
argument allows applications to receive messages which have
obsolete version numbers. This can happen when messages are received out-of-order;
applications which set this argument to false
should use other methods to
determine how to treat the data (e.g. use a time stamp property to know how old/stale
it is).
If enableVersioning
is set to true, version numbers will be sent with each operation.
AWS IoT maintains version numbers for each shadow, and will reject operations which
contain the incorrect version; in applications where multiple clients update the same
shadow, clients can use versioning to avoid overwriting each other's changes.
If the callback
parameter is provided, it will be invoked after registration is complete (i.e., when subscription ACKs have been received for all shadow topics). Applications should wait until shadow registration is complete before performing update/get/delete operations.
Unregister interest in the Thing Shadow named thingName
. The thingShadow class
will unsubscribe from all applicable topics and no more events will be fired
for thingName
.
Update the Thing Shadow named thingName
with the state specified in the
JavaScript object stateObject
. thingName
must have been previously
registered
using awsIot.thingShadow#register(). The thingShadow class will subscribe
to all applicable topics and publish stateObject
on the update sub-topic.
This function returns a clientToken
, which is a unique value associated with
the update operation. When a 'status' or 'timeout' event is emitted,
the clientToken
will be supplied as one of the parameters, allowing the
application to keep track of the status of each operation. The caller may
create their own clientToken
value; if stateObject
contains a clientToken
property, that will be used rather than the internally generated value. Note
that it should be of atomic type (i.e. numeric or string). This function
returns 'null' if an operation is already in progress.
Get the current state of the Thing Shadow named thingName
, which must have
been previously registered using awsIot.thingShadow#register(). The
thingShadow class will subscribe to all applicable topics and publish on the
get sub-topic.
This function returns a clientToken
, which is a unique value associated with
the get operation. When a 'status or 'timeout' event is emitted,
the clientToken
will be supplied as one of the parameters, allowing the
application to keep track of the status of each operation. The caller may
supply their own clientToken
value (optional); if supplied, the value of
clientToken
will be used rather than the internally generated value. Note
that this value should be of atomic type (i.e. numeric or string). This
function returns 'null' if an operation is already in progress.
Delete the Thing Shadow named thingName
, which must have been previously
registered using awsIot.thingShadow#register(). The thingShadow class
will subscribe to all applicable topics and publish on the delete
sub-topic.
This function returns a clientToken
, which is a unique value associated with
the delete operation. When a 'status' or 'timeout' event is emitted,
the clientToken
will be supplied as one of the parameters, allowing the
application to keep track of the status of each operation. The caller may
supply their own clientToken
value (optional); if supplied, the value of
clientToken
will be used rather than the internally generated value. Note
that this value should be of atomic type (i.e. numeric or string). This
function returns 'null' if an operation is already in progress.
Identical to the mqtt.Client#publish() method, with the restriction that the topic may not represent a Thing Shadow. This method allows the user to publish messages to topics on the same connection used to access Thing Shadows.
Identical to the mqtt.Client#subscribe() method, with the restriction that the topic may not represent a Thing Shadow. This method allows the user to subscribe to messages from topics on the same connection used to access Thing Shadows.
Identical to the mqtt.Client#unsubscribe() method, with the restriction that the topic may not represent a Thing Shadow. This method allows the user to unsubscribe from topics on the same used to access Thing Shadows.
Invokes the mqtt.Client#end()
method on the MQTT connection owned by the thingShadow
class. The force
and callback
parameters are optional and identical in function to the
parameters in the mqtt.Client#end() method.
The jobs
class wraps an instance of the device
class with additional functionality to
handle job execution management through the AWS IoT Jobs platform. Arguments in deviceOptions
are the same as those in the device class and the jobs
class supports all of the
same events and functions as the device
class.
The jobs
class also supports the following methods:
Subscribes to job execution notifications for the thing named thingName
. If
operationName
is specified then the callback will only be called when a job
ready for execution contains a property called operation
in its job document with
a value matching operationName
. If operationName
is omitted then the callback
will be called for every job ready for execution that does not match another
subscribeToJobs
subscription.
thingName
name of the Thing to receive job execution notificationsoperationName
optionally filter job execution notifications to jobs with a value
for the operation
property that matches operationName
callback
- function (err, job) callback for when a job execution is ready for processing or an error occurs
- err
a subscription error or an error that occurs when client is disconnecting
- job
an object that contains job execution information and functions for updating job execution status.Unsubscribes from job execution notifications for the thing named thingName
having
operations with a value of the given operationName
. If operationName
is omitted then
the default handler for the thing with the given name is unsubscribed.
thingName
name of the Thing to cancel job execution notifications foroperationName
optional name of previously subscribed operation namescallback
- function (err) callback for when the unsubscribe operation completesCauses 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.
thingName
name of the Thing to cancel job execution notifications forcallback
- function (err) callback for when the startJobNotifications operation completesObject that contains job execution information and functions for updating job execution status.
The JSON document describing details of the job to be executed eg.
{
"operation": "install",
"otherProperty": "value",
...
}
Returns the job id.
Returns the job operation from the job document. Eg. 'install', 'reboot', etc.
Returns the current job status according to AWS Orchestra.
{
"status":"IN_PROGRESS|QUEUED",
"statusDetails": {
"progress":"50%"
}
}
Update the status of the job execution to be IN_PROGRESS for the thing associated with the job.
statusDetails
optional document describing the status details of the in progress job e.g.{
"string": "string",
"progress": "50%"
}
callback
- function(err) optional callback for when the operation completes, err is null if no error occurredUpdate the status of the job execution to be FAILED for the thing associated with the job.
statusDetails
optional document describing the status details of the in progress job e.g.{
"string": "string",
"progress": "0%"
}
callback
- function(err) optional callback for when the operation completes, err is null if no error occurredUpdate the status of the job execution to be SUCCESS for the thing associated with the job.
statusDetails
optional document describing the status details of the in progress job e.g.{
"string": "string",
"progress": "100%"
}
callback
- function(err) optional callback for when the operation completes, err is null if no error occurredThis SDK supports three types of connections to the AWS IoT platform:
The default connection type is MQTT over TLS with mutual certificate authentication; to
configure a WebSocket/TLS connection, set the protocol
option to wss
when instantiating
the awsIot.device() or awsIot.thingShadow() classes. To use custom auth,
set the protocol
option to wss-custom-auth
.
To use custom authorization, you must first set up an authorizer function in Lambda and register it with IoT. Once you do, you will be able to authenticate using this function. There are two ways to use custom auth:
customAuthHeaders
option to your headers object when instantiating the awsIotDevice()
or awsIot.thingShadow() classes. The headers object is an object containing the header name
and values as key-value pairs:1 { 2 'X-Amz-CustomAuthorizer-Name': 'TestAuthorizer', 3 'X-Amz-CustomAuthorizer-Signature': 'signature', 4 'TestAuthorizerToken': 'token' 5 }
customAuthQueryString
option to your headers object when instantiating the awsIotDevice() class. The query string is a string containing the values as key-value pairs:1 '?X-Amz-CustomAuthorizer-Name=TestAuthorizer&X-Amz-CustomAuthorizer-Signature=signature&TestAuthorizerToken=token'
The 'examples' directory contains several programs which demonstrate usage of the AWS IoT APIs:
device-example.js: demonstrate simple MQTT publish and subscribe operations.
echo-example.js: test Thing Shadow operation by echoing all delta state updates to the update topic; used in conjunction with the AWS IoT Console to verify connectivity with the AWS IoT platform.
thing-example.js: use a Thing Shadow to automatically synchronize state between a simulated device and a control application.
thing-passthrough-example.js: demonstrate use of a Thing Shadow with pasthrough of standard MQTT publish and subscribe messages.
temperature-control/temperature-control.js: an interactive device simulation which uses Thing Shadows.
jobs-example.js: receive example job execution messages and update job execution status.
jobs-agent.js: example agent to handle standard operations such as reboot, report system status, and shutdown. It also handles installation of files including but not limited to configuration files, program updates and security certificates. It also can install and launch other programs and manage their executions (start, stop and restart).
The example programs use command line parameters to set options. To see the available options, run the program and specify the '-h' option as follows:
1node examples/<EXAMPLE-PROGRAM> -h
NOTE: You have to use the certificate created in the same region as your host end point. You will also need to use unique custom endpoint with '-H' command line option when connect examples to IoT cloud.
The example programs can be configured to use a WebSocket/TLS connection to the AWS IoT platform by adding '--protocol=wss' to the command line to override the default setting of 'mqtts'.
1 -P, --protocol=PROTOCOL connect using PROTOCOL (mqtts|wss)
When using a WebSocket/TLS connection, you have the following options to set credentials.
1export AWS_ACCESS_KEY_ID=[a valid AWS access key ID] 2export AWS_SECRET_ACCESS_KEY=[a valid AWS secret access key]
The default shared credential file is located in ~/.aws/credentials
for Linux
users and %UserProfile%\.aws\credentials
for Windows users. This could be
configured using AWS CLI visit the AWS CLI home page.
Alternatively, you could provide credential file in different path or another profile by specifying in the awsIot.device(options)
.
The values of AWS_ACCESS_KEY_ID
and AWS_SECRET_ACCESS_KEY
must contain valid
AWS Identity and Access Management (IAM) credentials. For more information about AWS
IAM, visit the AWS IAM home page.
When not configured to use a WebSocket/TLS connection, the example programs require a client certificate and private key (created using either the AWS IoT Console or the AWS IoT CLI) in order to authenticate with AWS IoT. Each example program uses command line options to specify the names and/or locations of certificates as follows:
1 -f, --certificate-dir=DIR look in DIR for certificates
The --certificate-dir (-f) option will read all certificate and key files from the directory specified. Default certificate/key file names are as follows:
1 -k, --private-key=FILE use FILE as private key 2 -c, --client-certificate=FILE use FILE as client certificate 3 -a, --ca-certificate=FILE use FILE as CA certificate
The '-f' (certificate directory) option can be combined with these so that you don't have to specify absolute pathnames for each file.
The AWS IoT Console can generate JSON configuration data specifying the parameters required to connect a device to the AWS IoT Platform. The JSON configuration data includes pathnames to certificates, the hostname and port number, etc... The command line option '--configuration-file (-F)' is used when reading parameters from a configuration file.
1 -F, --configuration-file=FILE use FILE (JSON format) for configuration
The configuration file is in JSON format, and may contain the following properties:
device-example.js is run as two processes which communicate with one another via the AWS IoT platform using MQTT publish and subscribe. The command line option '--test-mode (-t)' is used to set which role each process performs. It's easiest to run each process in its own terminal window so that you can see the output generated by each. Note that in the following examples, all certificates are located in the ~/certs directory and have the default names as specified in the Certificate Configuration section.
1node examples/device-example.js -f ~/certs --test-mode=1 -H <PREFIX>.iot.<REGION>.amazonaws.com
1node examples/device-example.js -f ~/certs --test-mode=2 -H <PREFIX>.iot.<REGION>.amazonaws.com
Similar to device-example.js, thing-example.js is also run as two processes which communicate with one another via the AWS IoT platform. thing-example.js uses a Thing Shadow to synchronize state between the two processes, and the command line option '--test-mode (-t)' is used to set which role each process performs. As with device-example.js, it's best to run each process in its own terminal window or on separate hosts. In this example, the example programs are configured to use WebSocket/TLS connections to the AWS IoT platform as specified in the WebSocket Configuration.
1node examples/thing-example.js -P=wss --test-mode=1 -H <PREFIX>.iot.<REGION>.amazonaws.com
1node examples/thing-example.js -P=wss --test-mode=2 -H <PREFIX>.iot.<REGION>.amazonaws.com
Similar to thing-example.js, thing-passthrough-example.js is also run as two processes which communicate with one another via the AWS IoT platform. thing-passthrough-example.js uses a Thing Shadow to synchronize state from one process to another, and uses MQTT publish/subscribe to send information in the other direction. The command line option '--test-mode (-t)' is used to set which role each process performs. As with thing-example.js, it's best to run each process in its own terminal window. Note that in the following examples, all certificates are located in the ~/certs directory and have the default names as specified in the Certificate Configuration section.
1node examples/thing-passthrough-example.js -f ~/certs --test-mode=1 -H <PREFIX>.iot.<REGION>.amazonaws.com
1node examples/thing-passthrough-example.js -f ~/certs --test-mode=2 -H <PREFIX>.iot.<REGION>.amazonaws.com
echo-example.js is used in conjunction with the AWS IoT Console to verify connectivity with the AWS IoT platform and to perform interactive observation of Thing Shadow operation. In the following example, the program is run using the configuration file '../config.json', and the certificates are located in the '~/certs' directory. Here, the '-f' (certificate directory) and '-F' (configuration file) options are combined so that the configuration file doesn't need to contain absolute pathnames.
1node examples/echo-example.js -F ../config.json -f ~/certs --thing-name testThing1
temperature-control.js is an interactive simulation which demonstrates how Thing Shadows can be used to easily synchronize applications and internet-connected devices.
Like thing-example.js, temperature-control.js runs in two separate terminal windows and is configured via command-line options; in the following example, all certificates are located in the ~/certs directory and have the default names as specified in the Certificate Configuration section. The process running with '--test-mode=2' simulates an internet-connected temperature control device, and the process running with '--test-mode=1' simulates a mobile application which is monitoring/controlling it. The processes may be run on different hosts if desired.
temperature-control.js uses the blessed.js and blessed-contrib.js libraries to provide an interactive terminal interface; it looks best on an 80x25 terminal with a black background and white or green text and requires UTF-8 character encoding. You'll need to install these libraries in the examples/temperature-control directory as follows:
1cd examples/temperature-control 2npm install
1node examples/temperature-control/temperature-control.js -f ~/certs --test-mode=1 -H <PREFIX>.iot.<REGION>.amazonaws.com
1node examples/temperature-control/temperature-control.js -f ~/certs --test-mode=2 -H <PREFIX>.iot.<REGION>.amazonaws.com
The simulated temperature control device has two controls; Setpoint and Status. Status controls whether or not the device is active, and Setpoint controls the interior temperature the device will attempt to achieve. In addition, the device reports the current interior and exterior temperatures as well as its operating state (heating, cooling, or stopped).
Two Thing Shadows are used to connect the simulated device and mobile application; one contains the controls and the other contains the measured temperatures and operating state. Both processes can update the controls, but only the device can update the measured temperatures and the operating state.
Controlling the simulation is done using the up, down, left, right, and Enter keys as follows:
The operating state of the device is indicated by the color of the Interior temperature field as follows:
The following example shows the temperature control simulation in 'device' mode while the operating state is 'heating'.
The log window displays events of interest, e.g. network connectivity, Status toggles, re-synchronization with the Thing Shadow, etc...
In this example, the mobile application is disconnected from the network. Although it has requested that the Setpoint be lowered to 58 degrees, the command can't be sent to the device as there is no network connectivity, so the operating state still shows as 'stopped'. When the mobile application is reconnected to the network, it will attempt to update the Thing Shadow for the device's controls; if no control changes have been made on the device side during the disconnection period, the device will synchronize to the mobile application's requested state; otherwise, the mobile application will re- synchronize to the device's current state.
The simulation can be exited at any time by pressing q, Ctrl+c, or by selecting 'exit' on the menu bar.
jobs-example.js, like the echo-example.js can receive messages via the AWS IoT Console to verify connectivity with the AWS IoT platform. But it can also receive and process job executions initiated through the AWS IoT device jobs management platform. See the AWS IoT Jobs documentation here for more information on creating and deploying jobs.
1node examples/jobs-example.js -f ~/certs -H <PREFIX>.iot.<REGION>.amazonaws.com -T thingName
jobs-agent.js can be run on a device as-is or it can be modified to suit specific use cases. Example job documents are provided below. For more information see the AWS IoT connected device management documentation here.
1node examples/jobs-agent.js -f ~/certs -H <PREFIX>.iot.<REGION>.amazonaws.com -T agentThingName
The jobs-agent will respond to the AWS IoT jobs management platform with system status information when it receives a job execution notification with a job document that looks like this:
{
"operation": "systemStatus"
}
When the jobs-agent receives a reboot job document it will attempt to reboot the device it is running on while sending updates on its progress to the AWS IoT jobs management platform. After the reboot the job execution status will be marked as IN_PROGRESS until the jobs-agent is also restarted at which point the status will be updated to SUCCESS. To avoid manual steps during reboot it is suggested that device be configured to automatically start the jobs-agent at device startup time. Job document format:
{
"operation": "reboot"
}
When the jobs-agent receives a shutdown job document it will attempt to shutdown the device.
{
"operation": "shutdown"
}
When the jobs-agent receives an install job document it will attempt to install the files specified in the job document. An install job document should follow this general format.
{
"operation": "install",
"packageName": "uniquePackageName",
"workingDirectory": "../jobs-example-directory",
"launchCommand": "node jobs-example.js -f ~/certs -H <PREFIX>.iot.<REGION>.amazonaws.com -T thingName",
"autoStart": "true",
"files": [
{
"fileName": "jobs-example.js",
"fileVersion": "1.0.2.10",
"fileSource": {
"url": "https://some-bucket.s3.amazonaws.com/jobs-example.js"
},
"checksum": {
"inline": {
"value": "9569257356cfc5c7b2b849e5f58b5d287f183e08627743498d9bd52801a2fbe4"
},
"hashAlgorithm": "SHA256"
}
},
{
"fileName": "config.json",
"fileSource": {
"url": "https://some-bucket.s3.amazonaws.com/config.json"
}
}
]
}
packageName
: Each install operation must have a unique package name. If the packageName
matches a previous install operation then the new install operation overwrites the previous one.workingDirectory
: Optional property for working directorylaunchCommand
: Optional property for launching an application/package. If omitted copy files only.autoStart
: If set to true then agent will execute launch command when agent starts up.files
: Specifies files to be installed
fileName
: Name of file as written to file systemfileSource.url
: Location of file to be downloaded fromchecksum
: Optional file checksum
inline.value
: Checksum valuehashAlgorithm
: Checksum hash algorithm usedWhen the jobs-agent receives a start job document it will attempt to startup the specified package.
{
"operation": "start",
"packageName": "somePackageName"
}
When the jobs-agent receives a stop job document it will attempt to stop the specified package.
{
"operation": "stop",
"packageName": "somePackageName"
}
When the jobs-agent receives a restart job document it will attempt to restart the specified package.
{
"operation": "restart",
"packageName": "somePackageName"
}
This SDK can be packaged to run in a browser using browserify or webpack, and includes helper scripts and example application code to help you get started writing browser applications that use AWS IoT.
Browser applications connect to AWS IoT using MQTT over the Secure WebSocket Protocol. There are some important differences between Node.js and browser environments, so a few adjustments are necessary when using this SDK in a browser application.
When running in a browser environment, the SDK doesn't have access to the filesystem or process environment variables, so these can't be used to store credentials. While it might be possible for an application to prompt the user for IAM credentials, the Amazon Cognito Identity Service provides a more user-friendly way to retrieve credentials which can be used to access AWS IoT. The temperature-monitor browser example application illustrates this use case.
This SDK could also work with web applications using browserify
. First, you'll need to make sure that browserify
is installed. The following instructions and the scripts in this package assume that it is installed globally, as with:
1npm install -g browserify
This SDK includes a utility script called scripts/browserize.sh
. This script can create a browser bundle containing both the AWS SDK for JavaScript and this SDK, or you can use it to create application bundles for browser applications, like the ones under the examples/browser
directory. For Windows user who does not want to use bash shell, the SDK also includes batch file windows-browserize.bat
which does the same job as browserize.sh
but able to run in Windows CMD. To create the combined AWS SDK browser bundle, run this command in the SDK's top-level directory:
1npm run-script browserize
This command will create a browser bundle in browser/aws-iot-sdk-browser-bundle.js
. The browser bundle makes both the aws-sdk
and aws-iot-device-sdk
modules available so that you can require
them from your browserified application bundle.
NOTE: For Windows user who running scripts in CMD, since batch script file does not work well with NPM package script, Windows user could just call script directly to replace npm run-script browserize
. This also applies for example applications demonstrated below.
1.\scripts\windows-browserize.bat
You can also use the scripts/browserize.sh
script to browserify your own applications and use them with the AWS SDK browser bundle. For example, to prepare the temperature-monitor browser example application for use, run this command in the SDK's top-level directory:
1npm run-script browserize examples/browser/temperature-monitor/index.js
This command does two things. First, it creates an application bundle from examples/browser/temperature-monitor/index.js
and places it in examples/browser/temperature-monitor/bundle.js
. Second, it copies the browser/aws-iot-sdk-browser-bundle.js
into your application's directory where it can be used, e.g.:
1<script src="aws-iot-sdk-browser-bundle.js"></script> 2<script src="bundle.js"></script>
This SDK includes a companion browser application to the Temperature Control Example Application. The browser application allows you to monitor the status of the simulated temperature control device.
Follow the instructions to install the Temperature Control Example Application
In order for the browser application to be able to authenticate and connect to AWS IoT, you'll need to configure a Cognito Identity Pool. In the Amazon Cognito console, use Amazon Cognito to create a new identity pool, and allow unauthenticated identities to connect. Obtain the PoolID
constant. Make sure that the policy attached to the unauthenticated role has permissions to access the required AWS IoT APIs. More information about AWS IAM roles and policies can be found here.
Edit examples/browser/temperature-monitor/aws-configuration.js
, and replace the values of poolId
and region
with strings containing the ID of the Cognito Identity Pool and your AWS region (e.g., 'us-east-1'
) from the previous step.
Create the application browser bundle by executing the following command in the top-level directory of the SDK:
1npm run-script browserize examples/browser/temperature-monitor/index.js
Start an instance of the device simulation using:
1node examples/temperature-control/temperature-control.js -f ~/certs --test-mode=2 -H <PREFIX>.iot.<REGION>.amazonaws.com
NOTE: Although the above example shows connecting using a certificate/private key set, you can use any of the command line options described in the Example Programs Section.
examples/browser/temperature-monitor/index.html
in your web browser. It should connect to AWS IoT and began displaying the status of the simulated temperature control device you started in the previous step. If you change the device's settings, the browser window should update and display the latest status values.This SDK includes a browser application which demonstrates the functionality of AWS IoT lifecycle events. AWS IoT generates lifecycle events whenever clients connect or disconnect; applications can monitor these and take action when clients connect or disconnect from AWS IoT. Follow these instructions to run the application:
In order for the browser application to be able to authenticate and connect to AWS IoT, you'll need to configure a Cognito Identity Pool. In the Amazon Cognito console, use Amazon Cognito to create a new identity pool, and allow unauthenticated identities to connect. Obtain the PoolID
constant. Make sure that the policy attached to the unauthenticated role has permissions to access the required AWS IoT APIs. More information about AWS IAM roles and policies can be found here.
Edit examples/browser/lifecycle/aws-configuration.js
, and replace the values of poolId
and region
with strings containing the ID of the Cognito Identity Pool and your AWS region (e.g., 'us-east-1'
) from the previous step.
Create the application browser bundle by executing the following command in the top-level directory of the SDK:
1npm run-script browserize examples/browser/lifecycle/index.js
Open examples/browser/lifecycle/index.html
in your web browser. After connecting to AWS IoT, it should display 'connected clients'.
Start programs which connect to AWS IoT (e.g., the example programs in this package). Make sure that these programs are connecting to the same AWS region that your Cognito Identity Pool was created in. The browser application will display a green box containing the client ID of each client which connects; when the client disconnects, the box will disappear.
If a DynamoDB table named LifecycleEvents
exists in your account and has a primary key named clientId
, the lifecycle event browser monitor browser application will display the client ID contained in each row. By updating this table using an AWS IoT rule triggered by lifecycle events, you can maintain a persistent list of all of the currently connected clients within your account.
This SDK includes a browser application which implements a simple interactive MQTT client. You can use this application to subscribe to a topic and view the messages that arrive on it, or to publish to a topic. Follow these instructions to run the application:
In order for the browser application to be able to authenticate and connect to AWS IoT, you'll need to configure a Cognito Identity Pool. In the Amazon Cognito console, use Amazon Cognito to create a new identity pool, and allow unauthenticated identities to connect. Obtain the PoolID
constant. Make sure that the policy attached to the unauthenticated role has permissions to access the required AWS IoT APIs. More information about AWS IAM roles and policies can be found here.
Edit examples/browser/mqtt-explorer/aws-configuration.js
, and replace the values of poolId
and region
with strings containing the ID of the Cognito Identity Pool and your AWS region (e.g., 'us-east-1'
) from the previous step.
Create the application browser bundle by executing the following command in the top-level directory of the SDK:
1npm run-script browserize examples/browser/mqtt-explorer/index.js
Open examples/browser/mqtt-explorer/index.html
in your web browser. After connecting to AWS IoT, it should display input fields allowing you to subscribe or publish to a topic. By subscribing to '#', for example, you will be able to monitor all traffic within your AWS account as allowed by the policy associated with the unauthenticated role of your Cognito Identity Pool.
After your application development is complete, you will probably want to reduce the size of the browser bundle. There are a couple of easy techniques to do this, and by combining both of them you can create much smaller browser bundles.
The AWS SDK for JavaScript allows you to install only the features you use in your application. In order to use this feature when preparing a browser bundle, first you'll need to remove any existing bundle that you've already created:
1rm browser/aws-iot-sdk-browser-bundle.js
Define the AWS features your application uses as a comma-separated list in the AWS_SERVICES
environment variable. For example, the MQTT Explorer example uses only AWS Cognito Identity, so to create a bundle containing only this feature, do:
1export AWS_SERVICES=cognitoidentity
For a list of the AWS SDK feature names, refer to the features subdirectory of the AWS SDK for JavaScript. As another example, if your application uses Cognito Identity, DynamoDB, S3, and SQS, you would do:
1export AWS_SERVICES=cognitoidentity,dynamodb,s3,sqs
Create the browser app and bundle, e.g. for the MQTT Explorer example, do:
1npm run-script browserize examples/browser/mqtt-explorer/index.js
Uglify is an npm utility for minimizing the size of JavaScript source files. To use it, first install it as a global npm package:
1npm install -g uglify
Once installed, you can use it to reduce the bundle size:
1uglify -s ./browser/aws-iot-sdk-browser-bundle.js -o ./browser/aws-iot-sdk-browser-bundle-min.js
After you've created the minimized bundle, you'll need to make sure that your application loads this version rather than the non-minimized version, e.g:
1<script src="aws-iot-sdk-browser-bundle-min.js"></script>
By using both of the above techniques for the MQTT Explorer example, the bundle size can be reduced from 2.4MB to 615KB.
In order to work with webpack, you have to create a webpack package. You can put your file dependencies in entry.js
and output it as bundle.js
. An example is provided in the location ./examples/browser/mqtt-webpack
1cd ./examples/browser/mqtt-webpack 2npm install 3./node_modules/.bin/webpack --config webpack.config.js
The index.html
will load the output file bundle.js
and execute functions defined in entry.js
. This duplicates the example of mqtt-explore above which loaded SDK into web browser using browserify.
If you have problems connecting to the AWS IoT Platform when using this SDK or running the example programs, there are a few things to check:
npm -v
.This package includes unit tests which can be run as follows:
1npm test
Running the unit tests will also generate code coverage data in the 'reports' directory.
This SDK is distributed under the Apache License, Version 2.0, see LICENSE.txt and NOTICE.txt for more information.
If you have technical questions about AWS IoT Device SDK, use the AWS IoT Forum. For any other questions on AWS IoT, contact AWS Support.
No vulnerabilities found.
Reason
no dangerous workflow patterns detected
Reason
no binaries found in the repo
Reason
0 existing vulnerabilities detected
Reason
license file detected
Details
Reason
security policy file detected
Details
Reason
Found 21/26 approved changesets -- score normalized to 8
Reason
1 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
Reason
project is not fuzzed
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Score
Last Scanned on 2024-11-25
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More