jeudi 3 juin 2021

How to generate a random number based on the time of the day?

I am simulating an Iot Device (Noise Sensor) in Azure IoT hub the code below works perfectly fine. However I want to simulate something closer to reality, where I can use different decibel ranges between different hours.

Something like this:

if 00.00- 7.00AM - Randum number between (10-20)
if 7am-9AM - Random number  between (20-40)
if 11.30-1.30pm Random number between 60-80

I dont want to create a lof of IFs,Elses, as I would like to have cleaner code.

How should I do this in a structured manner?

My code below: (only the relevant method)

private static async Task SendDeviceToCloudMessagesAsync(CancellationToken ct)
{
    // Initial telemetry values
    int minNoise = 20;
    int maxNoise = 90;
    var rand = new Random();
    
    while (!ct.IsCancellationRequested)
    {
        double noiseDecibels = rand.Next(minNoise, maxNoise);
                  
        // Create JSON message
        string messageBody = JsonSerializer.Serialize(
            new
            {
                eui= "58A0CB0000101DB6",
                DecibelValue = noiseDecibels
            });
        using var message = new Message(Encoding.ASCII.GetBytes(messageBody))
        {
            ContentType = "application/json",
            ContentEncoding = "utf-8",
        };
    
        // Add a custom application property to the message.
        // An IoT hub can filter on these properties without 
        // access to the message body.
        message.Properties.Add("noiseAlert", (noiseDecibels > 70) ? "true" : "false");
    
        // Send the telemetry message
        await s_deviceClient.SendEventAsync(message);
        Console.WriteLine($"{DateTime.Now} > Sending message: {messageBody}");
    
        await Task.Delay(60000);
    }
}



Aucun commentaire:

Enregistrer un commentaire