我尝试使用MS教程https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-csharp-csharp-getstarted和
中的代码internal class Program
{
private static string connectionString = "HostName=...=";
private static string d2cEndpoint = "messages/events";
private static EventHubClient eventHubClient;
private static void Main(string[] args)
{
Console.WriteLine("Receive messages\n");
eventHubClient = EventHubClient.
CreateFromConnectionString(
connectionString, d2cEndpoint);
var d2cPartitions = eventHubClient.
GetRuntimeInformation().PartitionIds;
foreach (string partition in d2cPartitions)
{
ReceiveMessagesFromDeviceAsync(partition);
}
Console.ReadLine();
}
private async static Task ReceiveMessagesFromDeviceAsync(
string partition)
{
var eventHubReceiver = eventHubClient.
GetDefaultConsumerGroup().
CreateReceiver(partition, DateTime.UtcNow);
while (true)
{
EventData eventData = await eventHubReceiver.
ReceiveAsync();
if (eventData == null) continue;
string data = Encoding.UTF8.GetString(
eventData.GetBytes());
Console.WriteLine(string.Format(
"Message received. Partition: {0} Data: '{1}'",
partition, data));
}
}
}
从IoT Hub获取数据,但仍有问题。 可以轻松获取这些数据吗?
答案 0 :(得分:1)
使用VS2017版本> = 15.3.1,您可以为 EventHubTrigger 功能创建Azure Functions项目,而无需任何单行代码。以下模板代码段显示了此功能:
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.Azure.WebJobs.ServiceBus;
namespace FunctionApp4
{
public static class Function1
{
[FunctionName("Function1")]
public static void Run([EventHubTrigger("myEventHubName", Connection = "myIoTHub")]string myEventHubMessage, TraceWriter log)
{
log.Info($"C# Event Hub trigger function processed a message: {myEventHubMessage}");
}
}
}
和local.settings.json文件:
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "DefaultEndpointsProtocol=https;AccountName=...;AccountKey=...",
"AzureWebJobsDashboard": "DefaultEndpointsProtocol=https;AccountName=...;AccountKey=...",
"myIoTHub": "Endpoint=sb://....servicebus.windows.net/;SharedAccessKeyName=iothubowner;SharedAccessKey=..."
}
}