c# - 从 HttpTrigger 函数读取 Azure IoT Hub 遥测
问题描述
用例
我有一个将遥测数据发送到 IoT 中心的 IoT 中心设备。我想使用函数处理遥测,例如存储到数据库。
功能
我在 VS2019 中创建了以下函数并发布到 Azure:
[FunctionName("HttpTrigger")]
public static async Task<HttpResponseMessage> Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "post")]HttpRequestMessage req,
ILogger log)
{
log.LogInformation("C# HTTP trigger function processed a request.");
var messages = await req.Content.ReadAsAsync<JArray>();
// If the request is for subscription validation, send back the validation code.
if (messages.Count > 0 && string.Equals((string)messages[0]["eventType"],
"Microsoft.EventGrid.SubscriptionValidationEvent",
System.StringComparison.OrdinalIgnoreCase))
{
log.LogInformation("Validate request received");
return req.CreateResponse<object>(new
{
validationResponse = messages[0]["data"]["validationCode"]
});
}
// The request is not for subscription validation, so it's for one or more events.
foreach (JObject message in messages)
{
// Handle one event.
EventGridEvent eventGridEvent = message.ToObject<EventGridEvent>();
log.LogInformation($"Subject: {eventGridEvent.Subject}");
log.LogInformation($"Time: {eventGridEvent.EventTime}");
log.LogInformation($"Event data: {eventGridEvent.Data.ToString()}");
}
return req.CreateResponse(HttpStatusCode.OK);
}
活动订阅
在 IoT Hub 中,我使用 Web Hook Endpoint 类型创建了一个触发函数的事件订阅。
问题
事件数据的主体似乎已加密(?):
{{
"properties": {},
"systemProperties": {
"iothub-connection-device-id": "smartmeter",
"iothub-connection-auth-method": "{\"scope\":\"device\",\"type\":\"sas\",\"issuer\":\"iothub\",\"acceptingIpFilterRule\":null}",
"iothub-connection-auth-generation-id": "637057961942743477",
"iothub-enqueuedtime": "2019-10-05T08:09:17.973Z",
"iothub-message-source": "Telemetry"
},
"body": "eyJEYXRlVGltZSI6IjIwMTktMTAtMDVUMTA6MDk6MjkiLCJBY3R1YWxUYXJyaWYiOjEsIkFjdHVhbFBvd2VyRGVsaXZlcmVkIjoyNzEuMCwiVG90YWxFbGVjdHJpY2l0eURlbGl2ZXJlZFRhcnJpZjEiOjYwMTU1NzcuMCwiVG90YWxFbGVjdHJpY2l0eURlbGl2ZXJlZFRhcnJpZjIiOjYwMjc5NTIuMH0="
}}
虽然在 Cloud Shell 中我可以看到可读数据。我还可以通过使用 .Net 中的 EventHubClient 将设备读取到云消息来查看可读数据。
我错过了什么?我怎样才能解密身体?
解决方案
您的设备在未指定content-type和content-encoding的情况下发送了遥测数据,请参阅systemProperties对象中缺少这些属性。
设备在发送遥测数据时需要填充这些系统属性,然后您将在事件消息中看到:
"systemProperties":{
"iothub-content-type":"application/json",
"iothub-content-encoding":"utf-8",
...
并且事件的data.body将是一个 json 格式的文本。
更多细节在这里。
推荐阅读
- c# - 添加 .resx 文件时使用 WPF .net Core 3.0 编译错误
- spring - 如何在 Spring Boot 应用程序中注入 Prometheus 指标 bean?
- excel - 如何在 Excel 单元格中迭代字符时提高性能
- php - 有什么方法可以使用 laravel 从单独表中的两列中对用户进行身份验证?
- angular8 - 如何从角度删除硬编码的获取网址?
- angular - 从 API 加载后如何对图像执行任何操作
- python - SciKit-Learn CustomTransformer:TypeError:'numpy.ndarray'对象不可调用
- scala - 在 SPARK SQL 中读取分区的 HIVE 表
- magento - Magento 2.3.2版如何更改tinymce js路径
- java - 错误:(13,28) java: com.aliasi.tokenizer 包不存在