乐趣区

关于物联网:NET平台设备使用C语言接入阿里云IoT设备接入类

1. 筹备工作

1.1 注册阿里云账号

应用淘宝账号或手机号,开明阿里云账号,并通过实名认证 (能够用支付宝认证)

1.2 收费开明 IoT 物联网套件

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

1.3 软件开发环境语言

  • C#
  • 工具 Visual Studio IDE

2. IoT 平台云端开发

2.1 创立根底版产品

产品信息

音讯通信 Topic

2.2 注册设施

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

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. 运行后果

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

至此,实现了.NET 平台设施 C# 语言接入阿里云 IoT 物联网云平台的开发实际

物联网平台产品介绍详情:​​https://www.aliyun.com/product/iot/iot_instc_public_cn​​

             阿里云物联网平台客户交换群 
退出移动版