25

Stiamo tentando di utilizzare l'Internet of Things (AWS IoT) di Amazon Web Services per inviare messaggi da/a un browser Web (ad esempio:. IoT supporta JavaScript ci aspettiamo che questo è possibile ...Come utilizzare AWS IoT per inviare/ricevere messaggi a/da browser Web

abbiamo cercato alla documentazione AWS IoT ma trova solo esempi lato server(che espongono AWS secrets/chiavi ...)

C'è del buono che funziona con gli esempi o tutorial per l'utilizzo di AWS IoT per inviare/ricevere messaggi tramite WebSockets/MQTT nel browser (ad esempio, l'autenticazione con AWS Cognito)? Grazie!

risposta

19

Ecco un esempio che utilizza un pool di identità cognitive in JS per connettersi, pubblicare e reagire a un abbonamento.

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

Ricordarsi di autorizzare il ruolo IAM per la sottoscrizione/pubblicazione pure. Ecco un esempio:

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

la funzione sigv4 è [qui] (http://draw.kyleroche.com/sigv4utils.js) come riferimento. –

+0

viene visualizzato il seguente errore: aws-sdk-2.7.1.js: 6834 Errore non rilevato: momento non definito (...) callListeners @ aws-sdk-2.7.1.js: 6834emit @ aws-sdk-2.7.1 .js: 6810emit @ aws-sdk-2.7.1.js: 4054transition @ aws-sdk-2.7.1.js: 3831runTo @ aws-sdk -..... Come ho aggiornato anche lo sdk di aws, ma ottenendo ancora lo stesso errore potresti aiutarmi o se possibile condividere il file aws-sdk.js che stai usando. –

+0

hai usato "iotdevicegateway", cosa stai passando come parametro "iotdevicegateway"? O dobbiamo passare resourceId o DeviceId? –

1

Nel caso in cui nessun altro è alla ricerca di una soluzione: here's a tutorial che dimostra attraverso una semplice applicazione per chat come ottenere aggiornamenti in tempo reale in un front-end ReactJS utilizzando Serverless e WebSockets su AWS IOT. Il codice sorgente del tutorial è disponibile on Github.

+1

Questo esempio non include il supporto Cognito. Non è chiaro: nell'esempio vengono mostrate le chiavi nella sorgente javascript? –