node.js - 有关如何在 Raspberry Pi 上接收 AWS IOT 主题的简单示例

标签 node.js amazon-web-services mqtt aws-iot

我正在寻找一个关于如何从主题接收消息的简单 JavaScript 示例。我正在尝试使用 CodeBuild、Lambda、SNS,最后是 IoT 创建一个 Build Cop。我已成功向该主题发布消息,但我无法弄清楚如何接收该消息。

SDK 中的示例没有详细记录(至少对我来说),我无法弄清楚要使用哪个导入或为什么,以及如何订阅一个简单的主题。

向事物发送消息的代码如下。我从 Lambda 发送它。该代码是用 TypeScript 编写的,但我将转换后的 JavaScript 复制并粘贴到控制台中,因为它似乎本身不支持 TypeScript。

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);
  }
});

最佳答案

我不确定这是否是您的意思,但这里有一个有关如何使用 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());
  });

您可以在此处查看更多示例:https://github.com/aws/aws-iot-device-sdk-js#jobs

关于node.js - 有关如何在 Raspberry Pi 上接收 AWS IOT 主题的简单示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47764936/

相关文章:

apache - MQTT over websocket over Apache SSL

javascript - 如何通过 NodeJS 和 Mocha 执行具有不同结构的不同测试用例

node.js - fork : Cannot allocate memory - Ubuntu NGINX running NodeJS with PM2

amazon-web-services - AWS Redshift 查询计划警告

amazon-web-services - 使用 boto3 检查终止 AWS EC2 实例是否成功的正确方法是什么?

authentication - 如何使用redis作为mosquitto ACL的后端

javascript - 错误: Can't set headers after they are sent for HTTP node server

javascript - 如何仅在从restcall Node js获得响应后调用函数

amazon-web-services - 如何将Cognito身份池与API网关集成?

azure - IotHubClientTransientException : Transient error occured, 请重试