从浏览器端连接到Azure IoT/事件中心

从浏览器端连接到Azure IoT/事件中心,azure,websocket,apache-kafka,azure-eventhub,azure-iot-hub,Azure,Websocket,Apache Kafka,Azure Eventhub,Azure Iot Hub,是否有任何javascript sdk或库可用于从浏览器端连接到Azure IoT或事件中心 我希望在连接到事件中心时避免将消息从Web应用程序重定向到浏览器所涉及的延迟,而是直接从浏览器实现 讨论了一种通过WebSocket使用AMQP连接到物联网/事件中心但链接断开的方法。一般来说,有哪些选项或方法可用于对浏览器上的数据进行可靠的实时监控 npm install mqtt crypto-js --save index.js import mqtt from 'mqtt'; import C

是否有任何javascript sdk或库可用于从浏览器端连接到Azure IoT或事件中心

我希望在连接到事件中心时避免将消息从Web应用程序重定向到浏览器所涉及的延迟,而是直接从浏览器实现

讨论了一种通过WebSocket使用AMQP连接到物联网/事件中心但链接断开的方法。一般来说,有哪些选项或方法可用于对浏览器上的数据进行可靠的实时监控

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和设备密钥:

  • 登录azure
  • 所有资源并找到您的物联网中心
  • 设备浏览器
  • 单击要连接或创建的设备
  • 发送测试消息:

  • 单击“发送消息”

  • 键入一些东西并发送

  • 您将在浏览器控制台上看到“接收!这是一个测试!”


  • 您存储机密(事件中心SAS/密钥)的计划是什么?此代码不是针对物联网中心(而不是物联网中心)的吗?它还需要在本地安装带有npm的软件,我猜使用该页面的人不会这么做。