Skip to content

Commit

Permalink
Fix Simulated Temp Sensor to send 500 messages at a time by default (#…
Browse files Browse the repository at this point in the history
…460)

* Fix Simulated Temp Sensor to send 500 messages at a time by default

* Fix formatting
  • Loading branch information
varunpuranik authored Oct 19, 2018
1 parent c5c3faa commit d0b2196
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 19 deletions.
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
{
"EdgeHubConnectionString": "<YourConnectionString>",
"MessageDelay": "00:00:05",
"MessageCount": 500,
"machineTempMin": 21,
"machineTempMax": 100,
"machinePressureMin": 1,
Expand Down
46 changes: 27 additions & 19 deletions edge-modules/SimulatedTemperatureSensor/src/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,7 @@ namespace SimulatedTemperatureSensor
using System;
using System.Globalization;
using System.IO;
using System.Linq.Expressions;
using System.Net;
using System.Runtime.Loader;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
Expand All @@ -23,6 +21,7 @@ namespace SimulatedTemperatureSensor
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));
Expand All @@ -44,6 +43,8 @@ static async Task<int> MainAsync()
.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),
Expand All @@ -54,6 +55,10 @@ static async Task<int> MainAsync()
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()}");

Expand All @@ -69,11 +74,12 @@ static async Task<int> MainAsync()
ModuleClient moduleClient = await retryPolicy.ExecuteAsync(() => InitModuleClient(transportType));

ModuleClient userContext = moduleClient;
await moduleClient.SetInputMessageHandlerAsync("control", ControlMessageHandle, userContext).ConfigureAwait(false);
await moduleClient.SetInputMessageHandlerAsync("control", ControlMessageHandle, userContext);

(CancellationTokenSource cts, ManualResetEventSlim completed, Option<object> handler)
= ShutdownHandler.Init(TimeSpan.FromSeconds(5), null);
await SendEvents(moduleClient, messageDelay, sim, cts).ConfigureAwait(false);
await SendEvents(moduleClient, messageDelay, sendForever, messageCount, sim, cts);
await cts.Token.WhenCanceled();
completed.Set();
handler.ForEach(h => GC.KeepAlive(h));
return 0;
Expand All @@ -95,9 +101,9 @@ ITransportSettings[] GetTransportSettings()
}
ITransportSettings[] settings = GetTransportSettings();

ModuleClient moduleClient = await ModuleClient.CreateFromEnvironmentAsync(settings).ConfigureAwait(false);
ModuleClient moduleClient = await ModuleClient.CreateFromEnvironmentAsync(settings);
await moduleClient.OpenAsync().ConfigureAwait(false);
await moduleClient.SetMethodHandlerAsync("reset", ResetMethod, null).ConfigureAwait(false);
await moduleClient.SetMethodHandlerAsync("reset", ResetMethod, null);

Console.WriteLine("Successfully initialized module client.");
return moduleClient;
Expand Down Expand Up @@ -163,30 +169,27 @@ static Task<MethodResponse> ResetMethod(MethodRequest methodRequest, object user

/// <summary>
/// Module behavior:
/// Sends data once every 5 seconds.
/// 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%
/// - 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>
/// <param name="moduleClient"></param>
/// <param name="messageDelay"></param>
/// <param name="sim"></param>
/// <param name="cts"></param>
/// <returns></returns>
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)
while (!cts.Token.IsCancellationRequested && (sendForever || messageCount >= count))
{
if (Reset)
{
Expand Down Expand Up @@ -221,10 +224,15 @@ static async Task SendEvents(
var eventMessage = new Message(Encoding.UTF8.GetBytes(dataBuffer));
Console.WriteLine($"\t{DateTime.Now.ToLocalTime()}> Sending message: {count}, Body: [{dataBuffer}]");

await moduleClient.SendEventAsync("temperatureOutput", eventMessage).ConfigureAwait(false);
await Task.Delay(messageDelay, cts.Token).ConfigureAwait(false);
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)
Expand Down

0 comments on commit d0b2196

Please sign in to comment.