使用Javascript Azure Functions 处理IoT Hub消息并解析出Device ID

 

 创建Azure Functions 的过程可参照:Azure IoT Hub入门系列 (11)- 10分钟实现Azure Function 通过IoT Hub Trigger处理设备到云的消息(Java) - 51Azure.cloud

 

index.js 代码参考如下:

module.exports = function (context, IoTHubMessages) {
    context.log(`JavaScript eventhub trigger function called for message array: ${IoTHubMessages}`);
    
    for (var x = 0; x < IoTHubMessages.length; x++) {
        // the message payload is the temperature
        var temp = Number(IoTHubMessages[x]);

            context.log(`Processed message: ${IoTHubMessages[x].humidity}`);
            context.log(`DeviceId : ${context.bindingData.systemPropertiesArray[x]["iothub-connection-device-id"]}`);
           
       
    }

    context.done();
};

 

local.settings.json  如下:

{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "DefaultEndpointsProtocol=https;AccountName=funcnode;AccountKey=xasahngKueQgA+WWFVsPuUkfyzZwK9b2l3xjUjMkF7dR9ZrKC5MyJ+aZoQRTfQtHe/gRRtAoMILCRgnFyq4e9g==;EndpointSuffix=core.windows.net",
    "FUNCTIONS_WORKER_RUNTIME": "node",
    "My_IoT_Hub":"Endpoint=sb://.xxxxx.servicebus.windows.net/;SharedAccessKeyName=iothubowner;SharedAccessKey=xxx;EntityPath=xxx-iot"

  }
}

 

Function.json 如下:

{
  "bindings": [
    {
      "type": "eventHubTrigger",
      "name": "IoTHubMessages",
      "direction": "in",
      "eventHubName": "samples-workitems",
      "connection": "My_IoT_Hub",
      "cardinality": "many",
      "consumerGroup": "$Default"
    }
  ]
}

 

 

需要匹配的地方有:

Functions.json中最后一行 connection 属性指定了 IoT Hub的连接字符串的【变量名】

Local.settings.json中最后一行增加了IoT Hub的连接字符串的  【变量名】及其值,其值为IoT Hub 内置终结点

 

在循环中通过    context.log(`DeviceId : ${context.bindingData.systemPropertiesArray[x]["iothub-connection-device-id"]}`) 取出设备Device ID来。

 

 

视频讲解: