gpt4 book ai didi

Azure 物联网中心框架 3.5

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

是否有任何好的教程或指南可以通过框架 3.5 的设备通过 MQTT 协议(protocol)来使用 Azure IoT 中心?我找到了 M2MQTT 客户端,但它无法与 Azure IoT 中心配合使用。

最佳答案

IoT 中心使设备能够直接使用 MQTT v3.1.1 协议(protocol)与 IoT 中心设备端点进行通信。你可以看看这个document 。在文档中,教程是用 python 编写的,以下代码是使用 uPLibrary.Networking.M2Mqtt 的 C# 完整示例。

C# 示例:

    private static string hostName = "<iothub-hosename>";
private static int port = 8883;
private static string deviceId = "<deviceid>";
private static string userName = "";
private static string password = "";
private static string certBase64 = "<DigiCert Baltimore Root Certificate>";

static void Main(string[] args)
{

try
{
userName = $"{hostName}/{deviceId}/api-version=2016-11-14";
password = $"SharedAccessSignature sr=<SAS Token>";

byte[] certBytes = Convert.FromBase64String(certBase64);
X509Certificate caCert = new X509Certificate(certBytes);

MqttClient client = new MqttClient(hostName, port, true, caCert, null , MqttSslProtocols.TLSv1_0);
client.ProtocolVersion = MqttProtocolVersion.Version_3_1_1;

client.MqttMsgPublishReceived += Client_MqttMsgPublishReceived;
client.MqttMsgPublished += Client_MqttMsgPublished;
client.ConnectionClosed += Client_ConnectionClosed;
client.Connect(deviceId, userName, password);
if(client.IsConnected)
{
//To receive messages from IoT Hub, a device should subscribe using devices/{device_id}/messages/devicebound/# as a Topic Filter.
client.Subscribe(new string[] { $"devices/{deviceId}/messages/devicebound/#" }, new byte[] { MqttMsgBase.QOS_LEVEL_AT_LEAST_ONCE });

//After making a successful connection, a device can send messages to IoT Hub using devices/{device_id}/messages/events/ or devices/{device_id}/messages/events/{property_bag} as a Topic Name.
client.Publish($"devices/{deviceid}/messages/events/", System.Text.Encoding.ASCII.GetBytes("{id=123}"), MqttMsgBase.QOS_LEVEL_AT_LEAST_ONCE, false);
}
}
catch(Exception ex)
{
Console.Write(ex.Message);
}

Console.Read();
}

private static void Client_MqttMsgPublished(object sender, MqttMsgPublishedEventArgs e)
{
Console.WriteLine("Mqtt Published Message-[MsgId:{0}]:{1}", e.MessageId, e.IsPublished ? "Success": "Failure");
}

private static void Client_ConnectionClosed(object sender, EventArgs e)
{
Console.WriteLine("ConnectionClosed");
}

private static void Client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
{
Console.WriteLine(System.Text.Encoding.ASCII.GetString(e.Message));
}

在代码中,您可能需要将 DigiCert 巴尔的摩根证书certs.c 复制到 certBase64作为 base64 字符串(删除行 -----BEGIN CERTIFICATE----------END CERTIFICATE-----,并删除 \r\n\)。

更新: enter image description here

如何获取 SAS token ?

您可以使用Device Explorer要生成 SAS token ,请参阅 Using IoT Hub security tokens 的设备部分.

关于Azure 物联网中心框架 3.5,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50668110/

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