### Setup and Build with Webpack Source: https://github.com/aws/aws-iot-device-sdk-js/blob/master/README.md Configure and build your project using webpack by installing dependencies and running the webpack command with a specific configuration file. ```sh cd ./examples/browser/mqtt-webpack npm install ./node_modules/.bin/webpack --config webpack.config.js ``` -------------------------------- ### Running Example Programs with Help Option Source: https://github.com/aws/aws-iot-device-sdk-js/blob/master/README.md To view the available command-line options for example programs, run the program with the '-h' flag. This helps in understanding how to configure and use the examples. ```bash node examples/ -h ``` -------------------------------- ### Install Temperature Control Dependencies Source: https://github.com/aws/aws-iot-device-sdk-js/blob/master/README.md Install the necessary libraries (blessed.js and blessed-contrib.js) for the temperature-control.js example. Navigate to the example's directory first. ```sh cd examples/temperature-control npm install ``` -------------------------------- ### Install and Require AWS IoT Device SDK Source: https://context7.com/aws/aws-iot-device-sdk-js/llms.txt Install the SDK via npm and require the top-level module to access its classes. This setup is necessary before using any of the SDK's functionalities. ```javascript // npm install aws-iot-device-sdk var awsIot = require('aws-iot-device-sdk'); // awsIot.device – MQTT client with offline queue + reconnect // awsIot.thingShadow – Device Shadow API // awsIot.jobs – IoT Jobs API ``` -------------------------------- ### Run Echo Example Source: https://github.com/aws/aws-iot-device-sdk-js/blob/master/README.md Execute the echo-example.js script to verify connectivity and observe Thing Shadow operations. Requires a configuration file and certificate directory. ```sh node examples/echo-example.js -F ../config.json -f ~/certs --thing-name testThing1 ``` -------------------------------- ### Define Install Job Operation Source: https://github.com/aws/aws-iot-device-sdk-js/blob/master/README.md This JSON document defines an 'install' job operation for the jobs-agent. It specifies the package name, installation directory, launch command, and the files to be downloaded and installed, including their source URLs and checksums. ```json { "operation": "install", "packageName": "uniquePackageName", "workingDirectory": "../jobs-example-directory", "launchCommand": "node jobs-example.js -f ~/certs -H .iot..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" } } ] } ``` -------------------------------- ### Install AWS IoT Device SDK from GitHub Source: https://github.com/aws/aws-iot-device-sdk-js/blob/master/README.md Clone the SDK repository from GitHub and install dependencies locally. This method is useful for development or when needing the latest unreleased code. ```bash git clone https://github.com/aws/aws-iot-device-sdk-js.git cd aws-iot-device-sdk-js npm install ``` -------------------------------- ### Define Start Job Operation Source: https://github.com/aws/aws-iot-device-sdk-js/blob/master/README.md This JSON document defines a 'start' job operation for the jobs-agent, specifying the package name to be started. ```json { "operation": "start", "packageName": "somePackageName" } ``` -------------------------------- ### Run Thing Passthrough Example Source: https://github.com/aws/aws-iot-device-sdk-js/blob/master/README.md Execute the thing-passthrough-example.js script. Requires certificate files and an AWS IoT endpoint. ```sh node examples/thing-passthrough-example.js -f ~/certs --test-mode=2 -H .iot..amazonaws.com ``` -------------------------------- ### Run thing-passthrough-example.js - Terminal 1 Source: https://github.com/aws/aws-iot-device-sdk-js/blob/master/README.md Example command to run the first process of thing-passthrough-example.js. It specifies the certificate directory, test mode, and the AWS IoT endpoint. ```sh node examples/thing-passthrough-example.js -f ~/certs --test-mode=1 -H .iot..amazonaws.com ``` -------------------------------- ### Install Uglify Globally Source: https://github.com/aws/aws-iot-device-sdk-js/blob/master/README.md Install the Uglify npm utility globally to minimize JavaScript source files. ```sh npm install -g uglify ``` -------------------------------- ### Run device-example.js - Terminal 1 Source: https://github.com/aws/aws-iot-device-sdk-js/blob/master/README.md Example command to run the first process of device-example.js. It specifies the certificate directory, test mode, and the AWS IoT endpoint. ```sh node examples/device-example.js -f ~/certs --test-mode=1 -H .iot..amazonaws.com ``` -------------------------------- ### Install AWS IoT Device SDK via npm Source: https://github.com/aws/aws-iot-device-sdk-js/blob/master/README.md Install the AWS IoT Device SDK for JavaScript using npm. Ensure you have Node.js version 8.17 or above. ```bash npm install aws-iot-device-sdk ``` -------------------------------- ### Subscribe, Publish, and Handle Messages Source: https://context7.com/aws/aws-iot-device-sdk-js/llms.txt This example shows how to subscribe to a topic, publish messages with quality of service, and process incoming messages. It also includes error handling for subscribe and publish operations. ```javascript // Publish – queued automatically while offline device.on('connect', function() { device.subscribe('sensor/temperature', { qos: 1 }, function(err, granted) { if (err) { console.error('subscribe failed', err); return; } console.log('subscribed:', granted); }); device.publish('sensor/temperature', JSON.stringify({ value: 23.5 }), { qos: 1 }, function(err) { if (err) console.error('publish failed', err); }); }); device.on('message', function(topic, message) { // message is a Buffer var data = JSON.parse(message.toString()); console.log('received on', topic, data); }); ``` -------------------------------- ### Install Browserify Globally Source: https://github.com/aws/aws-iot-device-sdk-js/blob/master/README.md This command installs the browserify tool globally on your system. It is a prerequisite for packaging the AWS IoT Device SDK for JavaScript to run in a browser environment. ```sh npm install -g browserify ``` -------------------------------- ### Run device-example.js - Terminal 2 Source: https://github.com/aws/aws-iot-device-sdk-js/blob/master/README.md Example command to run the second process of device-example.js. It specifies the certificate directory, test mode, and the AWS IoT endpoint. ```sh node examples/device-example.js -f ~/certs --test-mode=2 -H .iot..amazonaws.com ``` -------------------------------- ### Browserize MQTT Explorer Example Application Source: https://github.com/aws/aws-iot-device-sdk-js/blob/master/README.md Use this command to create a browser bundle for the MQTT explorer application. This allows interactive MQTT client functionality in the browser. Configure AWS credentials and Cognito settings in `aws-configuration.js`. ```sh npm run-script browserize examples/browser/mqtt-explorer/index.js ``` -------------------------------- ### Run thing-example.js - Terminal 1 Source: https://github.com/aws/aws-iot-device-sdk-js/blob/master/README.md Example command to run the first process of thing-example.js using WebSocket/TLS. It specifies the protocol, test mode, and the AWS IoT endpoint. ```sh node examples/thing-example.js -P=wss --test-mode=1 -H .iot..amazonaws.com ``` -------------------------------- ### Check Node.js Version Source: https://github.com/aws/aws-iot-device-sdk-js/blob/master/README.md Verify your Node.js version before installing the SDK. Node.js version 8.17 or above is required. ```bash node -v ``` -------------------------------- ### Run thing-example.js - Terminal 2 Source: https://github.com/aws/aws-iot-device-sdk-js/blob/master/README.md Example command to run the second process of thing-example.js using WebSocket/TLS. It specifies the protocol, test mode, and the AWS IoT endpoint. ```sh node examples/thing-example.js -P=wss --test-mode=2 -H .iot..amazonaws.com ``` -------------------------------- ### Browserize Lifecycle Example Application Source: https://github.com/aws/aws-iot-device-sdk-js/blob/master/README.md Use this command to create a browser bundle for the lifecycle event monitor application. Ensure you have configured your AWS credentials and Cognito settings in `aws-configuration.js`. ```sh npm run-script browserize examples/browser/lifecycle/index.js ``` -------------------------------- ### Browser Usage with browserify/webpack Source: https://context7.com/aws/aws-iot-device-sdk-js/llms.txt Bundles the SDK for browser applications. In browsers, credentials must be obtained via Amazon Cognito. This example shows how to bundle and use the SDK in a browser environment. ```bash # Install browserify globally npm install -g browserify # Create the combined AWS SDK + IoT SDK browser bundle npm run-script browserize # Bundle your own app against the browser bundle npm run-script browserize examples/browser/temperature-monitor/index.js # → outputs: examples/browser/temperature-monitor/bundle.js # examples/browser/temperature-monitor/aws-iot-sdk-browser-bundle.js # With webpack (see examples/browser/mqtt-webpack/) cd examples/browser/mqtt-webpack && npm install ./node_modules/.bin/webpack --config webpack.config.js ``` ```html ``` ```javascript // Browser application index.js (bundled with browserify/webpack) var AWSIoTData = require('aws-iot-device-sdk'); var AWS = require('aws-sdk'); AWS.config.region = 'us-east-1'; var cognitoIdentity = new AWS.CognitoIdentity(); cognitoIdentity.getId({ IdentityPoolId: 'us-east-1:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' }, function(err, data) { cognitoIdentity.getCredentialsForIdentity({ IdentityId: data.IdentityId }, function(err, creds) { var mqttClient = AWSIoTData.device({ protocol: 'wss', host: 'abcdefg123.iot.us-east-1.amazonaws.com', clientId: 'browser-' + Math.random().toString(36).substring(7), accessKeyId: creds.Credentials.AccessKeyId, secretKey: creds.Credentials.SecretKey, sessionToken: creds.Credentials.SessionToken }); mqttClient.on('connect', function() { mqttClient.subscribe('sensor/#'); }); mqttClient.on('message', function(topic, payload) { document.getElementById('output').textContent = topic + ': ' + payload.toString(); }); }); }); ``` -------------------------------- ### jobs-agent reboot operation Source: https://github.com/aws/aws-iot-device-sdk-js/blob/master/README.md Example job document for the jobs-agent to initiate a device reboot and report progress. It's recommended to configure the device to auto-start the agent. ```json { "operation": "reboot" } ``` -------------------------------- ### Configuring WebSocket Protocol Source: https://github.com/aws/aws-iot-device-sdk-js/blob/master/README.md Override the default 'mqtts' protocol to 'wss' for WebSocket/TLS connections by adding '--protocol=wss' to the command line arguments when running example programs. ```bash -P, --protocol=PROTOCOL connect using PROTOCOL (mqtts|wss) ``` -------------------------------- ### Run jobs-example.js Source: https://github.com/aws/aws-iot-device-sdk-js/blob/master/README.md Execute the jobs-example script to verify connectivity with AWS IoT and process job executions. Requires certificate files and endpoint information. ```bash node examples/jobs-example.js -f ~/certs -H .iot..amazonaws.com -T thingName ``` -------------------------------- ### Get Thing Shadow State Source: https://context7.com/aws/aws-iot-device-sdk-js/llms.txt Retrieves the current state of a registered Thing Shadow. Handles 'connect', 'status', and 'timeout' events to manage the get operation and process the response. ```javascript var pendingTokens = {}; thingShadows.on('connect', function() { thingShadows.register('WeatherStation', {}, function() { var token = thingShadows.get('WeatherStation'); if (token) pendingTokens[token] = 'get'; }); }); thingShadows.on('status', function(thingName, stat, clientToken, stateObject) { if (pendingTokens[clientToken] === 'get' && stat === 'accepted') { console.log('current shadow state:', JSON.stringify(stateObject)); // stateObject.state.reported, stateObject.state.desired, etc. } delete pendingTokens[clientToken]; }); thingShadows.on('timeout', function(thingName, clientToken) { console.warn('get timed out for', thingName); delete pendingTokens[clientToken]; }); ``` -------------------------------- ### awsIot.thingShadow#get Source: https://github.com/aws/aws-iot-device-sdk-js/blob/master/README.md Retrieves the current state of a Thing Shadow. The Thing Shadow must have been previously registered. This function publishes to the 'get' sub-topic and returns a client token for tracking the operation. ```APIDOC ## awsIot.thingShadow#get(thingName, [clientToken]) ### Description Get the current state of the Thing Shadow named `thingName`, which must have been previously registered using [awsIot.thingShadow#register()](#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. ``` -------------------------------- ### Create and Use Thing Shadow Client Source: https://context7.com/aws/aws-iot-device-sdk-js/llms.txt Initializes the Thing Shadow client with device credentials and options. Handles connection, registration, and state updates. Listen for events like 'connect', 'status', 'delta', 'foreignStateChange', and 'timeout'. ```javascript var awsIot = require('aws-iot-device-sdk'); var thingShadows = awsIot.thingShadow({ keyPath: './certs/private.pem.key', certPath: './certs/certificate.pem.crt', caPath: './certs/root-CA.crt', clientId: 'shadow-client-001', host: 'abcdefg123.iot.us-east-1.amazonaws.com' }, { operationTimeout: 10000 // ms before 'timeout' event fires (default 10000) }); thingShadows.on('connect', function() { // Register interest in a Thing Shadow thingShadows.register('MyThermostat', { persistentSubscribe: true, // stay subscribed (default true, faster ops) ignoreDeltas: false, // receive delta events (default false) discardStale: true, // drop out-of-order messages (default true) enableVersioning: true // send/receive version numbers (default true) }, function(err) { if (err) { console.error('register failed:', err); return; } console.log('registered MyThermostat'); // Update shadow desired state var clientToken = thingShadows.update('MyThermostat', { state: { desired: { setpoint: 22, mode: 'cool' } } }); if (clientToken === null) { console.log('update rejected – another operation is in progress'); } else { console.log('update sent with clientToken:', clientToken); } }); }); // Status event: fired after accepted or rejected response to update/get/delete thingShadows.on('status', function(thingName, stat, clientToken, stateObject) { // stat === 'accepted' | 'rejected' console.log('status for', thingName, '→', stat); console.log('clientToken:', clientToken); console.log('state:', JSON.stringify(stateObject)); }); // Delta event: fired when desired !== reported state thingShadows.on('delta', function(thingName, stateObject) { console.log('delta for', thingName, ':', JSON.stringify(stateObject)); // Acknowledge the delta by updating reported state thingShadows.update(thingName, { state: { reported: stateObject.state.desired } }); }); // Foreign state change: another client updated or deleted the shadow thingShadows.on('foreignStateChange', function(thingName, operation, stateObject) { console.log('foreign', operation, 'on', thingName, ':', JSON.stringify(stateObject)); }); // Timeout event: no accepted/rejected response within operationTimeout thingShadows.on('timeout', function(thingName, clientToken) { console.warn('operation timed out for', thingName, 'token:', clientToken); }); thingShadows.on('error', function(err) { console.error(err); }); ``` -------------------------------- ### jobs-agent shutdown operation Source: https://github.com/aws/aws-iot-device-sdk-js/blob/master/README.md Example job document for the jobs-agent to shut down the device. ```json { "operation": "shutdown" } ``` -------------------------------- ### jobs-agent systemStatus operation Source: https://github.com/aws/aws-iot-device-sdk-js/blob/master/README.md Example job document for the jobs-agent to report system status to the AWS IoT jobs management platform. ```json { "operation": "systemStatus" } ``` -------------------------------- ### Use JSON Configuration File Source: https://github.com/aws/aws-iot-device-sdk-js/blob/master/README.md Use the --configuration-file option to load connection parameters from a JSON file. This file can specify host, port, client ID, and certificate paths. ```sh -F, --configuration-file=FILE use FILE (JSON format) for configuration ``` -------------------------------- ### Start Job Notifications Source: https://github.com/aws/aws-iot-device-sdk-js/blob/master/README.md Call this function to have any queued job executions for a given thing published to the subscribeToJobs handler. It only needs to be invoked once per thing. ```javascript awsIot.jobs.startJobNotifications(thingName, [callback]) ``` -------------------------------- ### Update Job Status to Succeeded Source: https://github.com/aws/aws-iot-device-sdk-js/blob/master/README.md This function updates the job execution status to 'SUCCESS'. An optional statusDetails object can be provided, for example, to indicate 100% completion. ```javascript job.succeeded([statusDetails],[callback]) ``` -------------------------------- ### Run Unit Tests Source: https://github.com/aws/aws-iot-device-sdk-js/blob/master/README.md Execute the unit tests for the SDK using the npm test command. This will also generate code coverage data. ```sh npm test ``` -------------------------------- ### Create Combined AWS SDK Browser Bundle (Windows CMD) Source: https://github.com/aws/aws-iot-device-sdk-js/blob/master/README.md For Windows users, this batch script performs the same function as `npm run-script browserize` to create a combined browser bundle. It can be called directly in the Windows CMD. ```sh .\scripts\windows-browserize.bat ``` -------------------------------- ### Unregister Thing Shadow Source: https://context7.com/aws/aws-iot-device-sdk-js/llms.txt Unsubscribes from all shadow topics for a given thing name and removes it from the internal registry. This example shows how to unregister multiple things before ending the connection. ```javascript // Clean up all registered shadows before disconnect var registeredThings = ['Thermostat1', 'Thermostat2', 'Thermostat3']; registeredThings.forEach(function(name) { thingShadows.unregister(name); }); thingShadows.end(false, function() { console.log('all shadows unregistered and connection closed'); }); ``` -------------------------------- ### Specify Individual Certificate Files Source: https://github.com/aws/aws-iot-device-sdk-js/blob/master/README.md Use these options to specify the exact file paths for your private key, client certificate, and CA certificate. ```sh -k, --private-key=FILE use FILE as private key ``` ```sh -c, --client-certificate=FILE use FILE as client certificate ``` ```sh -a, --ca-certificate=FILE use FILE as CA certificate ``` -------------------------------- ### awsIot.thingShadow(deviceOptions, thingShadowOptions) Source: https://context7.com/aws/aws-iot-device-sdk-js/llms.txt Creates a Thing Shadow client that wraps a device instance with the AWS IoT Shadow API. It supports multiple Thing Shadow registrations per connection, version tracking, delta notifications, and foreign state change events. ```APIDOC ## `awsIot.thingShadow(deviceOptions, thingShadowOptions)` – Device Shadow Client Creates a Thing Shadow client that wraps a `device` instance with the AWS IoT Shadow API. Supports multiple Thing Shadow registrations per connection, version tracking, delta notifications, and foreign state change events. ```js var awsIot = require('aws-iot-device-sdk'); var thingShadows = awsIot.thingShadow({ keyPath: './certs/private.pem.key', certPath: './certs/certificate.pem.crt', caPath: './certs/root-CA.crt', clientId: 'shadow-client-001', host: 'abcdefg123.iot.us-east-1.amazonaws.com' }, { operationTimeout: 10000 // ms before 'timeout' event fires (default 10000) }); thingShadows.on('connect', function() { // Register interest in a Thing Shadow thingShadows.register('MyThermostat', { persistentSubscribe: true, // stay subscribed (default true, faster ops) ignoreDeltas: false, // receive delta events (default false) discardStale: true, // drop out-of-order messages (default true) enableVersioning: true // send/receive version numbers (default true) }, function(err) { if (err) { console.error('register failed:', err); return; } console.log('registered MyThermostat'); // Update shadow desired state var clientToken = thingShadows.update('MyThermostat', { state: { desired: { setpoint: 22, mode: 'cool' } } }); if (clientToken === null) { console.log('update rejected – another operation is in progress'); } else { console.log('update sent with clientToken:', clientToken); } }); }); // Status event: fired after accepted or rejected response to update/get/delete thingShadows.on('status', function(thingName, stat, clientToken, stateObject) { // stat === 'accepted' | 'rejected' console.log('status for', thingName, '→', stat); console.log('clientToken:', clientToken); console.log('state:', JSON.stringify(stateObject)); }); // Delta event: fired when desired !== reported state thingShadows.on('delta', function(thingName, stateObject) { console.log('delta for', thingName, ':', JSON.stringify(stateObject)); // Acknowledge the delta by updating reported state thingShadows.update(thingName, { state: { reported: stateObject.state.desired } }); }); // Foreign state change: another client updated or deleted the shadow thingShadows.on('foreignStateChange', function(thingName, operation, stateObject) { console.log('foreign', operation, 'on', thingName, ':', JSON.stringify(stateObject)); }); // Timeout event: no accepted/rejected response within operationTimeout thingShadows.on('timeout', function(thingName, clientToken) { console.warn('operation timed out for', thingName, 'token:', clientToken); }); thingShadows.on('error', function(err) { console.error(err); }); ``` ``` -------------------------------- ### awsIot.jobs Source: https://github.com/aws/aws-iot-device-sdk-js/blob/master/README.md Initializes the jobs class, wrapping a device instance with functionality for AWS IoT Jobs. ```APIDOC ## awsIot.jobs(deviceOptions) ### Description Initializes the `jobs` class, which enhances a `device` instance with capabilities for managing job execution through the AWS IoT Jobs platform. The `jobs` class supports all events and functions of the `device` class, along with its own specific methods. ### Parameters #### Path Parameters - **deviceOptions** (object) - Required - Options for the underlying device instance, same as those used for the [device class](#device). ``` -------------------------------- ### Create MQTT Device Client (TLS) Source: https://context7.com/aws/aws-iot-device-sdk-js/llms.txt Use this snippet to create a device client for MQTT over TLS connections. Ensure you provide valid paths to your private key, certificate, and root CA certificate. ```javascript var awsIot = require('aws-iot-device-sdk'); // --- Certificate-based MQTT over TLS (port 8883) --- var device = awsIot.device({ keyPath: './certs/private.pem.key', certPath: './certs/certificate.pem.crt', caPath: './certs/root-CA.crt', clientId: 'my-device-001', host: 'abcdefg123.iot.us-east-1.amazonaws.com', // Reconnect tuning (all in milliseconds) baseReconnectTimeMs: 1000, // first reconnect wait (default 1000) maximumReconnectTimeMs: 128000, // max reconnect wait (default 128000) minimumConnectionTimeMs: 20000, // time before "stable" (default 20000) drainTimeMs: 250, // inter-publish drain rate (default 250) // Offline publish queue offlineQueueing: true, // queue publishes while offline offlineQueueMaxSize: 100, // 0 = unlimited offlineQueueDropBehavior:'oldest',// 'oldest' | 'newest' autoResubscribe: true, // re-subscribe after reconnect enableMetrics: true, // report SDK version to AWS debug: false // verbose logging }); ``` -------------------------------- ### jobs.startJobNotifications(thingName, callback) Source: https://context7.com/aws/aws-iot-device-sdk-js/llms.txt Triggers the delivery of any queued pending jobs for a given thing. This should typically be called once per thing. ```APIDOC ## jobs.startJobNotifications(thingName, callback) ### Description Triggers delivery of any queued pending jobs for `thingName`. Call once per thing. ### Parameters - **thingName** (string) - The name of the thing for which to start job notifications. - **callback** (function) - The function to call after attempting to start notifications. - **err** (Error) - An error object if starting notifications fails. ``` -------------------------------- ### Create Application Browser Bundle Source: https://github.com/aws/aws-iot-device-sdk-js/blob/master/README.md This command creates an application-specific browser bundle for your own JavaScript code and copies the AWS IoT SDK browser bundle into your application's directory. This allows your application code to use the SDK in the browser. ```sh npm run-script browserize examples/browser/temperature-monitor/index.js ``` -------------------------------- ### Create and Use AWS IoT Jobs Client Source: https://context7.com/aws/aws-iot-device-sdk-js/llms.txt Initializes the Jobs client with security credentials and host information. It then subscribes to job notifications, handles job execution lifecycle (in-progress, succeeded, failed), and triggers job notification delivery. ```javascript var awsIot = require('aws-iot-device-sdk'); var jobs = awsIot.jobs({ keyPath: './certs/private.pem.key', certPath: './certs/certificate.pem.crt', caPath: './certs/root-CA.crt', clientId: 'jobs-device-001', host: 'abcdefg123.iot.us-east-1.amazonaws.com' }); jobs.on('connect', function() { console.log('connected to IoT Jobs'); // Subscribe to ALL job types with a default handler jobs.subscribeToJobs('my-device', function(err, job) { if (err) { console.error('jobs subscription error:', err); return; } console.log('received job:', job.id, 'operation:', job.operation); console.log('job document:', JSON.stringify(job.document)); // Mark in-progress job.inProgress({ progress: '0%' }, function(err) { if (err) { job.failed({ reason: err.message }); return; } // Simulate work setTimeout(function() { job.succeeded({ progress: '100%' }, function(err) { if (err) console.error('failed to mark succeeded:', err); else console.log('job', job.id, 'completed'); }); }, 2000); }); }); // Subscribe to a specific operation type (overrides the default for 'install') jobs.subscribeToJobs('my-device', 'install', function(err, job) { if (err) { console.error(err); return; } console.log('install job received, files:', job.document.files); job.inProgress({ step: 'downloading' }, function(err) { if (err) return job.failed(); // ... download files, then: job.succeeded({ step: 'complete' }); }); }); // Trigger delivery of any queued pending jobs (call once per thing) jobs.startJobNotifications('my-device', function(err) { if (err) console.error('startJobNotifications error:', err); else console.log('job notifications started'); }); }); jobs.on('error', function(err) { console.error('jobs error:', err); }); ``` -------------------------------- ### awsIot.device(options) Source: https://context7.com/aws/aws-iot-device-sdk-js/llms.txt Creates an MQTT client configured for a TLS or WebSocket connection to the AWS IoT platform. The returned object extends mqtt.Client and inherits all of its publish/subscribe methods, extended with offline queuing, auto-resubscription, and progressive backoff reconnection. ```APIDOC ## `awsIot.device(options)` – MQTT Device Client Creates an MQTT client configured for a TLS or WebSocket connection to the AWS IoT platform. The returned object extends `mqtt.Client` and inherits all of its publish/subscribe methods, extended with offline queuing, auto-resubscription, and progressive backoff reconnection. ### Options for Certificate-based MQTT over TLS (port 8883): - `keyPath`: Path to the private key file. - `certPath`: Path to the certificate file. - `caPath`: Path to the root CA certificate file. - `clientId`: Unique identifier for the device. - `host`: AWS IoT endpoint hostname. - `baseReconnectTimeMs`: Initial delay before the first reconnect attempt (default: 1000ms). - `maximumReconnectTimeMs`: Maximum delay between reconnect attempts (default: 128000ms). - `minimumConnectionTimeMs`: Time required for a connection to be considered stable before backoff resets (default: 20000ms). - `drainTimeMs`: Delay between publishing messages when offline queuing is enabled (default: 250ms). - `offlineQueueing`: Boolean to enable or disable offline message queuing (default: false). - `offlineQueueMaxSize`: Maximum size of the offline message queue (0 for unlimited). - `offlineQueueDropBehavior`: Behavior when the queue is full ('oldest' or 'newest'). - `autoResubscribe`: Boolean to automatically re-subscribe to topics after reconnecting (default: false). - `enableMetrics`: Boolean to enable reporting SDK version to AWS (default: false). - `debug`: Boolean to enable verbose logging (default: false). ### Options for WebSocket/SigV4 (port 443): - `protocol`: Set to 'wss'. - `host`: AWS IoT endpoint hostname. - `clientId`: Unique identifier for the device. - `accessKeyId`: AWS access key ID. - `secretKey`: AWS secret access key. - `sessionToken`: Session token (required for STS/Cognito). ### Options for Custom Authorizer (port 443): - `protocol`: Set to 'wss-custom-auth'. - `host`: AWS IoT endpoint hostname. - `clientId`: Unique identifier for the device. - `customAuthHeaders`: An object containing custom authorization headers, such as: - `'X-Amz-CustomAuthorizer-Name'`: Name of the custom authorizer. - `'X-Amz-CustomAuthorizer-Signature'`: Signature of the custom authorizer. - `[Other Custom Headers]`: Any other custom headers required by the authorizer. ### MQTT Events (inherited from mqtt.js): - `connect`: Emitted when the client successfully connects. - `reconnect`: Emitted when the client attempts to reconnect. - `offline`: Emitted when the client goes offline. - `close`: Emitted when the connection is closed. - `error`: Emitted when an error occurs. - `message`: Emitted when a message is received on a subscribed topic. - `packetsend`: Low-level hook for outgoing packets. - `packetreceive`: Low-level hook for incoming packets. ### Example Usage: ```javascript var awsIot = require('aws-iot-device-sdk'); // Certificate-based MQTT over TLS var device = awsIot.device({ keyPath: './certs/private.pem.key', certPath: './certs/certificate.pem.crt', caPath: './certs/root-CA.crt', clientId: 'my-device-001', host: 'abcdefg123.iot.us-east-1.amazonaws.com', // ... other options }); // WebSocket/SigV4 var deviceWss = awsIot.device({ protocol: 'wss', host: 'abcdefg123.iot.us-east-1.amazonaws.com', clientId: 'my-browser-client', accessKeyId: process.env.AWS_ACCESS_KEY_ID, secretKey: process.env.AWS_SECRET_ACCESS_KEY, sessionToken: process.env.AWS_SESSION_TOKEN }); // Custom Authorizer var deviceCustomAuth = awsIot.device({ protocol: 'wss-custom-auth', host: 'abcdefg123.iot.us-east-1.amazonaws.com', clientId: 'my-custom-auth-device', customAuthHeaders: { 'X-Amz-CustomAuthorizer-Name': 'MyLambdaAuthorizer', 'X-Amz-CustomAuthorizer-Signature': '', 'MyTokenName': '' } }); // Event handlers device.on('connect', function() { console.log('connected'); device.subscribe('sensor/temperature', { qos: 1 }, function(err, granted) { if (err) { console.error('subscribe failed', err); return; } console.log('subscribed:', granted); }); device.publish('sensor/temperature', JSON.stringify({ value: 23.5 }), { qos: 1 }, function(err) { if (err) console.error('publish failed', err); }); }); device.on('message', function(topic, message) { var data = JSON.parse(message.toString()); console.log('received on', topic, data); }); // Unsubscribe device.unsubscribe('sensor/temperature', function() { console.log('unsubscribed'); }); // Graceful disconnect device.end(false, function() { console.log('disconnected'); }); ``` -------------------------------- ### Create Combined AWS SDK Browser Bundle Source: https://github.com/aws/aws-iot-device-sdk-js/blob/master/README.md Use this command to create a browser bundle that includes both the AWS SDK for JavaScript and the AWS IoT Device SDK. This bundle makes both modules available for use in browserified applications. ```sh npm run-script browserize ``` -------------------------------- ### awsIot.thingShadow#publish Source: https://github.com/aws/aws-iot-device-sdk-js/blob/master/README.md Publishes a message to a specified topic, identical to mqtt.Client#publish but restricted from using Thing Shadow topics. ```APIDOC ## awsIot.thingShadow#publish(topic, message, [options], [callback]) ### Description Publishes a message to a given topic. This method is identical to `mqtt.Client#publish()` with the restriction that the topic cannot be a Thing Shadow topic. It allows users to publish messages on the same connection used for Thing Shadows. ### Method ``` awsIot.thingShadow.publish(topic, message, [options], [callback]) ``` ### Parameters #### Path Parameters - **topic** (string) - Required - The topic to publish the message to. Cannot be a Thing Shadow topic. - **message** (string|Buffer|object) - Required - The message payload to publish. - **options** (object) - Optional - Publishing options. - **callback** (function) - Optional - Callback function executed upon publish completion. ``` -------------------------------- ### awsIot.thingShadow#subscribe Source: https://github.com/aws/aws-iot-device-sdk-js/blob/master/README.md Subscribes to a specified topic, identical to mqtt.Client#subscribe but restricted from using Thing Shadow topics. ```APIDOC ## awsIot.thingShadow#subscribe(topic, [options], [callback]) ### Description Subscribes to a given topic. This method is identical to `mqtt.Client#subscribe()` with the restriction that the topic cannot be a Thing Shadow topic. It allows users to subscribe to messages on the same connection used for Thing Shadows. ### Method ``` awsIot.thingShadow.subscribe(topic, [options], [callback]) ``` ### Parameters #### Path Parameters - **topic** (string) - Required - The topic to subscribe to. Cannot be a Thing Shadow topic. - **options** (object) - Optional - Subscription options. - **callback** (function) - Optional - Callback function executed upon subscription. ``` -------------------------------- ### Run Temperature Control - Device Mode Source: https://github.com/aws/aws-iot-device-sdk-js/blob/master/README.md Run the temperature-control.js script in 'device' mode, simulating an internet-connected temperature control device. Requires certificate files and an AWS IoT endpoint. ```sh node examples/temperature-control/temperature-control.js -f ~/certs --test-mode=2 -H .iot..amazonaws.com ``` -------------------------------- ### thingShadows.register(thingName, [options], [callback]) Source: https://context7.com/aws/aws-iot-device-sdk-js/llms.txt Subscribes to all relevant shadow topics for `thingName`. The optional `callback` is invoked when all subscription ACKs have been received; wait for it before issuing shadow operations. ```APIDOC ## `thingShadows.register(thingName, [options], [callback])` – Register a Thing Shadow Subscribes to all relevant shadow topics for `thingName`. The optional `callback` is invoked when all subscription ACKs have been received — wait for it before issuing shadow operations. ```js thingShadows.on('connect', function() { // Register with default options (persistentSubscribe, versioning, delta all enabled) thingShadows.register('MotionSensor', {}, function(err, failedTopics) { if (err) { console.error('subscription error:', err, failedTopics); return; } // Safe to perform operations now var token = thingShadows.get('MotionSensor'); console.log('get issued with token:', token); }); // Register update-only device (no deltas, non-persistent subscriptions) thingShadows.register('AuditLogger', { ignoreDeltas: true, persistentSubscribe: false }); }); ``` ``` -------------------------------- ### awsIot.thingShadow#end Source: https://github.com/aws/aws-iot-device-sdk-js/blob/master/README.md Closes the MQTT connection, identical to mqtt.Client#end. ```APIDOC ## awsIot.thingShadow#end([force], [callback]) ### Description Invokes the `end()` method on the MQTT connection owned by the `thingShadow` class. This function is identical in function to the `mqtt.Client#end()` method. ### Method ``` awsIot.thingShadow.end([force], [callback]) ``` ### Parameters #### Path Parameters - **force** (boolean) - Optional - If true, forces the disconnection. - **callback** (function) - Optional - Callback function executed upon disconnection. ``` -------------------------------- ### Specify Certificate Directory Source: https://github.com/aws/aws-iot-device-sdk-js/blob/master/README.md Use the --certificate-dir option to specify a directory containing default-named certificate and key files. Default names are certificate.pem.crt, private.pem.key, and root-CA.crt. ```sh -f, --certificate-dir=DIR look in DIR for certificates ``` -------------------------------- ### Create MQTT Device Client (WebSocket/SigV4) Source: https://context7.com/aws/aws-iot-device-sdk-js/llms.txt This snippet configures a device client for WebSocket connections using SigV4 authentication. It requires AWS access key ID, secret access key, and session token, typically obtained from environment variables. ```javascript var awsIot = require('aws-iot-device-sdk'); // --- WebSocket/SigV4 (port 443) --- var deviceWss = awsIot.device({ protocol: 'wss', host: 'abcdefg123.iot.us-east-1.amazonaws.com', clientId: 'my-browser-client', accessKeyId: process.env.AWS_ACCESS_KEY_ID, secretKey: process.env.AWS_SECRET_ACCESS_KEY, sessionToken: process.env.AWS_SESSION_TOKEN, // required for STS/Cognito }); ``` -------------------------------- ### awsIot.thingShadow Source: https://github.com/aws/aws-iot-device-sdk-js/blob/master/README.md Wraps a device instance with functionality to operate on Thing Shadows via the AWS IoT API. Supports all events from mqtt.Client() and provides additional events specific to Thing Shadows. ```APIDOC ## awsIot.thingShadow(deviceOptions, thingShadowOptions) ### Description The `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](#device). thingShadowOptions has the addition of the following arguments specific to the `thingShadow` class. ### Parameters #### Path Parameters - **deviceOptions** (object) - Options for the underlying device instance. - **thingShadowOptions** (object) - Options specific to the thingShadow class. - **operationTimeout** (number) - The timeout for thing operations (default 10 seconds). ### Events #### Event: 'message' `function(topic, message) {}` Emitted when a message is received on a topic not related to any Thing Shadows. - **topic** (string) - Topic of the received packet. - **message** (string) - Payload of the received packet. #### Event: 'status' `function(thingName, stat, clientToken, stateObject) {}` Emitted when an operation `update|get|delete` completes. - **thingName** (string) - Name of the Thing Shadow for which the operation has completed. - **stat** (string) - Status of the operation `accepted|rejected`. - **clientToken** (string) - The operation's clientToken. - **stateObject** (object) - The stateObject returned for the operation. #### Event: 'delta' `function(thingName, stateObject) {}` Emitted when a delta has been received for a registered Thing Shadow. - **thingName** (string) - Name of the Thing Shadow that has received a delta. - **stateObject** (object) - The stateObject returned for the operation. #### Event: 'foreignStateChange' `function(thingName, operation, stateObject) {}` Emitted when a different client's update or delete operation is accepted on the shadow. - **thingName** (string) - Name of the Thing Shadow for which the operation has completed. - **operation** (string) - Operation performed by the foreign client `update|delete`. - **stateObject** (object) - The stateObject returned for the operation. #### Event: 'timeout' `function(thingName, clientToken) {}` Emitted when an operation `update|get|delete` has timed out. - **thingName** (string) - Name of the Thing Shadow that has received a timeout. - **clientToken** (string) - The operation's clientToken. ``` -------------------------------- ### Configure Custom Authentication Connection Source: https://github.com/aws/aws-iot-device-sdk-js/blob/master/README.md For connections using a custom authorization function, set the 'protocol' option to 'wss-custom-auth' when instantiating the device or thingShadow classes. ```javascript new awsIot.device({ protocol: 'wss-custom-auth' }); ``` -------------------------------- ### Include Browser Bundles in HTML Source: https://github.com/aws/aws-iot-device-sdk-js/blob/master/README.md These script tags show how to include the generated AWS IoT SDK browser bundle and your application's bundle in an HTML file. Ensure the paths are correct for your project structure. ```html ``` -------------------------------- ### startJobNotifications Source: https://github.com/aws/aws-iot-device-sdk-js/blob/master/README.md Initiates the process to receive job notifications for a specific thing. This should be called once per thing after subscribing to job operations. ```APIDOC ## startJobNotifications ### Description Starts the delivery of job notifications for a given thing. After this method is called, any queued job executions for the specified thing will be published to the appropriate `subscribeToJobs` handlers. This method only needs to be invoked once per thing. ### Method `jobs.startJobNotifications(thingName, callback)` ### Parameters * `thingName` (string) - The name of the thing for which to start job notifications. * `callback` (function) - A function that will be called with `(err)` arguments. `err` contains error information if an error occurred during the initiation process. ### Example ```javascript jobs.startJobNotifications(thingName, function(err) { if (err) { console.error('Failed to start job notifications:', err); } else { console.log('Job notifications initiated for thing:', thingName); } }); ``` ``` -------------------------------- ### Run jobs-agent.js Source: https://github.com/aws/aws-iot-device-sdk-js/blob/master/README.md Execute the jobs-agent script to manage AWS IoT job executions on a device. Requires certificate files and endpoint information. ```bash node examples/jobs-agent.js -f ~/certs -H .iot..amazonaws.com -T agentThingName ``` -------------------------------- ### Jobs Class Initialization Source: https://github.com/aws/aws-iot-device-sdk-js/blob/master/README.md Initializes the Jobs class with necessary connection parameters. This class inherits all functionality from the base awsIot.device class. ```APIDOC ## Jobs Class ### Description Initializes the Jobs class, which provides functionality for managing AWS IoT jobs. It inherits all methods and events from the base `awsIot.device` class. ### Usage ```javascript var awsIot = require('aws-iot-device-sdk'); var jobs = awsIot.jobs({ keyPath: '', certPath: '', caPath: '', clientId: '', host: '' }); ``` ### Parameters * `keyPath` (string) - Path to the private key file. * `certPath` (string) - Path to the certificate file. * `caPath` (string) - Path to the root CA certificate file. * `clientId` (string) - A unique identifier for the client. * `host` (string) - The custom endpoint for AWS IoT. ``` -------------------------------- ### awsIot.thingShadow#unsubscribe Source: https://github.com/aws/aws-iot-device-sdk-js/blob/master/README.md Unsubscribes from a specified topic, identical to mqtt.Client#unsubscribe but restricted from using Thing Shadow topics. ```APIDOC ## awsIot.thingShadow#unsubscribe(topic, [callback]) ### Description Unsubscribes from a given topic. This method is identical to `mqtt.Client#unsubscribe()` with the restriction that the topic cannot be a Thing Shadow topic. It allows users to unsubscribe from topics on the same connection used for Thing Shadows. ### Method ``` awsIot.thingShadow.unsubscribe(topic, [callback]) ``` ### Parameters #### Path Parameters - **topic** (string) - Required - The topic to unsubscribe from. Cannot be a Thing Shadow topic. - **callback** (function) - Optional - Callback function executed upon unsubscription. ``` -------------------------------- ### Run Temperature Control - Mobile App Mode Source: https://github.com/aws/aws-iot-device-sdk-js/blob/master/README.md Run the temperature-control.js script in 'mobile application' mode. Requires certificate files and an AWS IoT endpoint. ```sh node examples/temperature-control/temperature-control.js -f ~/certs --test-mode=1 -H .iot..amazonaws.com ```