基于开源MQTT自主接入阿里云IoT平台(C#)

简介: 基于开源MQTT自主接入阿里云IoT平台(C#)

本文由 GXIC 作者 wongxmig 完成,欢迎关注 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/

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物联网云平台的开发实践。

相关实践学习
消息队列RocketMQ版:基础消息收发功能体验
本实验场景介绍消息队列RocketMQ版的基础消息收发功能,涵盖实例创建、Topic、Group资源创建以及消息收发体验等基础功能模块。
消息队列 MNS 入门课程
1、消息队列MNS简介 本节课介绍消息队列的MNS的基础概念 2、消息队列MNS特性 本节课介绍消息队列的MNS的主要特性 3、MNS的最佳实践及场景应用 本节课介绍消息队列的MNS的最佳实践及场景应用案例 4、手把手系列:消息队列MNS实操讲 本节课介绍消息队列的MNS的实际操作演示 5、动手实验:基于MNS,0基础轻松构建 Web Client 本节课带您一起基于MNS,0基础轻松构建 Web Client
目录
相关文章
|
1月前
|
消息中间件 存储 Apache
恭喜 Apache RocketMQ、Apache Seata 荣获 2024 开源创新榜单“年度开源项目”
近日,以“新纪天工、开物焕彩——致敬开源的力量”为活动主题的“重大科技成就发布会(首场)”在国家科技传播中心成功举办,并隆重揭晓了 2024 开源创新榜单,旨在致敬中国开源力量,传播推广开源科技成就,营造中国开源创新生态。2024 年开源创新榜单由中国科协科学技术传播中心、中国计算机学会、中国通信学会、中国科学院软件研究所共同主办,中国开发者社区承办,以王怀民院士为首组建评审委员会,进行研讨评审,面向中国开源行业领域,遴选具有创新性、贡献度和影响力的开源项目、社区、应用场景与开源事件。在评审出的 10 个年度开源项目中,Apache RocketMQ、Apache Seata 成功入选。
|
2月前
|
Linux C# iOS开发
开源GTKSystem.Windows.Forms框架让C# Winform支持跨平台运行
开源GTKSystem.Windows.Forms框架让C# Winform支持跨平台运行
65 12
|
3月前
|
存储 算法 安全
FreeMQTT:一款Python语言实现的开源MQTT Server
FreeMQTT 是一款用 Python 语言并基于 Tornado 开发的开源 MQTT 服务器,支持 MQTT3.1.1 和 MQTT5.0 协议,提供多租户安全隔离、高效 Topic 匹配算法及实时上下线通知等功能,适用于 IoT 场景。快速启动仅需克隆仓库、安装依赖并运行服务。
|
3月前
|
消息中间件 运维 Serverless
商业版vs开源版:一图看懂云消息队列 RocketMQ 版核心优势
自建开源 RocketMQ 集群,为保证业务稳定性,往往需要按照业务请求的峰值去配置集群资源。云消息队列 RocketMQ 版 Serverless 实例通过资源快速伸缩,实现资源使用量与实际业务负载贴近,并按实际使用量计费,有效降低企业的运维压力和使用成本。
230 15
|
3月前
|
开发框架 C# iOS开发
基于C#开源、功能强大、灵活的跨平台开发框架 - Uno Platform
基于C#开源、功能强大、灵活的跨平台开发框架 - Uno Platform
|
3月前
|
网络协议 Unix Linux
精选2款C#/.NET开源且功能强大的网络通信框架
精选2款C#/.NET开源且功能强大的网络通信框架
110 0
|
3月前
|
消息中间件 弹性计算 运维
一图看懂云消息队列 RabbitMQ 版对比开源优势
一张图带您快速了解云消息队列 RabbitMQ 版对比开源版本的显著优势。
|
4月前
|
开发框架 缓存 算法
开源且实用的C#/.NET编程技巧练习宝库(学习,工作,实践干货)
开源且实用的C#/.NET编程技巧练习宝库(学习,工作,实践干货)
|
5月前
|
XML 网络协议 物联网
基于surging的木舟IOT平台如何添加网络组件
【8月更文挑战第30天】在基于 Surging 的木舟 IOT 平台中添加网络组件需经历八个步骤:首先理解 Surging 及平台架构;其次明确组件需求,选择合适技术库;接着创建项目并配置;然后设计实现网络功能;再将组件集成至平台;接着进行详尽测试;最后根据反馈持续优化与维护。具体实施时应参照最新文档调整。
98 10
|
7月前
|
消息中间件 新零售 弹性计算
云消息队列 RabbitMQ 版入门训练营,解锁对比开源优势与零基础实战
欢迎加入「云消息队列 RabbitMQ 版入门训练营」。
192 22