|
| 1 | +// Copyright (c) Microsoft. All rights reserved. |
| 2 | +// Licensed under the MIT license. See LICENSE file in the project root for full license information. |
| 3 | + |
| 4 | +// This application uses the Azure IoT Hub device SDK for .NET |
| 5 | +// For samples see: https://github.com/Azure/azure-iot-sdk-csharp/tree/master/iothub/device/samples |
| 6 | + |
| 7 | +using Microsoft.Azure.Devices.Client; |
| 8 | +using System; |
| 9 | +using System.Linq; |
| 10 | +using System.Text; |
| 11 | +using System.Text.Json; |
| 12 | +using System.Threading; |
| 13 | +using System.Threading.Tasks; |
| 14 | + |
| 15 | +namespace SimulatedDevice |
| 16 | +{ |
| 17 | + /// <summary> |
| 18 | + /// This sample illustrates the very basics of a device app sending telemetry. For a more comprehensive device app sample, please see |
| 19 | + /// <see href="https://github.com/Azure-Samples/azure-iot-samples-csharp/tree/master/iot-hub/Samples/device/DeviceReconnectionSample"/>. |
| 20 | + /// </summary> |
| 21 | + internal class Program |
| 22 | + { |
| 23 | + private static DeviceClient s_deviceClient; |
| 24 | + |
| 25 | + // The device connection string to authenticate the device with your IoT hub. |
| 26 | + // Using the Azure CLI: |
| 27 | + // az iot hub device-identity show-connection-string --hub-name {YourIoTHubName} --device-id MyDotnetDevice --output table |
| 28 | + private static string s_connectionString = "{Your device connection string here}"; |
| 29 | + |
| 30 | + private static async Task Main(string[] args) |
| 31 | + { |
| 32 | + Console.WriteLine("IoT Hub Quickstarts #1 - Simulated device."); |
| 33 | + |
| 34 | + // This sample accepts the device connection string as a parameter, if present |
| 35 | + CheckForConnectionStringArgument(args); |
| 36 | + |
| 37 | + // Connect to the IoT hub using the MQTT protocol |
| 38 | + s_deviceClient = DeviceClient.CreateFromConnectionString(s_connectionString, TransportType.Mqtt); |
| 39 | + |
| 40 | + // Set up a condition to quit the sample |
| 41 | + Console.WriteLine("Press control-C to exit."); |
| 42 | + using var cts = new CancellationTokenSource(); |
| 43 | + Console.CancelKeyPress += (sender, eventArgs) => |
| 44 | + { |
| 45 | + eventArgs.Cancel = true; |
| 46 | + cts.Cancel(); |
| 47 | + Console.WriteLine("Device simulator exit requested..."); |
| 48 | + }; |
| 49 | + |
| 50 | + // Run the telemetry loop |
| 51 | + await SendDeviceToCloudMessagesAsync(cts.Token); |
| 52 | + |
| 53 | + Console.WriteLine("Device simulator finished."); |
| 54 | + } |
| 55 | + |
| 56 | + private static void CheckForConnectionStringArgument(string[] args) |
| 57 | + { |
| 58 | + if (args.Any()) |
| 59 | + { |
| 60 | + try |
| 61 | + { |
| 62 | + var cs = IotHubConnectionStringBuilder.Create(args.First()); |
| 63 | + s_connectionString = cs.ToString(); |
| 64 | + } |
| 65 | + catch (Exception) { } |
| 66 | + } |
| 67 | + } |
| 68 | + |
| 69 | + // Async method to send simulated telemetry |
| 70 | + private static async Task SendDeviceToCloudMessagesAsync(CancellationToken ct) |
| 71 | + { |
| 72 | + // Initial telemetry values |
| 73 | + double minTemperature = 20; |
| 74 | + double minHumidity = 60; |
| 75 | + var rand = new Random(); |
| 76 | + |
| 77 | + while (!ct.IsCancellationRequested) |
| 78 | + { |
| 79 | + double currentTemperature = minTemperature + rand.NextDouble() * 15; |
| 80 | + double currentHumidity = minHumidity + rand.NextDouble() * 20; |
| 81 | + |
| 82 | + // Create JSON message |
| 83 | + string messageBody = JsonSerializer.Serialize( |
| 84 | + new |
| 85 | + { |
| 86 | + temperature = currentTemperature, |
| 87 | + humidity = currentHumidity, |
| 88 | + }); |
| 89 | + using var message = new Message(Encoding.ASCII.GetBytes(messageBody)) |
| 90 | + { |
| 91 | + ContentType = "application/json", |
| 92 | + ContentEncoding = "utf-8", |
| 93 | + }; |
| 94 | + |
| 95 | + // Add a custom application property to the message. |
| 96 | + // An IoT hub can filter on these properties without access to the message body. |
| 97 | + message.Properties.Add("temperatureAlert", (currentTemperature > 30) ? "true" : "false"); |
| 98 | + |
| 99 | + // Send the telemetry message |
| 100 | + await s_deviceClient.SendEventAsync(message); |
| 101 | + Console.WriteLine($"{DateTime.Now} > Sending message: {messageBody}"); |
| 102 | + |
| 103 | + await Task.Delay(1000); |
| 104 | + } |
| 105 | + } |
| 106 | + } |
| 107 | +} |
0 commit comments