【发布时间】:2017-09-15 09:10:36
【问题描述】:
我有一个将设备连接到的 Azure IoT 中心。我想启用监控以监控与集线器连接和断开连接的设备。
我已在我的 IoT 集线器的监控类别中启用 Verbose on Connections:
我的设备连接到我的 Hub 并显示在设备资源管理器中:
然后我设置了一个 Azure 函数来将我的数据从操作监控记录到 Azure SQL 数据库:
using System;
using System.Configuration;
using System.Data.SqlClient;
using Newtonsoft.Json;
public static void Run(string myEventHubMessage, TraceWriter log)
{
log.Info(myEventHubMessage);
try
{
var connectionString = ConfigurationManager.ConnectionStrings["iotAzureSQLDb"].ConnectionString;
log.Info(connectionString);
var message = JsonConvert.DeserializeObject<MonitoringMessage>(myEventHubMessage);
using (var connection = new SqlConnection(connectionString))
{
var sqlStatement = "insert into [dbo].[DeviceStatuses] " +
"(DeviceId, ConnectionStatus, ConnectionUpdateTime)" +
"values " +
"(@DeviceId, @ConnectionStatus, @ConnectionUpdateTime)";
using (var dataCommand = new SqlCommand(sqlStatement, connection))
{
dataCommand.Parameters.AddWithValue("@ConnectionStatus", message.operationName);
dataCommand.Parameters.AddWithValue("@DeviceId", message.deviceId);
dataCommand.Parameters.AddWithValue("@ConnectionUpdateTime", message.time);
connection.Open();
dataCommand.ExecuteNonQuery();
connection.Close();
log.Info($"Device {message.deviceId} changed state: {message.operationName}");
}
}
}
catch (Exception ex)
{
log.Info(ex.Message);
}
}
public class MonitoringMessage
{
public string deviceId { get; set; }
public string operationName { get; set; }
public int? durationMs { get; set; }
public string authType { get; set; }
public string protocol { get; set; }
public DateTimeOffset? time { get; set; }
public string category { get; set; }
public string level { get; set; }
public int? statusCode { get; set; }
public int? statusType { get; set; }
public string statusDescription { get; set; }
}
如果我在操作监控中启用设备身份操作,我会记录创建事件。所以我相信函数的输入是正确的。但是,没有为 Connections 创建任何内容???
我也可以很好地向我连接的设备发送消息。我只是没有看到任何连接/断开连接的事件。
我还尝试创建流分析并对输入进行采样,一段时间内我知道我有连接/断开连接,但没有找到任何东西。
【问题讨论】:
-
这就是我正在使用的替代方法,问题是您必须每“x”分钟轮询一次才能获得连接/断开的内容。而如果物联网监控工作正常,我会在设备断开连接时收到事件。
标签: c# azure iot azure-iot-hub