From 1a8de240faec31b63f54ebc1741d22e31801f7b2 Mon Sep 17 00:00:00 2001 From: "David R. Williamson" Date: Mon, 7 Dec 2020 15:10:53 -0800 Subject: [PATCH] Update simulated device project --- iot-hub/Quickstarts/Quickstarts.sln | 6 +- .../Quickstarts/simulated-device/Program.cs | 107 ++++++++++++++++++ .../simulated-device/SimulatedDevice.cs | 67 ----------- ...d-device.csproj => SimulatedDevice.csproj} | 4 +- 4 files changed, 112 insertions(+), 72 deletions(-) create mode 100644 iot-hub/Quickstarts/simulated-device/Program.cs delete mode 100644 iot-hub/Quickstarts/simulated-device/SimulatedDevice.cs rename iot-hub/Quickstarts/simulated-device/{simulated-device.csproj => SimulatedDevice.csproj} (75%) diff --git a/iot-hub/Quickstarts/Quickstarts.sln b/iot-hub/Quickstarts/Quickstarts.sln index c47477fb..dc064b4d 100644 --- a/iot-hub/Quickstarts/Quickstarts.sln +++ b/iot-hub/Quickstarts/Quickstarts.sln @@ -1,13 +1,13 @@  Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 15 -VisualStudioVersion = 15.0.26124.0 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.30717.126 MinimumVisualStudioVersion = 15.0.26124.0 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "back-end-application", "back-end-application\back-end-application.csproj", "{F029ED62-3E01-429A-8E32-4862990A35E2}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "read-d2c-messages", "read-d2c-messages\read-d2c-messages.csproj", "{7701514F-DA48-4344-82FE-4C4A1E7577F9}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "simulated-device", "simulated-device\simulated-device.csproj", "{C22BD1F5-D8A7-452A-96C4-FF0C0553EBF3}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SimulatedDevice", "simulated-device\SimulatedDevice.csproj", "{C22BD1F5-D8A7-452A-96C4-FF0C0553EBF3}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "simulated-device-2", "simulated-device-2\simulated-device-2.csproj", "{3B033BD3-38B4-4B92-8871-2787DD7C86CC}" EndProject diff --git a/iot-hub/Quickstarts/simulated-device/Program.cs b/iot-hub/Quickstarts/simulated-device/Program.cs new file mode 100644 index 00000000..e3bd63de --- /dev/null +++ b/iot-hub/Quickstarts/simulated-device/Program.cs @@ -0,0 +1,107 @@ +// Copyright (c) Microsoft. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +// This application uses the Azure IoT Hub device SDK for .NET +// For samples see: https://github.com/Azure/azure-iot-sdk-csharp/tree/master/iothub/device/samples + +using Microsoft.Azure.Devices.Client; +using System; +using System.Linq; +using System.Text; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; + +namespace SimulatedDevice +{ + /// + /// This sample illustrates the very basics of a device app sending telemetry. For a more comprehensive device app sample, please see + /// . + /// + internal class Program + { + private static DeviceClient s_deviceClient; + + // The device connection string to authenticate the device with your IoT hub. + // Using the Azure CLI: + // az iot hub device-identity show-connection-string --hub-name {YourIoTHubName} --device-id MyDotnetDevice --output table + private static string s_connectionString = "{Your device connection string here}"; + + private static async Task Main(string[] args) + { + Console.WriteLine("IoT Hub Quickstarts #1 - Simulated device."); + + // This sample accepts the device connection string as a parameter, if present + CheckForConnectionStringArgument(args); + + // Connect to the IoT hub using the MQTT protocol + s_deviceClient = DeviceClient.CreateFromConnectionString(s_connectionString, TransportType.Mqtt); + + // Set up a condition to quit the sample + Console.WriteLine("Press control-C to exit."); + using var cts = new CancellationTokenSource(); + Console.CancelKeyPress += (sender, eventArgs) => + { + eventArgs.Cancel = true; + cts.Cancel(); + Console.WriteLine("Device simulator exit requested..."); + }; + + // Run the telemetry loop + await SendDeviceToCloudMessagesAsync(cts.Token); + + Console.WriteLine("Device simulator finished."); + } + + private static void CheckForConnectionStringArgument(string[] args) + { + if (args.Any()) + { + try + { + var cs = IotHubConnectionStringBuilder.Create(args.First()); + s_connectionString = cs.ToString(); + } + catch (Exception) { } + } + } + + // Async method to send simulated telemetry + private static async Task SendDeviceToCloudMessagesAsync(CancellationToken ct) + { + // Initial telemetry values + double minTemperature = 20; + double minHumidity = 60; + var rand = new Random(); + + while (!ct.IsCancellationRequested) + { + double currentTemperature = minTemperature + rand.NextDouble() * 15; + double currentHumidity = minHumidity + rand.NextDouble() * 20; + + // Create JSON message + string messageBody = JsonSerializer.Serialize( + new + { + temperature = currentTemperature, + humidity = currentHumidity, + }); + 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("temperatureAlert", (currentTemperature > 30) ? "true" : "false"); + + // Send the telemetry message + await s_deviceClient.SendEventAsync(message); + Console.WriteLine($"{DateTime.Now} > Sending message: {messageBody}"); + + await Task.Delay(1000); + } + } + } +} diff --git a/iot-hub/Quickstarts/simulated-device/SimulatedDevice.cs b/iot-hub/Quickstarts/simulated-device/SimulatedDevice.cs deleted file mode 100644 index 01ad30c8..00000000 --- a/iot-hub/Quickstarts/simulated-device/SimulatedDevice.cs +++ /dev/null @@ -1,67 +0,0 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -// This application uses the Azure IoT Hub device SDK for .NET -// For samples see: https://github.com/Azure/azure-iot-sdk-csharp/tree/master/iothub/device/samples - -using System; -using Microsoft.Azure.Devices.Client; -using Newtonsoft.Json; -using System.Text; -using System.Threading.Tasks; - -namespace simulated_device -{ - class SimulatedDevice - { - private static DeviceClient s_deviceClient; - - // The device connection string to authenticate the device with your IoT hub. - // Using the Azure CLI: - // az iot hub device-identity show-connection-string --hub-name {YourIoTHubName} --device-id MyDotnetDevice --output table - private readonly static string s_connectionString = "{Your device connection string here}"; - - // Async method to send simulated telemetry - private static async void SendDeviceToCloudMessagesAsync() - { - // Initial telemetry values - double minTemperature = 20; - double minHumidity = 60; - Random rand = new Random(); - - while (true) - { - double currentTemperature = minTemperature + rand.NextDouble() * 15; - double currentHumidity = minHumidity + rand.NextDouble() * 20; - - // Create JSON message - var telemetryDataPoint = new - { - temperature = currentTemperature, - humidity = currentHumidity - }; - var messageString = JsonConvert.SerializeObject(telemetryDataPoint); - var message = new Message(Encoding.ASCII.GetBytes(messageString)); - - // 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("temperatureAlert", (currentTemperature > 30) ? "true" : "false"); - - // Send the telemetry message - await s_deviceClient.SendEventAsync(message); - Console.WriteLine("{0} > Sending message: {1}", DateTime.Now, messageString); - - await Task.Delay(1000); - } - } - private static void Main(string[] args) - { - Console.WriteLine("IoT Hub Quickstarts #1 - Simulated device. Ctrl-C to exit.\n"); - - // Connect to the IoT hub using the MQTT protocol - s_deviceClient = DeviceClient.CreateFromConnectionString(s_connectionString, TransportType.Mqtt); - SendDeviceToCloudMessagesAsync(); - Console.ReadLine(); - } - } -} diff --git a/iot-hub/Quickstarts/simulated-device/simulated-device.csproj b/iot-hub/Quickstarts/simulated-device/SimulatedDevice.csproj similarity index 75% rename from iot-hub/Quickstarts/simulated-device/simulated-device.csproj rename to iot-hub/Quickstarts/simulated-device/SimulatedDevice.csproj index 92970301..69825b01 100644 --- a/iot-hub/Quickstarts/simulated-device/simulated-device.csproj +++ b/iot-hub/Quickstarts/simulated-device/SimulatedDevice.csproj @@ -2,11 +2,11 @@ Exe - netcoreapp2.1 + net5.0 - +