Prerequisits
Visual studio 2019
Microsoft azure account
IOT Hub
Following are the
steps
- Open visual studio
- Create new project for .net core console
application
- Click next you will get the following screen
- Provide the Project Name and Location and click on Create.
- From the nugget package install the following
packages.
- In the Program.cs class do the following code
using Microsoft.Azure.Devices;using Microsoft.Azure.Devices.Client;
using Microsoft.Azure.Devices.Common.Exceptions;
using Newtonsoft.Json;
using System;
using System.Text;
using System.Threading.Tasks;
using Message = Microsoft.Azure.Devices.Client.Message;
namespace IOTDevice
{
class Program
{
static RegistryManager registryManager;
static string connectionString = "{iot hub connection string}";
static string DeviceConnectionString = "HostName=<yourIotHubName>.azure-devices.net;DeviceId=<yourIotDeviceName>;SharedAccessKey=<yourIotDeviceAccessKey>";
static string deviceId = "myfirstdevice";
static Device device;
static void Main(string[] args)
{
registryManager = RegistryManager.CreateFromConnectionString(connectionString);
AddDeviceAsync().Wait();
SendTelemetryMessageToDevice();
}
private static async Task AddDeviceAsync()
{
try
{
device = await registryManager.AddDeviceAsync(new Device(deviceId));
}
catch (DeviceAlreadyExistsException)
{
device = await registryManager.GetDeviceAsync(deviceId);
}
Console.WriteLine("Generated device key: {0}", device.Authentication.SymmetricKey.PrimaryKey);
}
private static async void SendTelemetryMessageToDevice()
{
try
{
DeviceConnectionString = DeviceConnectionString.Replace("<yourIotHubName>", "your iot hub name");
DeviceConnectionString = DeviceConnectionString.Replace("<yourIotDeviceName>", deviceId);
DeviceConnectionString = DeviceConnectionString.Replace("<yourIotDeviceAccessKey>", device.Authentication.SymmetricKey.PrimaryKey);
var deviceClient = DeviceClient.CreateFromConnectionString(DeviceConnectionString, Microsoft.Azure.Devices.Client.TransportType.Amqp);
var telemetrymessage = new {
memessage="TestMessage"
};
var messageString = JsonConvert.SerializeObject(telemetrymessage);
var message = new Message(Encoding.ASCII.GetBytes(messageString));
message.ContentType = "application/json";
message.ContentEncoding = "UTF-8";
await deviceClient.SendEventAsync(message);
}
catch (Exception ex)
{
}
}
}
}
No comments:
Post a Comment