KDR
KDR

Reputation: 488

Connect to Azure IoT/Event hub from browser side

Is there any javascript sdk or library available to connect to Azure IoT or Event hub from Browser side?

I would like to avoid the latency involved in the redirection of the messages from Web application to browser in connecting to the Event hub and instead achieve it directly from browser.

This question discusses an approach using AMQP over Websockets to connect to the IoT/Event hub but the links are broken. In general, What are the options or approaches available for reliable real-time monitoring of data on the browser?

Upvotes: 4

Views: 2002

Answers (1)

唐雯倩
唐雯倩

Reputation: 71

npm install mqtt crypto-js --save

index.js

import mqtt from 'mqtt';
import CryptoJS from 'crypto-js';

var host='{iothubname}.azure-devices.net';
var deviceId = '{DeviceId}';
var sharedKey = '{DeviceKey}';
var topic ='devices/'+deviceId+'/messages/devicebound/#';

function encodeUriComponentStrict (str) {
    return encodeURIComponent(str).replace(/[!'()*]/g, function (c) {
        return '%' + c.charCodeAt(0).toString(16);
    });
}
function getSaSToken (hostName,deviceId,sharedKey){
    var sr = encodeUriComponentStrict(hostName + '/devices/' + deviceId);
    var se = Math.round(new Date().getTime() / 1000) + 24 * 3600;
    var StringToSign = sr + '\n' + se;
    var sig = encodeUriComponentStrict(CryptoJS.HmacSHA256(StringToSign, CryptoJS.enc.Base64.parse(sharedKey)).toString(CryptoJS.enc.Base64));
    return 'SharedAccessSignature sr=' + sr + '&sig=' + sig + '&se=' + se;
}

var client  = mqtt.connect({
            host:host,
            port:443,
            path:'/$iothub/websocket?iothub-no-client-cert=true',
            protocol: 'mqtts',
            protocolId: 'MQTT',
            protocolVersion: 4,
            clientId:deviceId,
            username: host+'/'+deviceId+'/api-version=2016-11-14',
            password: getSaSToken(host,deviceId,sharedKey),
            keepalive: 30000
})

client.on('connect',function(packet){
    console.log('mqtt connected!',packet);
    client.subscribe(topic);
})
client.on('reconnect',function(){
    console.log('mqtt reconnected!');
})
client.on('close',function(c){
    console.log('mqtt closed!',c);
})
client.on('message',function(topic, message, packet){
    var string = new TextDecoder("utf-8").decode(message);
    console.log('receive!',string);
})

How to get device id and device key:

  1. Login azure
  2. All resources and find your iot hub
  3. Device Explorer
  4. Click the device which you want to connect or create one

enter image description here

Send a test message:

  1. Click "Send Message" enter image description here

  2. Type something and send enter image description here

  3. You will see "receive! this is a test!" on your browser console

Upvotes: 1

Related Questions