Jac*_*sle 32 amazon-web-services websocket node.js amazon-cognito aws-iot
我们正在尝试使用Amazon Web Services物联网(AWS IoT)从Web浏览器发送消息(例如:.鉴于AWS IoT支持JavaScript,我们希望这是可能的 ......
我们在AWS IoT文档中进行了搜索,但只查找了服务器端示例 (公开AWS秘密/密钥......)
是否有任何良好的工作示例或教程可以使用AWS IoT在浏览器中通过WebSockets/MQTT发送/接收消息(例如:使用AWS Cognito进行身份验证)?谢谢!
Kyl*_*che 25
这是一个使用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);
}
};
}
Run Code Online (Sandbox Code Playgroud)
请记住授权您的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"
]
}
]
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10577 次 |
| 最近记录: |