1

How do I generate an Azure IoT Hub connection string from deviceInfo, which is a JSON object of device information after I create a new device using the IoT Hub Service NodeJS API.

This is my code snippet below. Inside the callback, where the comment is, I'm trying to get a device connection string to resolve, rather than all the device information.

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);
    });
  });
}

I reviewed the documentation on Microsoft's website, but the only documentation specifically for connection strings is this. Here is the device information object definitions. I know I could parse it myself, but I also couldn't find a specific definition in the documentation on what a connection string consists of. From my experience, I know it's a host name, a device id, and a symmetric key - though I was hoping for an azure function to generate it to isolate myself from issues down the road if the connection string generation changes.

azure-iothub from npm

Any assistance would be appreciated.

technogeek1995
  • 3,185
  • 2
  • 31
  • 52

3 Answers3

3

There is a function in azure-iot-device npm (IoT Hub Device SDK for Node.js) to generate device connection string:

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

You could also refer to full code here to see how Azure IoT Toolkit generates the device connection string.

Jun Han
  • 13,821
  • 7
  • 26
  • 31
0

This is the function that I came up with. However, I would like to use a function from the Azure IoT Hub package, if possible.

function generateConnectionString(deviceInfo, hub){
  return `HostName=${hub}.azure-devices.net;DeviceId=${deviceInfo.deviceId};SharedAccessKey=${deviceInfo.authentication.symmetricKey.primaryKey}`;
}
technogeek1995
  • 3,185
  • 2
  • 31
  • 52
0

As far as i know, there is no function in the package to generate the connection string for device. But i can find a method to format the connection string in util.

   import * as util from 'util';
   var connectionString = util.format('HostName=xxx-lab.azure-devices.net;DeviceId=%s;SharedAccessKey=%s', deviceId, deviceKey);
Michael Xu
  • 4,382
  • 1
  • 8
  • 16
  • Thank you for your response. Glad to know that I wasn't the only one able to find a function to generate a connection string. – technogeek1995 Aug 23 '18 at 14:05