.NET平台设备使用C#语言接入阿里云IoT

简介: 1. 准备工作 1.1 注册阿里云账号 使用淘宝账号或手机号,开通阿里云账号,并通过实名认证(可以用支付宝认证) 1.2 免费开通IoT物联网套件 产品官网 https://www.aliyun.com/product/iot 1.

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

iot-tech-weixin.png | center | 115x114

相关实践学习
部署Stable Diffusion玩转AI绘画(GPU云服务器)
本实验通过在ECS上从零开始部署Stable Diffusion来进行AI绘画创作,开启AIGC盲盒。
相关文章
|
2月前
|
存储 算法 安全
.NET 平台 SM2 国密算法 License 证书生成深度解析
授权证书文件的后缀通常取决于其编码格式和具体用途。本文档通过一个示例程序展示了如何在 .NET 平台上使用国密 SM2 算法生成和验证许可证(License)文件。该示例不仅详细演示了 SM2 国密算法的实际应用场景,还提供了关于如何高效处理大规模许可证文件生成任务的技术参考。通过对不同并发策略的性能测试,开发者可以更好地理解如何优化许可证生成流程,以满足高并发和大数据量的需求。 希望这段描述更清晰地传达了程序的功能和技术亮点。
183 13
.NET 平台 SM2 国密算法 License 证书生成深度解析
|
21天前
|
SQL 小程序 API
如何运用C#.NET技术快速开发一套掌上医院系统?
本方案基于C#.NET技术快速构建掌上医院系统,结合模块化开发理念与医院信息化需求。核心功能涵盖用户端的预约挂号、在线问诊、报告查询等,以及管理端的排班管理和数据统计。采用.NET Core Web API与uni-app实现前后端分离,支持跨平台小程序开发。数据库选用SQL Server 2012,并通过读写分离与索引优化提升性能。部署方案包括Windows Server与负载均衡设计,确保高可用性。同时针对API差异、数据库老化及高并发等问题制定应对措施,保障系统稳定运行。推荐使用Postman、Redgate等工具辅助开发,提升效率与质量。
|
2月前
|
物联网 数据挖掘 BI
基于阿里云物联网平台(IoT)的智能家居系统开发与部署
随着物联网技术的发展,智能家居成为提升生活品质的重要方向。阿里云物联网平台提供设备接入、数据管理及应用开发能力,支持亿级设备接入、高效数据管理和灵活应用开发,确保系统安全。本文通过实战案例展示如何基于该平台构建智能家居系统,涵盖设备接入、远程控制、场景联动与数据分析等功能,助力企业快速部署智能家居解决方案。
|
4月前
|
开发框架 搜索推荐 算法
一个包含了 50+ C#/.NET编程技巧实战练习教程
一个包含了 50+ C#/.NET编程技巧实战练习教程
184 18
|
4月前
|
缓存 算法 安全
精选10款C#/.NET开发必备类库(含使用教程),工作效率提升利器!
精选10款C#/.NET开发必备类库(含使用教程),工作效率提升利器!
143 12
|
4月前
|
Linux API C#
基于 .NET 开发的多功能流媒体管理控制平台
基于 .NET 开发的多功能流媒体管理控制平台
83 9
|
4月前
|
开发框架 人工智能 .NET
C#/.NET/.NET Core拾遗补漏合集(24年12月更新)
C#/.NET/.NET Core拾遗补漏合集(24年12月更新)
|
4月前
|
开发框架 算法 .NET
C#/.NET/.NET Core技术前沿周刊 | 第 15 期(2024年11.25-11.30)
C#/.NET/.NET Core技术前沿周刊 | 第 15 期(2024年11.25-11.30)
|
4月前
|
开发框架 Cloud Native .NET
C#/.NET/.NET Core技术前沿周刊 | 第 16 期(2024年12.01-12.08)
C#/.NET/.NET Core技术前沿周刊 | 第 16 期(2024年12.01-12.08)
|
4月前
|
开发框架 监控 .NET
C#进阶-ASP.NET WebForms调用ASMX的WebService接口
通过本文的介绍,希望您能深入理解并掌握ASP.NET WebForms中调用ASMX WebService接口的方法和技巧,并在实际项目中灵活运用这些技术,提高开发效率和应用性能。
179 5