IoT向Web浏览器发送消息

IoT向Web浏览器发送消息

本文介绍了如何使用AWS IoT向Web浏览器发送消息/从Web浏览器接收消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在尝试使用Amazon Web Services物联网(AWS IoT)从Web浏览器发送消息到Web浏览器(例如:)。鉴于AWS IoT支持JavaScript,我们期望 可能 ...



我们在AWS IoT文档中进行了搜索,但仅找到了服务器端示例 (公开AWS秘密/密钥...)



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

解决方案

下面是一个示例,该示例使用JS中的认知身份池来连接,发布和响应订阅。 > //配置Cognito身份池
AWS.config.region ='us-east-1';
var凭证=新的AWS.CognitoIdentityCredentials({
IdentityPoolId: 'us-east-1:您的身份池GUID',
});

//获取来自Cognito的AWS凭证是异步的,因此我们需要在回调
凭证中驱动其余mqtt客户端初始化.get(function(err){
if(err){
console)。 log(err);
的回报;
}
var requestUrl = SigV4Utils.getSignedUrl('wss','data.iot.us-east-1.amazonaws.com','/ mqtt',
'iotdevicegateway',' us-east-1',
凭据.accessKeyId,凭据.secretAccessKey,凭据.sessionToken);
initClient(requestUrl);
});

函数init(){
//做设置东西
}

//连接客户端,订阅绘图主题,然后发布一个嘿,我已连接消息
函数initClient(requestUrl){
var clientId = String(Math.random())。replace('。',));
var client = new Paho.MQTT.Client(requestUrl,clientId);
var connectOptions = {
onSuccess:function(){
console.log(’connected’);

//订阅图形
client.subscribe( your / mqtt / topic);

//发布生命周期事件
message = new Paho.MQTT.Message(’{ id:’+凭据.identityId +’}}));
message.destinationName =‘您的/ mqtt /主题’;
console.log(message);
client.send(message);
},
useSSL:true,
timeout:3,
mqttVersion:4,
onFailure:function(){
console.error('connect失败');
}
};
client.connect(connectOptions);

client.onMessageArrived =函数(消息){

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

};
}



请记住还要授权您的IAM角色进行订阅/发布。以下是示例:

  {
Version: 2012-10-17,
声明:[
{
效果:允许,
操作:[
iot:Connect
],
资源: *
},
{
效果:允许,
操作: iot:Receive,
资源 : *
},
{
Effect:允许,
Action: iot:Subscribe,
Resource:[
arn:aws:iot:us-east-1 :: your / mqtt / topic
]
},
{
Effect:允许,
动作: iot:Publish,
资源:[
arn:aws:iot:us-east-1 :: your / mqtt / topic
]
}
]
}


We are trying to use Amazon Web Services Internet of Things (AWS IoT) to send messages from/to a Web Browser (e.g: . Given that the AWS IoT supports JavaScript we expect that this is possible ...

We have searched at the AWS IoT Documentation but only found server-side examples (which expose AWS secrets/keys...)

Are there any good working examples or tutorials for using AWS IoT to send/receive messages via WebSockets/MQTT in the browser (e.g: authenticating with AWS Cognito)? Thanks!

解决方案

Here's a sample that uses a cognito identity pool in JS to connect, publish and react to a subscription.

// 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

Remember to authorize your IAM role for subscribing / publishing as well. Here's a sample:

{
    "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"
            ]
        }
    ]
}

这篇关于如何使用AWS IoT向Web浏览器发送消息/从Web浏览器接收消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 22:30