AWS IoT Device SDK for JavaScript

repository·master·Indexed 21 days ago

https://github.com/aws/aws-iot-device-sdk-js

AWS IoT Node.js SDK for Embedded Devices providing connectivity to the AWS IoT Platform via MQTT or MQTT over Secure WebSockets. It includes core abstractions for secure device connections (device class), state synchronization via Thing Shadows (thingShadow class), and fleet-wide task management through the AWS IoT Jobs service (jobs class). Supports Node.js version 8.17 or above.

Tokens
13.4K
Snippets
42
Records
51
Agent score
75%

What's inside aws-iot-device-sdk-js

  1. Manage Thing Shadows with the thingShadow class

    master

    The thingShadow class wraps a device instance to provide high-level API access to AWS IoT Thing Shadows.

    Lifecycle and Operations:

    1. Register: You must call register(thingName, [options], [callback]) before performing operations. This subscribes the client to the necessary shadow topics.
      • options.ignoreDeltas: If true, ignores the delta sub-topic.
      • options.persistentSubscribe: If false, the client unsubscribes from operation sub-topics when not performing an operation (improves traffic but slows down operations).
      • options.discardStale: If false, allows receiving messages with old version numbers.
      • options.enableVersioning: If true, sends version numbers with updates to prevent overwriting concurrent changes.
    2. Perform Operations: Use update(), get(), or delete(). These return a clientToken (string or number) used to track the operation via 'status' or 'timeout' events.
    3. Unregister: Call unregister(thingName) to stop receiving events and unsubscribe from shadow topics.

    Core Events:

    • 'status': Emitted when update|get|delete completes. Returns (thingName, stat, clientToken, stateObject). stat is either 'accepted' or 'rejected'.
    • 'delta': Emitted when a delta is received for a registered shadow. Returns (thingName, stateObject).
    • 'foreignStateChange': Emitted when a different client performs an update or delete on the shadow. Returns (thingName, operation, stateObject).
    • 'timeout': Emitted when an operation times out. Returns (thingName, clientToken).
    • 'message': Emitted for non-shadow MQTT messages. Returns (topic, message).
    const shadow = awsIot.thingShadow(device, { operationTimeout: 10000 });
    
    shadow.register('myThing', { ignoreDeltas: false }, (err) => {
      if (!err) {
        const token = shadow.update('myThing', { state: { temperature: 25 } });
        console.log('Update operation token:', token);
      }
    });
    
    shadow.on('status', (thingName, stat, clientToken, stateObject) => {
      console.log(`Operation ${clientToken} for ${thingName} was ${stat}`);
    });
  2. Understand the core SDK abstractions: device, thingShadow, and jobs

    master

    The SDK is built on top of mqtt.js and provides three primary classes to interact with the AWS IoT Platform:

    1. device: A wrapper around mqtt.js that provides a secure connection to AWS IoT via MQTT or MQTT over Secure WebSockets. It handles intermittent connections with progressive backoff retries, automatic re-subscription, and queued offline publishing.
    2. thingShadow: Implements functionality to access Thing Shadows. It allows devices to update, be notified of changes to, get the current state of, or delete Thing Shadows to synchronize state between devices and the cloud.
    3. jobs: Implements functionality to interact with the AWS IoT Jobs service, used for managing fleet-wide tasks like firmware updates, certificate rotations, and device reboots.
  3. Configure AWS IoT connection types

    master

    The SDK supports three connection modes. By default, the SDK uses MQTT over TLS with mutual certificate authentication on port 8883. To use other modes, set the protocol option when instantiating awsIot.device() or awsIot.thingShadow().

    Connection Typeprotocol valueAuthentication Method
    MQTT over TLS(default)Mutual certificate authentication (Port 8883)
    MQTT over WebSocket/TLSwssSigV4 authentication (Port 443)
    MQTT over WebSocket/TLS (Custom)wss-custom-authCustom authorization function
  4. Use SDK with webpack

    master

    To use the SDK with webpack, you must create a webpack package with an entry.js file and a webpack.config.js.

    An example implementation is provided in ./examples/browser/mqtt-webpack. To run it:

    cd ./examples/browser/mqtt-webpack
    npm install
    ./node_modules/.bin/webpack --config webpack.config.js

    The resulting bundle.js is then loaded by index.html.

  5. Setup the Temperature Monitor browser example

    master

    The Temperature Monitor browser application allows you to monitor a simulated temperature control device.

    Prerequisites:

    1. Install the Temperature Control Example Application.
    2. Configure an Amazon Cognito Identity Pool in the AWS Console.
      • Allow unauthenticated identities to connect.
      • Ensure the unauthenticated IAM role has permissions for required AWS IoT APIs.
      • Obtain the PoolID.

    Steps:

    1. Edit examples/browser/temperature-monitor/aws-configuration.js and replace poolId and region with your Cognito values.
    2. Create the bundle:
      npm run-script browserize examples/browser/temperature-monitor/index.js
    3. Start the device simulation (in a separate terminal):
      node examples/temperature-control/temperature-control.js -f ~/certs --test-mode=2 -H <PREFIX>.iot.<REGION>.amazonaws.com
    4. Open examples/browser/temperature-monitor/index.html in your browser.
    npm run-script browserize examples/browser/temperature-monitor/index.js
  6. Setup the MQTT Explorer browser example

    master

    An interactive MQTT client for subscribing to and publishing messages.

    Steps:

    1. Configure a Cognito Identity Pool (allow unauthenticated access) and obtain the PoolID.
    2. Edit examples/browser/mqtt-explorer/aws-configuration.js with your poolId and region.
    3. Create the bundle:
      npm run-script browserize examples/browser/mqtt-explorer/index.js
    4. Open examples/browser/mqtt-explorer/index.html in your browser.

    To monitor all traffic allowed by your policy, subscribe to the # wildcard.

    npm run-script browserize examples/browser/mqtt-explorer/index.js
  7. Configure Certificate authentication

    master

    For non-WebSocket connections (using mqtts), you must provide client certificates and private keys. You can specify them in two ways:

    1. Using a Certificate Directory

    Use the -f or --certificate-dir flag to point to a directory. The SDK will look for files with these exact names:

    • certificate.pem.crt: Your AWS IoT certificate
    • private.pem.key: Your private key
    • root-CA.crt: The root CA certificate

    2. Specifying Individual Files

    Use specific flags for each file:

    • -k, --private-key=FILE: Path to the private key
    • -c, --client-certificate=FILE: Path to the client certificate
    • -a, --ca-certificate=FILE: Path to the CA certificate

    Tip: You can combine -f with individual file flags to avoid using absolute paths in your configuration.

    # Example using a directory
    node examples/device-example.js -f ~/certs --test-mode=1 -H <PREFIX>.iot.<REGION>.amazonaws.com
    
    # Example using individual files
    node examples/device-example.js -k ./key.pem -c ./cert.pem -a ./root.pem
  8. Implement AWS IoT Jobs operations with jobs-agent.js

    master

    The jobs-agent.js is an example agent that handles standard device management operations via AWS IoT Jobs. It responds to specific JSON job documents.

    Supported Operations

    systemStatus

    Responds with system status information. Document: {"operation": "systemStatus"}

    reboot

    Attempts to reboot the device. Status is marked IN_PROGRESS until the agent restarts, then updated to SUCCESS. Document: {"operation": "reboot"}

    shutdown

    Attempts to shutdown the device. Document: {"operation": "shutdown"}

    install

    Installs files specified in the document. Requires a unique packageName. Document:

    {
      "operation": "install",
      "packageName": "uniquePackageName",
      "workingDirectory": "../path",
      "launchCommand": "node app.js",
      "autoStart": "true",
      "files": [
        {
          "fileName": "app.js",
          "fileSource": { "url": "https://s3..." },
          "checksum": { "inline": { "value": "..." }, "hashAlgorithm": "SHA256" }
        }
      ]
    }

    start, stop, restart

    Manages the execution of a previously installed package. Document (start): {"operation": "start", "packageName": "somePackageName"}

    node examples/jobs-agent.js -f ~/certs -H <PREFIX>.iot.<REGION>.amazonaws.com -T agentThingName
  9. Configure Custom Authorization for WebSocket connections

    master

    To use a custom authorizer (registered via Lambda in AWS IoT), set the protocol to wss-custom-auth and provide credentials using one of two methods:

    1. Headers: Set the customAuthHeaders option to an object containing your header names and values.
    2. Query String: Set the customAuthQueryString option to a string containing key-value pairs.

    Note: The custom authorizer must be previously set up in Lambda and registered with AWS IoT.

    // Using customAuthHeaders
    const device = awsIot.device({
        protocol: 'wss-custom-auth',
        customAuthHeaders: {
            'X-Amz-CustomAuthorizer-Name': 'TestAuthorizer',
            'X-Amz-CustomAuthorizer-Signature': 'signature',
            'TestAuthorizerToken': 'token'
        }
    });
    
    // Using customAuthQueryString
    const device = awsIot.device({
        protocol: 'wss-custom-auth',
        customAuthQueryString: '?X-Amz-CustomAuthorizer-Name=TestAuthorizer&X-Amz-CustomAuthorizer-Signature=signature&TestAuthorizerToken=token'
    });
  10. Install the AWS IoT Device SDK for JavaScript

    master

    The SDK requires Node.js version 8.17 or above. You can install it via npm or by cloning the repository directly from GitHub.

    To check your current Node version, use:

    node -v
    # Installing with npm
    npm install aws-iot-device-sdk
    
    # Installing from github
    git clone https://github.com/aws/aws-iot-device-sdk-js.git
    cd aws-iot-device-sdk-js
    npm install
  11. Configure WebSocket/TLS connections

    master

    To use a WebSocket/TLS connection instead of the default mqtts protocol, add the --protocol=wss flag to your command line. When using WebSockets, you must provide credentials using one of the following methods:

    1. System Environment Variables

    Export your AWS IAM credentials to the environment:

    export AWS_ACCESS_KEY_ID=[a valid AWS access key ID]
    export AWS_SECRET_ACCESS_KEY=[a valid AWS secret access key]

    2. Shared Credential File

    Load credentials from the default AWS shared credential file located at:

    • Linux: ~/.aws/credentials
    • Windows: %UserProfile%\.aws\credentials

    You can also specify a custom path or profile via the awsIot.device(options) configuration in your code.

    # Example command using WebSockets
    node examples/thing-example.js -P=wss --test-mode=1 -H <PREFIX>.iot.<REGION>.amazonaws.com
  12. Create application bundles with browserify

    master

    You can use the SDK's utility scripts to browserify your own application code and link it to the combined AWS SDK browser bundle.

    To bundle a specific application (e.g., examples/browser/temperature-monitor/index.js), run:

    npm run-script browserize <path-to-your-index.js>

    This command performs two actions:

    1. Creates an application bundle at <path-to-your-dir>/bundle.js.
    2. Copies browser/aws-iot-sdk-browser-bundle.js into your application's directory.

    In your HTML file, load the scripts in this order:

    <script src="aws-iot-sdk-browser-bundle.js"></script>
    <script src="bundle.js"></script>
    npm run-script browserize examples/browser/temperature-monitor/index.js