【发布时间】:2021-08-21 12:49:57
【问题描述】:
我在 Azure IoT 中心模拟 IoT 设备(噪声传感器),下面的代码运行良好。 但是我想模拟一些更接近现实的东西,我可以在不同的时间使用不同的分贝范围。
类似这样的:
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
我不想创建大量的 IF、Elses,因为我想要更简洁的代码。
我应该如何以结构化的方式做到这一点?
我的代码如下:(仅相关方法)
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);
}
}
【问题讨论】:
-
如果你想要有特定条件的东西,你必须有 if/else 语句来满足这个条件,不幸的是,别无选择,你可以创建一个函数来返回基于分贝值的有助于保持“清洁”的时间