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

我们正在尝试使用amazon web services物联网(AWS IoT)将消息发送到Web浏览器(例如:。鉴于AWS IoT支持JavaScript,我们期望这是可能的

我们已经在AWS IoT文档中进行了search,但仅查找了服务器端示例 (揭示了AWS秘密/密钥…)

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

下面是一个使用JS中的认知身份池来连接,发布和响应订阅的示例。

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

有关credentials.get调用的文档,请参阅此处

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

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

如果其他人正在寻找解决scheme:下面是一个教程 ,通过简单的聊天应用程序演示如何使用AWS IOT上的无服务器和Websockets实时更新到ReactJS前端。 本教程的源代码在Github上可用。

Interesting Posts