azure iot device to cloud messaging

Internet of Things IoT Frameworks 3 years ago

3.22K 1 0 0 0

_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.

User submissions are the sole responsibility of contributors, with TuteeHUB disclaiming liability for accuracy, copyrights, or consequences of use; content is for informational purposes only and not professional advice.

Answers (1)

Post Answer
profilepic.png
manpreet Tuteehub forum best answer Best Answer 3 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); } } } }
0 views
0 shares

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.

Similar Forum


Q

Azure IoT hub and sending messages with mosquitto_pub

_x000D_ _x000D_ I'm trying to send some simple message with mosquitto_pub to Azure IoT HUB but faced...
Q

How to generate AWS bootstrap certificates with java SDK?

_x000D_ _x000D_ According to this docs I need to generate so-called bootstrap certificates for my Io...
Q

is it possible to do 3way handshake only one time with mqtt communication?

_x000D_ _x000D_ I am using mosquitto_pub to publish the data with TLS using a topic. I am using mosq...

Important Internet of Things Links