.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盲盒。
相关文章
|
1月前
|
XML 网络协议 物联网
基于surging的木舟IOT平台如何添加网络组件
【8月更文挑战第30天】在基于 Surging 的木舟 IOT 平台中添加网络组件需经历八个步骤:首先理解 Surging 及平台架构;其次明确组件需求,选择合适技术库;接着创建项目并配置;然后设计实现网络功能;再将组件集成至平台;接着进行详尽测试;最后根据反馈持续优化与维护。具体实施时应参照最新文档调整。
45 10
|
2月前
|
C# 开发者 Windows
在VB.NET项目中使用C#编写的代码
在VB.NET项目中使用C#编写的代码
41 0
|
28天前
|
SQL 存储 关系型数据库
C#一分钟浅谈:使用 ADO.NET 进行数据库访问
【9月更文挑战第3天】在.NET开发中,与数据库交互至关重要。ADO.NET是Microsoft提供的用于访问关系型数据库的类库,包含连接数据库、执行SQL命令等功能。本文从基础入手,介绍如何使用ADO.NET进行数据库访问,并提供示例代码,同时讨论常见问题及其解决方案,如连接字符串错误、SQL注入风险和资源泄露等,帮助开发者更好地利用ADO.NET提升应用的安全性和稳定性。
62 6
|
25天前
|
算法 Java 中间件
C#/.NET/.NET Core优质学习资料,干货收藏!
C#/.NET/.NET Core优质学习资料,干货收藏!
|
25天前
|
人工智能 开发框架 算法
C#/.NET/.NET Core技术前沿周刊 | 第 2 期(2024年8.19-8.25)
C#/.NET/.NET Core技术前沿周刊 | 第 2 期(2024年8.19-8.25)
|
25天前
|
缓存 开发框架 算法
C#/.NET这些实用的编程技巧你都会了吗?
C#/.NET这些实用的编程技巧你都会了吗?
|
25天前
|
传感器 应用服务中间件 Linux
C#/.NET/.NET Core技术前沿周刊 | 第 3 期(2024年8.26-8.31)
C#/.NET/.NET Core技术前沿周刊 | 第 3 期(2024年8.26-8.31)
|
25天前
|
人工智能 算法 C#
C#/.NET/.NET Core技术前沿周刊 | 第 1 期(2024年8.12-8.18)
C#/.NET/.NET Core技术前沿周刊 | 第 1 期(2024年8.12-8.18)
|
2月前
|
JSON C# 开发者
💡探索C#语言进化论:揭秘.NET开发效率飙升的秘密武器💼
【8月更文挑战第28天】C#语言凭借其强大的功能与易用性深受开发者喜爱。伴随.NET平台演进,C#持续引入新特性,如C# 7.0的模式匹配,让处理复杂数据结构更直观简洁;C# 8.0的异步流则使异步编程更灵活高效,无需一次性加载全部数据至内存。通过示例展示了模式匹配简化JSON解析及异步流实现文件逐行读取的应用。此外,C# 8.0还提供了默认接口成员和可空引用类型等特性,进一步提高.NET开发效率与代码可维护性。随着C#的发展,未来的.NET开发将更加高效便捷。
44 1
|
2月前
|
缓存 运维 前端开发
阿里云云效操作报错合集之如何解决在使用流水线构建net8应用时遇到无法构建的报错
本合集将整理呈现用户在使用过程中遇到的报错及其对应的解决办法,包括但不限于账户权限设置错误、项目配置不正确、代码提交冲突、构建任务执行失败、测试环境异常、需求流转阻塞等问题。阿里云云效是一站式企业级研发协同和DevOps平台,为企业提供从需求规划、开发、测试、发布到运维、运营的全流程端到端服务和工具支撑,致力于提升企业的研发效能和创新能力。

热门文章

最新文章