-
Notifications
You must be signed in to change notification settings - Fork 90
/
AzureIoTHub.cs
117 lines (102 loc) · 4.6 KB
/
AzureIoTHub.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
using Azure.Messaging.EventHubs.Consumer;
using Microsoft.Azure.Devices;
using Microsoft.Azure.Devices.Client;
using Microsoft.Azure.Devices.Common.Exceptions;
using System;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
namespace DeviceSimulator
{
public static class AzureIoTHub
{
/// <summary>
/// Please replace with correct connection string value
/// The connection string could be got from Azure IoT Hub -> Shared access policies -> iothubowner -> Connection String:
/// </summary>
private const string iotHubConnectionString = "<your-hub-connection-string>";
/// <summary>
/// Please replace with correct device connection string
/// The device connect string could be got from Azure IoT Hub -> Devices -> {your device name } -> Connection string
/// </summary>
private const string deviceConnectionString = "<your-device-connection-string>";
public static async Task<string> CreateDeviceIdentityAsync(string deviceName)
{
var registryManager = RegistryManager.CreateFromConnectionString(iotHubConnectionString);
var device = new Device(deviceName);
try
{
device = await registryManager.AddDeviceAsync(device);
}
catch (DeviceAlreadyExistsException)
{
device = await registryManager.GetDeviceAsync(deviceName);
}
return device.Authentication.SymmetricKey.PrimaryKey;
}
public static async Task SendDeviceToCloudMessageAsync(CancellationToken cancelToken)
{
var deviceClient = DeviceClient.CreateFromConnectionString(deviceConnectionString);
double avgTemperature = 70.0D;
var rand = new Random();
while (!cancelToken.IsCancellationRequested)
{
double currentTemperature = avgTemperature + rand.NextDouble() * 4 - 3;
var telemetryDataPoint = new
{
Temperature = currentTemperature
};
var messageString = JsonSerializer.Serialize(telemetryDataPoint);
var message = new Microsoft.Azure.Devices.Client.Message(Encoding.UTF8.GetBytes(messageString))
{
ContentType = "application/json",
ContentEncoding = "utf-8"
};
await deviceClient.SendEventAsync(message);
Console.WriteLine($"{DateTime.Now} > Sending message: {messageString}");
//Keep this value above 1000 to keep a safe buffer above the ADT service limits
//See https://aka.ms/adt-limits for more info
await Task.Delay(5000);
}
}
public static async Task<string> ReceiveCloudToDeviceMessageAsync()
{
var oneSecond = TimeSpan.FromSeconds(1);
var deviceClient = DeviceClient.CreateFromConnectionString(deviceConnectionString);
while (true)
{
var receivedMessage = await deviceClient.ReceiveAsync();
if (receivedMessage == null)
{
await Task.Delay(oneSecond);
continue;
}
var messageData = Encoding.ASCII.GetString(receivedMessage.GetBytes());
await deviceClient.CompleteAsync(receivedMessage);
return messageData;
}
}
public static async Task ReceiveMessagesFromDeviceAsync(CancellationToken cancelToken)
{
try
{
string eventHubConnectionString = await IotHubConnection.GetEventHubsConnectionStringAsync(iotHubConnectionString);
await using var consumerClient = new EventHubConsumerClient(
EventHubConsumerClient.DefaultConsumerGroupName,
eventHubConnectionString);
await foreach (PartitionEvent partitionEvent in consumerClient.ReadEventsAsync(cancelToken))
{
if (partitionEvent.Data == null) continue;
string data = Encoding.UTF8.GetString(partitionEvent.Data.Body.ToArray());
Console.WriteLine($"Message received. Partition: {partitionEvent.Partition.PartitionId} Data: '{data}'");
}
}
catch (TaskCanceledException) { } // do nothing
catch (Exception ex)
{
Console.WriteLine($"Error reading event: {ex}");
}
}
}
}