我想从Azure IoT中心读取“ Microsoft.Devices.DeviceConnected”事件(https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-event-grid#event-types)。我找到的唯一示例涉及Azure事件网格,但是我想使用IoT中心的内部终结点(事件中心)。这有可能吗? 当我使用 EventProcessorHost 接口订阅内部事件中心时,得到的都是D2C用户遥测消息。
答案 0 :(得分:0)
就像@PeterBons所说的那样,Azure IoT Hub不支持此功能,但是可以使用Azure Function在Azure IoT Hub之外完成。以下屏幕片段显示了此集成,其中EventGrid事件被推送到IoT中心流:
如您所见,上面的 EventGridTrigger 函数是Azure事件网格和Azure IoT中心之间的集成器。该集成商有责任使用事件网格事件,映射到D2C消息,并将其作为具有Https协议的虚拟IoT设备(后端设备)发送到Azure IoT中心。
更新:
以下代码段是Azure功能-Azure IoT中心集成商的示例:
#r "Microsoft.Azure.EventGrid"
#r "Newtonsoft.Json"
using System.Configuration;
using System.Threading.Tasks;
using System.Security.Cryptography;
using System.Web;
using System.Net.Http;
using System.Text;
using System.Globalization;
using Newtonsoft.Json;
using Microsoft.Azure.EventGrid.Models;
// reusable client proxy
static HttpClientHelper iothub = new HttpClientHelper(Environment.GetEnvironmentVariable("AzureIoTHubShariedAccessPolicy"));
public static async Task Run(EventGridEvent eventGridEvent, ILogger log)
{
log.LogInformation(eventGridEvent.Data.ToString());
// my virtual backend iot device
string deviceId = "Device13";
var content = new StringContent(JsonConvert.SerializeObject(eventGridEvent), Encoding.UTF8, "application/json");
await iothub.Client.PostAsync($"/devices/{deviceId}/messages/events?api-version=2018-06-30", content);
}
// helpers
class HttpClientHelper
{
HttpClient client;
DateTime expiringSaS;
(string hostname, string keyname, string key) config;
public HttpClientHelper(string connectionString)
{
config = GetPartsFromConnectionString(connectionString);
client = new HttpClient() { BaseAddress = new Uri($"https://{config.hostname}")};
SetAuthorizationHeader();
}
public HttpClient Client
{
get
{
if (expiringSaS < DateTime.UtcNow.AddMinutes(-1))
{
SetAuthorizationHeader();
}
return client;
}
}
internal void SetAuthorizationHeader()
{
lock (client)
{
if (expiringSaS < DateTime.UtcNow.AddMinutes(-1))
{
string sasToken = GetSASToken(config.hostname, config.key, config.keyname, 1);
if (client.DefaultRequestHeaders.Contains("Authorization"))
client.DefaultRequestHeaders.Remove("Authorization");
client.DefaultRequestHeaders.Add("Authorization", sasToken);
expiringSaS = DateTime.UtcNow.AddHours(1);
}
}
}
internal (string hostname, string keyname, string key) GetPartsFromConnectionString(string connectionString)
{
var parts = connectionString.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries).Select(s => s.Split(new[] { '=' }, 2)).ToDictionary(x => x[0].Trim(), x => x[1].Trim());
return (parts["HostName"] ?? "", parts["SharedAccessKeyName"] ?? "", parts["SharedAccessKey"] ?? "");
}
internal string GetSASToken(string resourceUri, string key, string keyName = null, uint hours = 24)
{
var expiry = GetExpiry(hours);
string stringToSign = HttpUtility.UrlEncode(resourceUri) + "\n" + expiry;
HMACSHA256 hmac = new HMACSHA256(Convert.FromBase64String(key));
var signature = Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(stringToSign)));
var sasToken = String.Format(CultureInfo.InvariantCulture, $"SharedAccessSignature sr={HttpUtility.UrlEncode(resourceUri)}&sig={HttpUtility.UrlEncode(signature)}&se={expiry}");
if (!string.IsNullOrEmpty(keyName))
sasToken += $"&skn={keyName}";
return sasToken;
}
internal string GetExpiry(uint hours = 24)
{
TimeSpan sinceEpoch = DateTime.UtcNow - new DateTime(1970, 1, 1);
return Convert.ToString((int)sinceEpoch.TotalSeconds + 3600 * hours);
}
}
和function.json:
{
"bindings": [
{
"type": "eventGridTrigger",
"name": "eventGridEvent",
"direction": "in"
}
],
"disabled": false
}
答案 1 :(得分:0)
我只是想补充一下,您可以轻松地在IoT中心的“事件”下创建事件订阅(使用事件网格),并将“连接”事件(例如,设备已连接或设备断开)推送到Azure功能,事件中心或服务总线等
答案 2 :(得分:0)