.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

相关实践学习
基于阿里云DeepGPU实例,用AI画唯美国风少女
本实验基于阿里云DeepGPU实例,使用aiacctorch加速stable-diffusion-webui,用AI画唯美国风少女,可提升性能至高至原性能的2.6倍。
相关文章
|
4月前
|
传感器 物联网 网络架构
ENS、IoT设备、X86、ARM
ENS(Enterprise Name Service)是企业名称服务,是一种为物联网设备提供命名和寻址服务的技术。ENS通过为物联网设备分配唯一的名称和地址,使得物联网设备可以被网络中的其他设备和服务所识别和访问。 IoT设备(Internet of Things device)是连接到互联网的物理设备,可以收集和共享数据,用于监测、控制和优化各种业务流程和操作。IoT设备包括各种传感器、执行器、网关和路由器等。
40 2
|
6月前
|
C# 对象存储
C#上传阿里云OSS工具类AliOSSTool
C#上传阿里云OSS工具类AliOSSTool
244 0
|
2月前
|
网络协议 物联网 5G
K3S 系列文章 -5G IoT 网关设备 POD 访问报错 DNS 'i/o timeout' 分析与解决
K3S 系列文章 -5G IoT 网关设备 POD 访问报错 DNS 'i/o timeout' 分析与解决
|
28天前
|
数据采集 存储 监控
.NET智慧手术室管理平台源码
术前访视记录单、手术风险评估表、手术安全核查表、自费药品或耗材、麻醉知情同意书、麻醉记录单、分娩镇痛记录单、麻醉复苏单、术后镇痛记录单、术后访视记录单、压伤风险评估量表、手术清点记录单、护理记录单、输血护理记录单。
30 0
|
1月前
深入.net平台的分层开发
深入.net平台的分层开发
56 0
|
2月前
|
SQL 数据采集 分布式计算
阿里云数据湖支持哪些语言
阿里云数据湖支持哪些语言
16 1
|
4月前
|
JavaScript Java PHP
阿里云GPU云服务器支持哪些语言
阿里云GPU云服务器支持哪些语言
|
4月前
|
Web App开发 开发框架 .NET
asp.net基于WEB层面的云LIS系统平台源码
结合当今各检验科管理及实验室规模的不同状况,充分吸收当今IT科技的最新成就,开发出以高度产品化、功能强大、极易实施操作、并不断升级换代为主要特点的LIS系统。彻底解决检验科的信息孤岛,全面实现全院信息互通互联、高度共享,并为检验科的规范化管理提供了有力工具。
41 0
|
4月前
|
Web App开发 开发框架 .NET
asp.net基于WEB层面的区域云LIS系统平台源码
asp.net基于WEB层面的区域云LIS系统平台源码
49 1
|
4月前
|
开发框架 小程序 数据可视化
基于.NET、Uni-App开发支持多平台的小程序商城系统 - CoreShop
基于.NET、Uni-App开发支持多平台的小程序商城系统 - CoreShop