您可以使用 Azure 函数(预览版) 输出 ASA 作业,以便通过 Azure IoT Hub 面向服务的端点发送云到设备消息。
下面是这个函数的一个例子。
运行.csx:
#r "Newtonsoft.Json"
using System.Configuration;
using System.Text;
using System.Net;
using Microsoft.Azure.Devices;
using Newtonsoft.Json;
// create proxy
static Microsoft.Azure.Devices.ServiceClient client = ServiceClient.CreateFromConnectionString(ConfigurationManager.AppSettings["myIoTHub"]);
public static async Task<HttpResponseMessage> Run(string input, HttpRequestMessage req, TraceWriter log)
{
log.Info($"ASA Job: {input}");
var data = JsonConvert.DeserializeAnonymousType(input, new[] { new { xyz = "", IoTHub = new { ConnectionDeviceId = ""}}});
if(!string.IsNullOrEmpty(data[0]?.IoTHub?.ConnectionDeviceId))
{
string deviceId = data[0].IoTHub.ConnectionDeviceId;
log.Info($"Device: {deviceId}");
// cloud-to-device message
var msg = JsonConvert.SerializeObject(new { temp = 20.5 });
var c2dmsg = new Microsoft.Azure.Devices.Message(Encoding.ASCII.GetBytes(msg));
// send AMQP message
await client.SendAsync(deviceId, c2dmsg);
}
return req.CreateResponse(HttpStatusCode.NoContent);
}
function.json:
{
"bindings": [
{
"authLevel": "function",
"name": "input",
"type": "httpTrigger",
"direction": "in"
},
{
"name": "$return",
"type": "http",
"direction": "out"
}
],
"disabled": false
}
project.json:
{
"frameworks": {
"net46":{
"dependencies": {
"Microsoft.Azure.Devices": "1.3.2"
}
}
}
}
附录 A
出于测试目的,请执行以下步骤:
- 在您的 Azure Function App 中为您添加设置 myIoTHub
Azure IoT 中心的连接字符串。
- 创建 HttpTrigger 函数,将其命名为 HttpASA_1
- 用上述内容更新run.csx、function.json和project.json文件
- 对测试请求正文使用以下示例:
[
{
"时间": "2017-11-26T12:52:23.4292501Z",
“计数器”:57,
“风速”:8.7358,
“温度”:16.63,
“湿度”:79.42,
"EventProcessedUtcTime": "2017-11-26T12:52:21.3568252Z",
“分区 ID”:2,
"EventEnqueuedUtcTime": "2017-11-26T12:52:22.435Z",
“物联网中心”:{
“消息 ID”:空,
“CorrelationId”:空,
"ConnectionDeviceId": "Device1",
"ConnectionDeviceGenerationId": "636189812948967054",
"入队时间": "2017-11-26T12:52:21.562Z",
“流标识”:空
}
}
]
为您的实际 deviceId 更改值 Device1。
- 现在,AF 已准备好对其进行测试。按 Run 按钮运行示例并查看日志进度。
- 您应该会在您的设备上看到 AF 发送的 C2D 消息,或者您可以下载一个小测试器 Azure IoT Hub Tester 来模拟您的 MQTT 设备。以下屏幕 sn-p 显示了此测试器:
- 现在,在此步骤中,我们可以转到 ASA 作业以调用此 HttpASA_1 函数。请注意,ASA 作业仅调用 HttpTrigger 函数。以下屏幕 sn-p 显示为我们的 Azure 函数添加输出:
当您在导入选项组合框中选择订阅时,您应该会在组合框中看到此功能。完成后,按保存按钮并观看屏幕上的通知消息。 ASA 将向您的 AF 发送验证消息,其响应状态应为 20x 代码。
- 最后,您可以转到 Query 为您的 AF 生成输出。以下屏幕显示了所有遥测数据到 AF 的简单输出:
注意,inpsim 是我的 iothub 输入。
ASA 以以下格式输出 HttpTrigger 函数的有效负载,请参见我的示例:
[
{
"time": "2017-11-26T12:52:23.4292501Z",
"counter": 57,
"windSpeed": 8.7358,
"temperature": 16.63,
"humidity": 79.42,
"EventProcessedUtcTime": "2017-11-26T12:52:21.3568252Z",
"PartitionId": 2,
"EventEnqueuedUtcTime": "2017-11-26T12:52:22.435Z",
"IoTHub": {
"MessageId": null,
"CorrelationId": null,
"ConnectionDeviceId": "Device1",
"ConnectionDeviceGenerationId": "636189812948967054",
"EnqueuedTime": "2017-11-26T12:52:21.562Z",
"StreamId": null
}
}
]
请注意,我的遥测数据 (*) 是 counter、温度、湿度和时间戳时间,因此其他属性由 ASA 作业隐式创建。根据查询,您可以为 C2D 消息创建任何业务属性。