gpt4 book ai didi

node.js - 如何使用 AWS IoT 向/从 Web 浏览器发送/接收消息

转载 作者:IT老高 更新时间:2023-10-28 21:57:38 26 4
gpt4 key购买 nike

我们正在尝试使用亚马逊网络服务物联网 (AWS IoT) 从/向网络浏览器发送消息(例如:。鉴于 AWS IoT 支持 JavaScript,我们预计这是可能 ...

我们在 AWS IoT 文档中进行了搜索,但只找到了服务器端示例(暴露了 AWS secret / key ...)

有没有很好的工作示例或教程,用于使用 AWS IoT 在浏览器中通过 WebSockets/MQTT 发送/接收消息(例如:使用 AWS Cognito 进行身份验证)?谢谢!

最佳答案

这是一个使用 JS 中的 cognito 身份池来连接、发布和响应订阅的示例。

// Configure Cognito identity pool
AWS.config.region = 'us-east-1';
var credentials = new AWS.CognitoIdentityCredentials({
IdentityPoolId: 'us-east-1:your identity pool guid',
});

// Getting AWS creds from Cognito is async, so we need to drive the rest of the mqtt client initialization in a callback
credentials.get(function(err) {
if(err) {
console.log(err);
return;
}
var requestUrl = SigV4Utils.getSignedUrl('wss', 'data.iot.us-east-1.amazonaws.com', '/mqtt',
'iotdevicegateway', 'us-east-1',
credentials.accessKeyId, credentials.secretAccessKey, credentials.sessionToken);
initClient(requestUrl);
});

function init() {
// do setup stuff
}

// Connect the client, subscribe to the drawing topic, and publish a "hey I connected" message
function initClient(requestUrl) {
var clientId = String(Math.random()).replace('.', '');
var client = new Paho.MQTT.Client(requestUrl, clientId);
var connectOptions = {
onSuccess: function () {
console.log('connected');

// subscribe to the drawing
client.subscribe("your/mqtt/topic");

// publish a lifecycle event
message = new Paho.MQTT.Message('{"id":"' + credentials.identityId + '"}');
message.destinationName = 'your/mqtt/topic';
console.log(message);
client.send(message);
},
useSSL: true,
timeout: 3,
mqttVersion: 4,
onFailure: function () {
console.error('connect failed');
}
};
client.connect(connectOptions);

client.onMessageArrived = function (message) {

try {
console.log("msg arrived: " + message.payloadString);
} catch (e) {
console.log("error! " + e);
}

};
}

Documentation for the credentials.get call, here

请记住授权您的 IAM 角色进行订阅/发布。这是一个示例:

{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"iot:Connect"
],
"Resource": "*"
},
{
"Effect": "Allow",
"Action": "iot:Receive",
"Resource": "*"
},
{
"Effect": "Allow",
"Action": "iot:Subscribe",
"Resource": [
"arn:aws:iot:us-east-1::your/mqtt/topic"
]
},
{
"Effect": "Allow",
"Action": "iot:Publish",
"Resource": [
"arn:aws:iot:us-east-1::your/mqtt/topic"
]
}
]
}

关于node.js - 如何使用 AWS IoT 向/从 Web 浏览器发送/接收消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35439742/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com