Jeffrey Getzin
Jeffrey Getzin

Reputation: 561

Simple example on how to receive an AWS IOT topic on a Raspberry Pi

I'm looking for a simple JavaScript example of how to receive messages from a topic. I'm trying to create a Build Cop using CodeBuild, Lambda, SNS, and finally, IoT. I've successfully published messages to the topic, but I can't for the life of me figure out what to do to receive the message.

The examples in the SDK are not well-documented (to me at least) and I can't figure out which import to use or why, and how to subscribe to a simple topic.

The code to send the message to the thing is the following. I'm sending it from a Lambda. The code is written in TypeScript, but I'm copying and pasting the transpiled JavaScript into the console since it does not seem to support TypeScript natively.

const params = {
  topic: 'topic/buildcop',
  payload: color,
  qos: 1
};


this.iotdata.publish(params, function(err, data){
  if(err){
    console.log(`error: ${err}`);
  }
  else{
    console.log("success?");
    //context.succeed(event);
  }
});

Upvotes: 2

Views: 4863

Answers (1)

Deividi Silva
Deividi Silva

Reputation: 846

I'm not sure if this is what you meant, but here is an example on how to subscribe to a topic using the javascript sdk:

var awsIot = require('aws-iot-device-sdk');

//
// Replace the values of '<YourUniqueClientIdentifier>' and '<YourCustomEndpoint>'
// with a unique client identifier and custom host endpoint provided in AWS IoT.
// NOTE: client identifiers must be unique within your AWS account; if a client attempts 
// to connect with a client identifier which is already in use, the existing 
// connection will be terminated.
//
var device = awsIot.device({
   keyPath: <YourPrivateKeyPath>,
  certPath: <YourCertificatePath>,
    caPath: <YourRootCACertificatePath>,
  clientId: <YourUniqueClientIdentifier>,
      host: <YourCustomEndpoint>
});

//
// Device is an instance returned by mqtt.Client(), see mqtt.js for full
// documentation.
//
device
  .on('connect', function() {
    console.log('connect');
    device.subscribe('topic_1');
    device.publish('topic_2', JSON.stringify({ test_data: 1}));
  });

device
  .on('message', function(topic, payload) {
    console.log('message', topic, payload.toString());
  });

You can see more examples at here: https://github.com/aws/aws-iot-device-sdk-js#jobs

Upvotes: 4

Related Questions