【问题标题】:Generate Connection String For Azure IoT Hub From Device JSON After Creation创建后从设备 JSON 为 Azure IoT 中心生成连接字符串
【发布时间】:2018-08-22 13:17:27
【问题描述】:

如何从deviceInfo 生成 Azure IoT Hub 连接字符串,这是使用 IoT Hub 服务 NodeJS API 创建新设备后的设备信息 JSON 对象。

这是我下面的代码 sn-p。在回调中,即注释所在的位置,我试图获取要解析的设备连接字符串,而不是所有设备信息。

import iothub from 'azure-iothub';
const myIoTHub = iothub.Registry.fromConnectionString(...);

function createDevice(device) {
  return new Promise((resolve, reject) => {
    myIoTHub.create(device, function (err, deviceInfo, res) {
      if (err) reject(err);
      // deviceInfo ---> connectionString
      resolve(connectionString);
    });
  });
}

我查看了 Microsoft 网站上的文档,但唯一专门针对连接字符串的文档是 this。这是device information 对象定义。我知道我可以自己解析它,但我也无法在文档中找到关于连接字符串包含什么的具体定义。根据我的经验,我知道它是一个主机名、一个设备 ID 和一个对称密钥——尽管我希望有一个 azure 函数来生成它,以便在连接字符串生成发生变化时将自己与未来的问题隔离开来。

azure-iothub from npm

任何帮助将不胜感激。

【问题讨论】:

    标签: node.js azure es6-promise azure-iot-hub azure-iot-hub-device-management


    【解决方案1】:

    azure-iot-devicenpm(IoT Hub Device SDK for Node.js)中有一个函数可以生成设备连接字符串:

    import { ConnectionString as DeviceConnectionString } from "azure-iot-device";
    const deviceConnectionString = DeviceConnectionString.createWithSharedAccessKey(hostName, device.deviceId, device.authentication.SymmetricKey.primaryKey);
    

    您也可以参考完整代码here 了解Azure IoT Toolkit 是如何生成设备连接字符串的。

    【讨论】:

      【解决方案2】:

      这是我想出的功能。不过,如果可能的话,我想使用 Azure IoT Hub 包中的一个函数。

      function generateConnectionString(deviceInfo, hub){
        return `HostName=${hub}.azure-devices.net;DeviceId=${deviceInfo.deviceId};SharedAccessKey=${deviceInfo.authentication.symmetricKey.primaryKey}`;
      }
      

      【讨论】:

        【解决方案3】:

        据我所知,包中没有生成设备连接字符串的功能。但我可以在 util 中找到一种格式化连接字符串的方法。

           import * as util from 'util';
           var connectionString = util.format('HostName=xxx-lab.azure-devices.net;DeviceId=%s;SharedAccessKey=%s', deviceId, deviceKey);
        

        【讨论】:

        • 感谢您的回复。很高兴知道我不是唯一一个能够找到生成连接字符串的函数的人。
        猜你喜欢
        • 2018-11-11
        • 2023-03-17
        • 1970-01-01
        • 2023-01-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多