gpt4 book ai didi

c# - 向 Azure 物联网中心发送消息

转载 作者:行者123 更新时间:2023-12-03 03:01:53 25 4
gpt4 key购买 nike

我是 AzureIot 的初学者,我已获得访问具有 IOT 中心的 Azure 帐户的权限。从 azure 门户中,我看到以下形式的连接字符串:HostName=iothub-mycompany.azure-devices.net;SharedAccessKeyName=iothubowner;SharedAccessKey=_somekey_in_base64_

现在我需要的只是将 JSON 有效负载发送到此 IOT 中心。任何协议(protocol)都可以。

假设当我发送消息时,我可以看到此消息带有 this device explorer tool 。但我不确定我是否做错了什么,或者我的理解是否有缺陷。

我尝试了博客、msdn 等中的示例最后我想出了下面的代码

它运行了,但我不知道它在做什么以及在哪里查找此消息是否已发送

  • 设备资源管理器没有显示任何内容。

  • 我检查了事件登录门户网站 azure.com,但它看起来更像是登录事件日志。

  • 还在 azure 门户中的浏览器下我看到了物联网设备。我看到了我需要定位的设备名称。(我知道它存在)

这是代码,.Net4.5.2 ConsoleApplication 的一部分。

Program.cs:

class Program
{
static DeviceClient deviceClient;
const string IOT_HUB_CONN_STRING = "connection str in format specified above.";
const string IOT_HUB_DEVICE_LOCATION = "_some_location.";
const string IOT_HUB_DEVICE = "device_id";

static void Main(string[] args)
{
var ret = SendMessageToIoTHubAsync("temperature", 15);


Console.WriteLine("completed:" + ret.IsCompleted);


}
private static async Task SendMessageToIoTHubAsync(string sensorType, int sensorState)
{
deviceClient = DeviceClient.CreateFromConnectionString(IOT_HUB_CONN_STRING, TransportType.Mqtt);//i tried other trsnsports
try
{
var payload = "{" +
"\"deviceId\":\"" + IOT_HUB_DEVICE + "\", " +
"\"location\":\"" + IOT_HUB_DEVICE_LOCATION + "\", " +
"\"sensorType\":\"" + sensorType + "\", " +
"\"sensorState\":" + sensorState + ", " +
"\"localTimestamp\":\"" + DateTime.Now.ToLocalTime() + "\"" +
"}";

var msg = new Message(Encoding.UTF8.GetBytes(payload));

Debug.WriteLine("\t{0}> Sending message: [{1}]", DateTime.Now.ToLocalTime(), payload);

await deviceClient.SendEventAsync(msg);
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine("!!!! " + ex.Message);
}
}
}

顺便说一句,我的“设备”是 ClearScada 。我将拥有 C# 驱动程序,它将从 ClearScada 实例中获取数据,该驱动程序应将该数据发送到 azure 物联网中心。 本质上我只需要计算从 C# 发送的数据 到 Azure 物联网。问题:

  • 我在哪里可以看到我的消息。?
  • 我的功能是否正确,或者我的理解是否存在缺陷。

最佳答案

  • Where Can I see my messages.?

您可以在设备资源管理器中查看消息,如下所示:

enter image description here

  • Is my function correct or is there a flaw in my understanding.

您的函数存在两个问题:

  • 首先,您需要使用设备指定的连接字符串而不是Azure IoT 中心连接字符串。它具有以下格式:

    “HostName=[您的集线器名称].azure-devices.net;DeviceId=[设备 ID];SharedAccessKey=[设备 key ]”

您可以通过设备资源管理器轻松获取此连接字符串,如下所示:

enter image description here

  • 其次,您的程序在发送操作完全之前退出。您可以通过添加 Console.ReadLine(); 来避免这种情况发生这个:

enter image description here

更新:

Retrieving the value of the Task.IsCompleted property does not block the calling thread until the task has completed.

您可以像这样编辑您的 main 方法:

    static void Main(string[] args)
{
var ret = SendMessageToIoTHubAsync("temperature", 15);

ret.Wait();
Console.WriteLine("completed:" + ret.IsCompleted);
Console.ReadLine();
}

关于c# - 向 Azure 物联网中心发送消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48251474/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com