从浏览器端连接到azure iot/事件中心

2o7dmzc5  于 2021-06-07  发布在  Kafka
关注(0)|答案(1)|浏览(442)

是否有任何javascript sdk或库可用于从浏览器端连接到azure iot或event hub?
我想避免在连接到事件中心时将消息从web应用程序重定向到浏览器所涉及的延迟,而是直接从浏览器实现。
这个问题讨论了一种使用websockets上的amqp连接到iot/事件中心的方法,但是链接断开了。一般来说,有哪些选项或方法可用于可靠地实时监视浏览器上的数据?

kd3sttzy

kd3sttzy1#

npm install mqtt crypto-js --save

索引.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
所有资源,找到你的物联网中心
设备资源管理器
单击要连接或创建的设备

发送测试消息:
点击“发送消息”

键入内容并发送

您将看到“接收!这是个考验!”在浏览器控制台上

相关问题