Skip to content
This repository has been archived by the owner on Nov 16, 2023. It is now read-only.

Commit

Permalink
Update simulated device project
Browse files Browse the repository at this point in the history
  • Loading branch information
David R. Williamson committed Dec 8, 2020
1 parent 9246956 commit 1a8de24
Show file tree
Hide file tree
Showing 4 changed files with 112 additions and 72 deletions.
6 changes: 3 additions & 3 deletions iot-hub/Quickstarts/Quickstarts.sln
Original file line number Diff line number Diff line change
@@ -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
Expand Down
107 changes: 107 additions & 0 deletions iot-hub/Quickstarts/simulated-device/Program.cs
Original file line number Diff line number Diff line change
@@ -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
{
/// <summary>
/// This sample illustrates the very basics of a device app sending telemetry. For a more comprehensive device app sample, please see
/// <see href="https://github.com/Azure-Samples/azure-iot-samples-csharp/tree/master/iot-hub/Samples/device/DeviceReconnectionSample"/>.
/// </summary>
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);
}
}
}
}
67 changes: 0 additions & 67 deletions iot-hub/Quickstarts/simulated-device/SimulatedDevice.cs

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp2.1</TargetFramework>
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.Azure.Devices.Client" Version="1.*" />
<PackageReference Include="Microsoft.Azure.Devices.Client" Version="1.33.1" />
</ItemGroup>

</Project>

0 comments on commit 1a8de24

Please sign in to comment.