是否有任何javascript sdk或库可用于从浏览器端连接到Azure IoT或事件中心?
我希望避免在连接到事件中心时将消息从Web应用程序重定向到浏览器所涉及的延迟,而是直接从浏览器实现。
This question讨论了使用AMQP over Websockets连接到IoT / Event中心但链接断开的方法。一般而言,可用于在浏览器上可靠实时监控数据的选项或方法有哪些?
答案 0 :(得分:2)
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);
})
如何获取设备ID和设备密钥: