我是靠谱客的博主 大意睫毛,最近开发中收集的这篇文章主要介绍C# 基于开源MQTT自主接入阿里云IoT平台,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

1. 准备工作

1.1 注册阿里云账号

使用淘宝账号或手机号,开通阿里云账号,并通过实名认证(可以用支付宝认证)

1.2 免费开通IoT物联网套件

产品官网 https://www.aliyun.com/product/iot

image.png | left | 462x328

1.3 软件开发环境

  • 语言 C#
  • 工具 Visual Studio IDE

2. IoT平台云端开发

2.1 创建基础版产品

产品信息

image.png | left | 540x333

消息通信Topic

image.png | left | 539x290

2.2 注册设备

获取设备身份三元组,ProductKey,DeviceName,DeviceSecret

image.png | left | 572x220

3. 设备端开发

3.1 IoT平台接入password签名算法文件

签名规则参考 https://www.yuque.com/cloud-dev/iot-tech/mebm5g

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
namespace iotxsdkmqttnet {
    public class IotSignUtils {
        public static string sign(Dictionary<string, string> param, 
                            string deviceSecret, string signMethod) {
            string[] sortedKey = param.Keys.ToArray();
            Array.Sort(sortedKey);
 
            StringBuilder builder = new StringBuilder();
            foreach(var i in sortedKey){
                builder.Append(i).Append(param[i]);
            }
 
            byte[] key = Encoding.UTF8.GetBytes(deviceSecret);
            byte[] signContent = Encoding.UTF8.GetBytes(builder.ToString());
            //根据signMethod动态调整,硬编码了: 'hmacmd5'
            var hmac = new HMACMD5(key);
            byte[] hashBytes = hmac.ComputeHash(signContent);
 
            StringBuilder signBuilder = new StringBuilder();
            foreach (byte b in hashBytes)
                signBuilder.AppendFormat("{0:x2}", b);
 
            return signBuilder.ToString();
        }
    }
}

3.2 接入IoT平台C#版本的MQTT库

C#的mqtt库 https://www.nuget.org/packages/M2Mqtt/

目前最好用的C#库是 eclipse出的M2Mqtt库,

主页链接: http://www.eclipse.org/paho/clients/dotnet/

项目的地址是 https://github.com/eclipse/paho.mqtt.m2mqtt

使用方式是在vs 的命令中输入 Install-Package M2Mqtt

组件下载:M2Mqtt.Net.dll (v4.3.0最新版 2019.7.16本地生成)

链接:https://pan.baidu.com/s/1lacs13v9nde8d2wrj2oU4g 
提取码:l8cg 

3.3 设备端应用程序

using System;
using System.Net;
using System.Collections.Generic;
using uPLibrary.Networking.M2Mqtt;
using uPLibrary.Networking.M2Mqtt.Messages;
using System.Text;
using System.Linq;
 
namespace iotMqttDemo {
    class MainClass {
        static string ProductKey = "******";
        static string DeviceName = "******";
        static string DeviceSecret = "******";
        static string RegionId = "cn-shanghai";
 
        static string PubTopic = "/" + ProductKey + "/" + DeviceName + "/update";
        static string SubTopic = "/" + ProductKey + "/" + DeviceName + "/get";
 
        public static void Main(string[] args)
        {
            IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName());
            string clientId = host.AddressList.FirstOrDefault(
                ip => ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork).ToString();
            string t = Convert.ToString(DateTimeOffset.Now.ToUnixTimeMilliseconds());
            string signmethod = "hmacmd5";
 
            Dictionary<string, string> dict = new Dictionary<string, string>();
            dict.Add("productKey", ProductKey);
            dict.Add("deviceName", DeviceName);
            dict.Add("clientId", clientId);
            dict.Add("timestamp", t);
 
            string mqttUserName = DeviceName + "&" + ProductKey;
            string mqttPassword = IotSignUtils.sign(dict, DeviceSecret, signmethod);
            string mqttClientId = clientId + "|securemode=3,signmethod="+signmethod+",timestamp=" + t + "|";
            
            string targetServer = "tcp://" + ProductKey + ".iot-as-mqtt." + RegionId + ".aliyuncs.com";
            
            ConnectMqtt(targetServer, mqttClientId, mqttUserName, mqttPassword);
        }
 
        static void ConnectMqtt(string targetServer, string mqttClientId, string mqttUserName, string mqttPassword){
            MqttClient client = new MqttClient(targetServer);
            client.ProtocolVersion = MqttProtocolVersion.Version_3_1_1;
 
            client.Connect(mqttClientId, mqttUserName, mqttPassword, false, 60);
            client.MqttMsgPublishReceived += Client_MqttMsgPublishReceived;
 
            //发布消息
            String content = "{'content':'msg from :" + mqttClientId + ", 这里是.NET设备'}";
            var id = client.Publish(PubTopic, Encoding.ASCII.GetBytes(content));
 
            //订阅消息
            client.Subscribe(new string[] { SubTopic }, new byte[] { 0 });
        }
 
        static void Client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
        {
            // handle message received
            string topic = e.Topic;
            string message = Encoding.ASCII.GetString(e.Message);
        }
 
    }
}

4. 运行结果

云端看到设备上线记录,数据上报记录

image.png | left | 584x310

至此,完成了.NET平台设备C#语言接入阿里云IoT物联网云平台的开发实践。

MQTT模拟器:关注 

知识课堂:C# MQTTnet使用心得和C# MQTT库M2Mqtt的使用方法

https://blog.csdn.net/uaime/article/details/96119179

最后

以上就是大意睫毛为你收集整理的C# 基于开源MQTT自主接入阿里云IoT平台的全部内容,希望文章能够帮你解决C# 基于开源MQTT自主接入阿里云IoT平台所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(73)

评论列表共有 0 条评论

立即
投稿
返回
顶部