-
Notifications
You must be signed in to change notification settings - Fork 457
/
Program.cs
273 lines (234 loc) · 11 KB
/
Program.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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
// Copyright (c) Microsoft. All rights reserved.
namespace SimulatedTemperatureSensor
{
using System;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Devices.Client;
using Microsoft.Azure.Devices.Client.Transport.Mqtt;
using Microsoft.Azure.Devices.Edge.Util;
using Microsoft.Azure.Devices.Edge.Util.Concurrency;
using Microsoft.Azure.Devices.Edge.Util.TransientFaultHandling;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using ExponentialBackoff = Microsoft.Azure.Devices.Edge.Util.TransientFaultHandling.ExponentialBackoff;
class Program
{
const int RetryCount = 5;
const string MessageCountConfigKey = "MessageCount";
static readonly ITransientErrorDetectionStrategy TimeoutErrorDetectionStrategy = new DelegateErrorDetectionStrategy(ex => ex.HasTimeoutException());
static readonly RetryStrategy TransientRetryStrategy =
new ExponentialBackoff(RetryCount, TimeSpan.FromSeconds(2), TimeSpan.FromSeconds(60), TimeSpan.FromSeconds(4));
static readonly Random Rnd = new Random();
static readonly AtomicBoolean Reset = new AtomicBoolean(false);
public enum ControlCommandEnum
{
Reset = 0,
Noop = 1
}
public static int Main() => MainAsync().Result;
static async Task<int> MainAsync()
{
Console.WriteLine($"[{DateTime.UtcNow.ToString("MM/dd/yyyy hh:mm:ss.fff tt", CultureInfo.InvariantCulture)}] Main()");
IConfiguration configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("config/appsettings.json", optional: true)
.AddEnvironmentVariables()
.Build();
TimeSpan messageDelay = configuration.GetValue("MessageDelay", TimeSpan.FromSeconds(5));
int messageCount = configuration.GetValue(MessageCountConfigKey, 500);
bool sendForever = messageCount < 0;
var sim = new SimulatorParameters
{
MachineTempMin = configuration.GetValue<double>("machineTempMin", 21),
MachineTempMax = configuration.GetValue<double>("machineTempMax", 100),
MachinePressureMin = configuration.GetValue<double>("machinePressureMin", 1),
MachinePressureMax = configuration.GetValue<double>("machinePressureMax", 10),
AmbientTemp = configuration.GetValue<double>("ambientTemp", 21),
HumidityPercent = configuration.GetValue("ambientHumidity", 25)
};
string messagesToSendString = sendForever ? "unlimited" : messageCount.ToString();
Console.WriteLine(
$"Initializing simulated temperature sensor to send {messagesToSendString} messages, at an interval of {messageDelay.TotalSeconds} seconds.\n"
+ $"To change this, set the environment variable {MessageCountConfigKey} to the number of messages that should be sent (set it to -1 to send unlimited messages).");
TransportType transportType = configuration.GetValue("ClientTransportType", TransportType.Amqp_Tcp_Only);
Console.WriteLine($"Using transport {transportType.ToString()}");
var retryPolicy = new RetryPolicy(TimeoutErrorDetectionStrategy, TransientRetryStrategy);
retryPolicy.Retrying += (_, args) =>
{
Console.WriteLine($"Creating ModuleClient failed with exception {args.LastException}");
if (args.CurrentRetryCount < RetryCount)
{
Console.WriteLine("Retrying...");
}
};
ModuleClient moduleClient = await retryPolicy.ExecuteAsync(() => InitModuleClient(transportType));
ModuleClient userContext = moduleClient;
await moduleClient.SetInputMessageHandlerAsync("control", ControlMessageHandle, userContext);
(CancellationTokenSource cts, ManualResetEventSlim completed, Option<object> handler)
= ShutdownHandler.Init(TimeSpan.FromSeconds(5), null);
await SendEvents(moduleClient, messageDelay, sendForever, messageCount, sim, cts);
await cts.Token.WhenCanceled();
completed.Set();
handler.ForEach(h => GC.KeepAlive(h));
return 0;
}
static async Task<ModuleClient> InitModuleClient(TransportType transportType)
{
ITransportSettings[] GetTransportSettings()
{
switch (transportType)
{
case TransportType.Mqtt:
case TransportType.Mqtt_Tcp_Only:
case TransportType.Mqtt_WebSocket_Only:
return new ITransportSettings[] { new MqttTransportSettings(transportType) };
default:
return new ITransportSettings[] { new AmqpTransportSettings(transportType) };
}
}
ITransportSettings[] settings = GetTransportSettings();
ModuleClient moduleClient = await ModuleClient.CreateFromEnvironmentAsync(settings);
await moduleClient.OpenAsync().ConfigureAwait(false);
await moduleClient.SetMethodHandlerAsync("reset", ResetMethod, null);
Console.WriteLine("Successfully initialized module client.");
return moduleClient;
}
// Control Message expected to be:
// {
// "command" : "reset"
// }
static Task<MessageResponse> ControlMessageHandle(Message message, object userContext)
{
byte[] messageBytes = message.GetBytes();
string messageString = Encoding.UTF8.GetString(messageBytes);
Console.WriteLine($"Received message Body: [{messageString}]");
try
{
var messages = JsonConvert.DeserializeObject<ControlCommand[]>(messageString);
foreach (ControlCommand messageBody in messages)
{
if (messageBody.Command == ControlCommandEnum.Reset)
{
Console.WriteLine("Resetting temperature sensor..");
Reset.Set(true);
}
else
{
// NoOp
}
}
}
catch (JsonSerializationException)
{
var messageBody = JsonConvert.DeserializeObject<ControlCommand>(messageString);
if (messageBody.Command == ControlCommandEnum.Reset)
{
Console.WriteLine("Resetting temperature sensor..");
Reset.Set(true);
}
else
{
// NoOp
}
}
catch (Exception ex)
{
Console.WriteLine($"Failed to deserialize control command with exception: [{ex.Message}]");
}
return Task.FromResult(MessageResponse.Completed);
}
static Task<MethodResponse> ResetMethod(MethodRequest methodRequest, object userContext)
{
Console.WriteLine("Received direct method call to reset temperature sensor...");
Reset.Set(true);
var response = new MethodResponse((int)HttpStatusCode.OK);
return Task.FromResult(response);
}
/// <summary>
/// Module behavior:
/// Sends data periodically (with default frequency of 5 seconds).
/// Data trend:
/// - Machine Temperature regularly rises from 21C to 100C in regularly with jitter
/// - Machine Pressure correlates with Temperature 1 to 10psi
/// - Ambient temperature stable around 21C
/// - Humidity is stable with tiny jitter around 25%
/// Method for resetting the data stream
/// </summary>
static async Task SendEvents(
ModuleClient moduleClient,
TimeSpan messageDelay,
bool sendForever,
int messageCount,
SimulatorParameters sim,
CancellationTokenSource cts)
{
int count = 1;
double currentTemp = sim.MachineTempMin;
double normal = (sim.MachinePressureMax - sim.MachinePressureMin) / (sim.MachineTempMax - sim.MachineTempMin);
while (!cts.Token.IsCancellationRequested && (sendForever || messageCount >= count))
{
if (Reset)
{
currentTemp = sim.MachineTempMin;
Reset.Set(false);
}
if (currentTemp > sim.MachineTempMax)
{
currentTemp += Rnd.NextDouble() - 0.5; // add value between [-0.5..0.5]
}
else
{
currentTemp += -0.25 + (Rnd.NextDouble() * 1.5); // add value between [-0.25..1.25] - average +0.5
}
var tempData = new MessageBody
{
Machine = new Machine
{
Temperature = currentTemp,
Pressure = sim.MachinePressureMin + ((currentTemp - sim.MachineTempMin) * normal),
},
Ambient = new Ambient
{
Temperature = sim.AmbientTemp + Rnd.NextDouble() - 0.5,
Humidity = Rnd.Next(24, 27)
},
TimeCreated = DateTime.UtcNow
};
string dataBuffer = JsonConvert.SerializeObject(tempData);
var eventMessage = new Message(Encoding.UTF8.GetBytes(dataBuffer));
Console.WriteLine($"\t{DateTime.Now.ToLocalTime()}> Sending message: {count}, Body: [{dataBuffer}]");
await moduleClient.SendEventAsync("temperatureOutput", eventMessage);
await Task.Delay(messageDelay, cts.Token);
count++;
}
if (messageCount < count)
{
Console.WriteLine($"Done sending {messageCount} messages");
}
}
static void CancelProgram(CancellationTokenSource cts)
{
Console.WriteLine("Termination requested, closing.");
cts.Cancel();
}
internal class ControlCommand
{
[JsonProperty("command")]
public ControlCommandEnum Command { get; set; }
}
internal class SimulatorParameters
{
public double MachineTempMin { get; set; }
public double MachineTempMax { get; set; }
public double MachinePressureMin { get; set; }
public double MachinePressureMax { get; set; }
public double AmbientTemp { get; set; }
public int HumidityPercent { get; set; }
}
}
}