Reputation: 488
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
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:
Send a test message:
You will see "receive! this is a test!" on your browser console
Upvotes: 1