从浏览器端连接到Azure IoT / Event集线器

时间:2018-03-07 05:05:35

标签: azure websocket apache-kafka azure-eventhub azure-iot-hub

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

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

This question讨论了使用AMQP over Websockets连接到IoT / Event中心但链接断开的方法。一般而言,可用于在浏览器上可靠实时监控数据的选项或方法有哪些?

1 个答案:

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

  1. 登录azure
  2. 所有资源并找到您的iot hub
  3. 设备资源管理器
  4. 单击要连接的设备或创建一个
  5. enter image description here

    发送测试信息:

    1. 点击&#34;发送消息&#34; enter image description here

    2. 输入内容并发送 enter image description here

    3. 你会看到&#34;收到!这是一个考验!&#34;在浏览器控制台上