azure iot device to cloud messaging

Internet of Things IoT Frameworks 2 years ago

0 1 0 0 0 tuteeHUB earn credit +10 pts

5 Star Rating 1 Rating
_x000D_ _x000D_ I want to write a console application that writes device message to the cloud. I have written a cloud2-device application using IOT hub and preconfig all of my Hub device ID and works. Here is my sample code to connect-2-cloud-message using C# in visual studio. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Input; using System.Diagnostics.Tracing; using Microsoft.Azure.Devices.Client; namespace Device2CloudApp { class Program { // private our own fields for connection to IOT. private DeviceClient deviceClient; // use the device specific connection string. private const string IOT_HUB_CONN_STRING = "HostName=eNstaHub.azure-devices.net;DeviceId=GcobaniNumber1;SharedAccessKey=""; private const string IOT_HUB_DEVICE = "GcobaniNumber1"; private const string IOT_HUB_DEVICE_LOCATION = "West US"; /* * We calling all method inside the constructor for memory allocation. */ public Program () { SendMessageToIOTHubAsync(deviceClient).Wait(); } private async Task SendMessageToIOTHubAsync(DeviceClient deviceClient) { try { var payload = "{" + "\"deviceId\":\"" + IOT_HUB_DEVICE + "\", " + "\"location\":\"" + IOT_HUB_DEVICE_LOCATION + "\", " + "\"localTimestamp\":\"" + DateTime.Now.ToLocalTime() + "\"" + "}"; var msg = new Message(Encoding.UTF8.GetBytes(payload)); System.Diagnostics.Debug.WriteLine("\t{0} > Sending message:[{1}]", DateTime.Now.ToLocalTime(), payload); await deviceClient.SendEventAsync(msg); }catch(Exception ex) { System.Diagnostics.Debug.WriteLine("!!!" + ex.Message); } } static void Main(string[] args) { DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(IOT_HUB_CONN_STRING); // creating a Constructor here for method declarion. Program prg = new Program(); } } } On my console its not connection to the cloud-IOT hub; It throws an System.NullreferenceException.

Posted on 16 Aug 2022, this text provides information on IoT Frameworks related to Internet of Things. Please note that while accuracy is prioritized, the data presented might not be entirely correct or up-to-date. This information is offered for general knowledge and informational purposes only, and should not be considered as a substitute for professional advice.

Take Quiz To Earn Credits!

Turn Your Knowledge into Earnings.

tuteehub_quiz

Answers (1)

Post Answer
profilepic.png
manpreet Tuteehub forum best answer Best Answer 2 years ago
_x000D_ Please try this .Hope it helps. Declare the constants first. private const string DeviceKey = "your secret key"; private const string DeviceId = "DeviceName"; And then create a connection string based on SymmetricKey _deviceClient = DeviceClient.Create(IotHubUri, new DeviceAuthenticationWithRegistrySymmetricKey(DeviceId, DeviceKey), TransportType.Mqtt); Sample code of Simulator: using System; using System.Text; using System.Threading.Tasks; using Microsoft.Azure.Devices.Client; using Newtonsoft.Json; namespace SimulatedDevice { class Program { private const string IotHubUri = "YourHubName.azure-devices.net"; private const string DeviceKey = "Secret Key"; private const string DeviceId = "DeviceId"; private const double MinVoltage = 40; private const double MinTemperature = 10; private const double MinHumidity = 50; private static readonly Random Rand = new Random(); private static DeviceClient _deviceClient; private static int _messageId = 1; static void Main(string[] args) { Console.WriteLine("Simulated device\n"); _deviceClient = DeviceClient.Create(IotHubUri, new DeviceAuthenticationWithRegistrySymmetricKey(DeviceId, DeviceKey), TransportType.Mqtt); _deviceClient.ProductInfo = "Simulated_Client"; SendDeviceToCloudMessagesAsync(); Console.ReadLine(); } private static async void SendDeviceToCloudMessagesAsync() { while (true) { var currentVoltage = MinVoltage + Rand.NextDouble() * 15; var currentTemperature = MinTemperature + Rand.NextDouble() * 20; var currentHumidity = MinHumidity + Rand.NextDouble() * 25; var telemetryDataPoint = new { deviceId = DeviceId, timestamp = DateTime.UtcNow, Temperature = currentTemperature, Humidity = currentHumidity, Voltage = currentVoltage, }; var messageString = JsonConvert.SerializeObject(telemetryDataPoint); var message = new Message(Encoding.ASCII.GetBytes(messageString)); await _deviceClient.SendEventAsync(message); Console.WriteLine("{0} > Sending message: {1}", DateTime.Now, messageString); await Task.Delay(2000); } } } }

No matter what stage you're at in your education or career, TuteeHub will help you reach the next level that you're aiming for. Simply,Choose a subject/topic and get started in self-paced practice sessions to improve your knowledge and scores.

Important Internet of Things Links

tuteehub community

Join Our Community Today

Ready to take your education and career to the next level? Register today and join our growing community of learners and professionals.

tuteehub community