Azure 物联网设备到云消息传递
azure iot device to cloud messaging
我想编写一个将设备消息写入云端的控制台应用程序。我已经使用 IOT 集线器编写了一个 cloud2-device 应用程序并预配置了我所有的集线器设备 ID 和工作。
这是我在 visual studio 中使用 C# connect-2-cloud-message 的示例代码。
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();
}
}
}
在我的控制台上,它没有连接到云物联网集线器;
它抛出一个 System.NullreferenceException.
您在 main
方法中有一个本地 deviceClient
方法,这不是与 Azure 通信时使用的方法。
删除那个,然后创建您在 class 中拥有的实例。
它应该像下面的代码一样工作。
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 ()
{
DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(IOT_HUB_CONN_STRING);
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)
{
// creating a Constructor here for method declarion.
Program prg = new Program(deviceClient);
}
}
}
请试试这个。希望对您有所帮助。
先声明常量。
private const string DeviceKey = "your secret key";
private const string DeviceId = "DeviceName";
然后根据SymmetricKey创建连接字符串
_deviceClient = DeviceClient.Create(IotHubUri, new
DeviceAuthenticationWithRegistrySymmetricKey(DeviceId, DeviceKey), TransportType.Mqtt);
模拟器示例代码:
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);
}
}
}
}
我想编写一个将设备消息写入云端的控制台应用程序。我已经使用 IOT 集线器编写了一个 cloud2-device 应用程序并预配置了我所有的集线器设备 ID 和工作。
这是我在 visual studio 中使用 C# connect-2-cloud-message 的示例代码。
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();
}
}
}
在我的控制台上,它没有连接到云物联网集线器; 它抛出一个 System.NullreferenceException.
您在 main
方法中有一个本地 deviceClient
方法,这不是与 Azure 通信时使用的方法。
删除那个,然后创建您在 class 中拥有的实例。
它应该像下面的代码一样工作。
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 ()
{
DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(IOT_HUB_CONN_STRING);
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)
{
// creating a Constructor here for method declarion.
Program prg = new Program(deviceClient);
}
}
}
请试试这个。希望对您有所帮助。
先声明常量。
private const string DeviceKey = "your secret key";
private const string DeviceId = "DeviceName";
然后根据SymmetricKey创建连接字符串
_deviceClient = DeviceClient.Create(IotHubUri, new
DeviceAuthenticationWithRegistrySymmetricKey(DeviceId, DeviceKey), TransportType.Mqtt);
模拟器示例代码:
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);
}
}
}
}