我想编写一个将设备消息写入云的控制台应用程序。我已经编写了一个使用IOT集线器和preconfig的Cloud2设备应用程序,所有我的集线器设备ID和工作。
下面是我在visual中使用C#连接2云消息的示例代码。
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();
}
}
}在我的控制台上,它没有连接到云-IOT集线器;它抛出一个System.NullreferenceException。
发布于 2019-08-08 01:28:25
它应该按照下面的代码工作。
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);
}
}
}发布于 2019-08-07 13:54:13
在deviceClient方法中有一个本地main,这不是与Azure通信时使用的方法。
删除该实例,然后创建类中的实例。
发布于 2019-08-08 02:56:30
请试试这个.Hope,它很有帮助。
首先声明常量。
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);
}
}
}
}https://stackoverflow.com/questions/57396012
复制相似问题