-
Notifications
You must be signed in to change notification settings - Fork 2
/
IoTHubConfig.cs
70 lines (62 loc) · 2.87 KB
/
IoTHubConfig.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
using Microsoft.Azure.EventHubs;
using Microsoft.Azure.EventHubs.Processor;
using System;
using System.Threading;
using System.Threading.Tasks;
namespace EVCharging
{
public class IoTHubConfig
{
public static Task ConfigureIotHub()
{
return Task.Run(() => ConnectToIotHubAsync(CancellationToken.None));
}
private static async Task ConnectToIotHubAsync(CancellationToken ct)
{
EventProcessorHost eventProcessorHost;
// Get configuration settings
string iotHubTelemetryConsumerGroup = "dashboard";
string iotHubEventHubName = Environment.GetEnvironmentVariable("IotHubEventHubName");
string iotHubEventHubEndpointIotHubOwnerConnectionString = Environment.GetEnvironmentVariable("EventHubEndpointIotHubOwnerConnectionString");
string solutionStorageAccountConnectionString = Environment.GetEnvironmentVariable("StorageAccountConnectionString");
// Initialize EventProcessorHost.
Console.WriteLine("Creating Event Processor Host for IoT Hub: {0}, ConsumerGroup: {1}", iotHubEventHubName, iotHubTelemetryConsumerGroup);
string StorageContainerName = "telemetrycheckpoints";
eventProcessorHost = new EventProcessorHost(
iotHubEventHubName,
iotHubTelemetryConsumerGroup,
iotHubEventHubEndpointIotHubOwnerConnectionString,
solutionStorageAccountConnectionString,
StorageContainerName);
// Registers the Event Processor Host and starts receiving messages.
EventProcessorOptions options = new EventProcessorOptions();
options.InitialOffsetProvider = (partitionId) => EventPosition.FromEnqueuedTime(DateTime.UtcNow);
options.SetExceptionHandler(EventProcessorHostExceptionHandler);
try
{
await eventProcessorHost.RegisterEventProcessorAsync<MessageProcessor>(options);
Console.WriteLine($"EventProcessor successfully registered");
}
catch (Exception e)
{
Console.WriteLine($"Exception during register EventProcessorHost '{e.Message}'");
}
// Wait till shutdown.
while (true)
{
if (ct.IsCancellationRequested)
{
Console.WriteLine($"Application is shutting down. Unregistering EventProcessorHost...");
await eventProcessorHost.UnregisterEventProcessorAsync();
return;
}
await Task.Delay(1000);
}
}
private static void EventProcessorHostExceptionHandler(ExceptionReceivedEventArgs args)
{
Console.WriteLine($"EventProcessorHostException: {args.Exception.Message}");
}
}
}