基本信息
源码名称:C#对接阿里云物联网平台示例源码(NetGadgeteer 温度、湿度、LED)
源码大小:0.37M
文件格式:.rar
开发语言:C#
更新时间:2019-03-24
   友情提示:(无需注册或充值,赞助后即可获取资源下载链接)

     嘿,亲!知识可是无价之宝呢,但咱这精心整理的资料也耗费了不少心血呀。小小地破费一下,绝对物超所值哦!如有下载和支付问题,请联系我们QQ(微信同号):78630559

本次赞助数额为: 2 元 
   源码介绍

//阿里云文档:https://help.aliyun.com/document_detail/30539.html?spm=5176.doc42743.6.574.ewvmlO
//           https://open.aliplus.com/doc_pass/mqtt_mode.html

//#define TLS_DirectConnection
using System;
using Microsoft.SPOT;
using uPLibrary.Networking.M2Mqtt;
using uPLibrary.Networking.M2Mqtt.Exceptions;
using uPLibrary.Networking.M2Mqtt.Messages;
using System.Threading;
using Microsoft.SPOT.Hardware;
using System.Text;
using YFSoft.Security.Cryptography;
using YFSoft.IO;
using YFSoft.NetMF;

namespace YFMQTT
{
    public class Program
    {
        //三元组信息
        const string productKey = "a12F0j8PYhD";
        const string deviceName = "yfth";
        const string deviceSecret = "TC39z10E5V43j6XIG7XXug3PXNCovJQd";

        const string hostServer = productKey   ".iot-as-mqtt.cn-shanghai.aliyuncs.com";
        //--//
        const string update_topic = "/" productKey "/" deviceName "/update";
        const string error_topic = "/"   productKey   "/"   deviceName   "/update/error";
        const string get_topic = "/"   productKey   "/"   deviceName   "/get";

        const string post_topic = "/sys/"   productKey   "/"   deviceName   "/thing/event/property/post";
  
        static int SendCount = 0, ReceiveCount = 0, ErrorCount = 0;
        static OutputPort led = new OutputPort((Cpu.Pin)(7*16 9),false);  //PH9

        #region    //CA证书
        static string caCert =
        "-----BEGIN CERTIFICATE-----\r\n"  
        "MIIEmjCCBAOgAwIBAgIJAKps0iIhwLzrMA0GCSqGSIb3DQEBDQUAMGcxGzAZBgNV\r\n"  
        "BAMMEkFsaXl1biBNUVRUIGJyb2tlcjETMBEGA1UECgwKYWxpeXVuLmNvbTEUMBIG\r\n"  
        "A1UECwwLZ2VuZXJhdGUtQ0ExHTAbBgkqhkiG9w0BCQEWDmlvdEBhbGl5dW4uY29t\r\n"  
        "MB4XDTE2MDQxNTAyMDU0M1oXDTI2MDQxMzAyMDU0M1owWzEPMA0GA1UEAwwGc2Vy\r\n"  
        "dmVyMRMwEQYDVQQKDAphbGl5dW4uY29tMRQwEgYDVQQLDAtnZW5lcmF0ZS1DQTEd\r\n"  
        "MBsGCSqGSIb3DQEJARYOaW90QGFsaXl1bi5jb20wgZ8wDQYJKoZIhvcNAQEBBQAD\r\n"  
        "gY0AMIGJAoGBAK5M/4eU9LD IpzQTFwHSNUPPMNwtDxg3ZOdGszJFdA4vgrVm/hn\r\n"  
        "/TcHfdKKRDyUzwJb1FbNYpdNlXK5l/qLKkY WpzEzJFjUMV9O40cbMXPyQ1VjbLl\r\n"  
        "SvlCGkmVTv8Q1B9fitzbKYGDznKBYES5P8IadvHmm74DtD9uQks6i62HAgMBAAGj\r\n"  
        "ggJYMIICVDAMBgNVHRMBAf8EAjAAMBEGCWCGSAGG EIBAQQEAwIGQDALBgNVHQ8E\r\n"  
        "BAMCBeAwLAYJYIZIAYb4QgENBB8WHUFsaXl1biBJb1QgQnJva2VyIENlcnRpZmlj\r\n"  
        "YXRlMB0GA1UdDgQWBBQcOXMYLcexVRQ6MQKF9gxHYstSTDCBmQYDVR0jBIGRMIGO\r\n"  
        "gBQOqXNDKdO1PQ4xP/tTwnR/gQbuDqFrpGkwZzEbMBkGA1UEAwwSQWxpeXVuIE1R\r\n"  
        "VFQgYnJva2VyMRMwEQYDVQQKDAphbGl5dW4uY29tMRQwEgYDVQQLDAtnZW5lcmF0\r\n"  
        "ZS1DQTEdMBsGCSqGSIb3DQEJARYOaW90QGFsaXl1bi5jb22CCQCpKzLXM7SzvTCB\r\n"  
        "sgYDVR0RBIGqMIGnhxD gAAAAAAAAD4Vwv/ 12GohwQeCbCFhxAgAh4JsBQADT4V\r\n"  
        "wv/ 12GohxAgAh4JsBQADVTlgzaCoNNVhxD wAAAAAAADT4Vwv/ 12GohxD wAAA\r\n"  
        "AAAADcmk/090y3MlhxD gAAAAAAAAGSc0f/ 8tX6hwTAqGMBhwQK0zcChwQKJYEC\r\n"  
        "hwR/AAABhxAAAAAAAAAAAAAAAAAAAAABgglsb2NhbGhvc3QwgYUGA1UdIAR MHww\r\n"  
        "egYDKwUIMHMwHAYIKwYBBQUHAgEWEGh0dHA6Ly9sb2NhbGhvc3QwUwYIKwYBBQUH\r\n"  
        "AgIwRzAQFglPd25UcmFja3MwAwIBARozVGhpcyBDQSBpcyBmb3IgQWxpeXVuIE1R\r\n"  
        "VFQgYnJva2VyIGluc3RhbGxhdGlvbiBvbmx5MA0GCSqGSIb3DQEBDQUAA4GBAJdV\r\n"  
        "BfFYEz/6bzHrAr/6bymO7iwA5qyUDd8WQo1G3D7QklN83A 5GMVK4E8bL8jtCbFv\r\n"  
        "XO0u6hLN4sw0oE0Ntm2M8y 7 GaO6BAOotb2nwecMS67Ltn98j6rF3WLK2opO6Jr\r\n"  
        "G5AeSj86gtAhr2ZVdfGpvWj74 gK4nG7cHnaiZOf\r\n"  
        "-----END CERTIFICATE-----\r\n";
        #endregion

        public static void Main()
        {
            Debug.Print("------ Aliyun MQTT ------");

            GeneralStream gs = new GeneralStream();
            if (gs.Open("DHT11") <= 0)
            {
                Debug.Print("Open DHT11 failed!");
                return;
            }

            #region Ntp网络校时
            string[] NtpSever = new string[] { "s2c.time.edu.cn", "time.windows.com", "s2g.time.edu.cn" };
            Utility.SetLocalTime(new DateTime(2050, 1, 1, 0, 0, 0));  //先强制设置一个,满足:设备时间 9小时 > 服务器时间即可 
            for (int i = 0; i < 3; i  )
            {
                if (DamperMonitNet.Ntp.UpdateTimeFromNtpServer(NtpSever[i], 8)) break;
            }
            Debug.Print(DateTime.Now.ToString());
            #endregion

            //--//
            while (true)
            {
#if TLS_DirectConnection
                //目前阿里云支持TLSV1.0,TLSV1.1,TLSV1.2 版本的协议来建立安全连接
                MqttClient mqttClient = new MqttClient(
                     hostServer, 1883, true,
                     new System.Security.Cryptography.X509Certificates.X509Certificate(Encoding.UTF8.GetBytes(caCert)),
                     null, //new System.Security.Cryptography.X509Certificates.X509Certificate(Encoding.UTF8.GetBytes(clientCert)),
                     MqttSslProtocols.TLSv1_0
                 );
#else
                MqttClient mqttClient = new MqttClient(
                  hostServer, 1883, false,
                  null,
                  null, //new System.Security.Cryptography.X509Certificates.X509Certificate(Encoding.UTF8.GetBytes(clientCert)),
                  MqttSslProtocols.None
              );
#endif  
                //CPU ID
                LargeBuffer lb = new LargeBuffer(1024);
                (new LargeBufferMarshaller(1003)).UnMarshalBuffer(ref lb);
                string CpuID = "";
                for (int i = 0; i < 12; i  ) CpuID  = lb.Bytes[i].ToString("X2");

                string clientId = CpuID;
                string timestamp = DateTime.Now.Ticks.ToString();
#if TLS_DirectConnection
                string mqttClientId = clientId   "|securemode=2,signmethod=hmacsha1,timestamp="   timestamp   "|";
#else
                string mqttClientId = clientId   "|securemode=3,signmethod=hmacsha1,timestamp="   timestamp   "|";
#endif
                string mqttUsername = deviceName   "&"   productKey;
                string content = "clientId"   clientId   "deviceName"   deviceName   "productKey"   productKey   "timestamp"   timestamp;
                HMACSHA1 hmacsha1 = new HMACSHA1();
                byte[] Key = Encoding.UTF8.GetBytes(deviceSecret);
                byte[] dataBuffer = Encoding.UTF8.GetBytes(content);
                byte[] hashBytes = hmacsha1.ComputeHash(Key, dataBuffer);
                string mqttPassword = "";
                for (int i = 0; i < hashBytes.Length; i  )
                {
                    mqttPassword  = hashBytes[i].ToString("X2");
                }
                mqttClient.Connect(mqttClientId, mqttUsername, mqttPassword, false, 10000);

                //连接成功
                if (mqttClient.IsConnected)
                {
                    mqttClient.ConnectionClosed  = new MqttClient.ConnectionClosedEventHandler(mqttClient_ConnectionClosed);
                    mqttClient.MqttMsgPublished  = new MqttClient.MqttMsgPublishedEventHandler(mqttClient_MqttMsgPublished);
                    mqttClient.MqttMsgPublishReceived  = new MqttClient.MqttMsgPublishEventHandler(mqttClient_MqttMsgPublishReceived);
                    mqttClient.MqttMsgSubscribed  = new MqttClient.MqttMsgSubscribedEventHandler(mqttClient_MqttMsgSubscribed);
                    mqttClient.MqttMsgUnsubscribed  = new MqttClient.MqttMsgUnsubscribedEventHandler(mqttClient_MqttMsgUnsubscribed);

                    //消息订阅
                    string[] topics = new string[] { get_topic, error_topic };
                    //0-至多一次 1-至少一次  2- 确保一次(不支持)
                    byte[] qosLevels = new byte[] { 1, 1 };
                    mqttClient.Subscribe(topics, qosLevels);

                    while (mqttClient.IsConnected)
                    {
                        try
                        {
                            byte[] bytData = new byte[4];
                             float T = 0;
                             float H = 0;
                             int ret = gs.IOControl((int)(6*16 11)); //PG11
                             if (ret != -1)
                             {
                                 bytData[0] = (byte)(ret & 0xFF);
                                 bytData[1] = (byte)(ret >> 8 & 0xFF);
                                 bytData[2] = (byte)(ret >> 16 & 0xFF);
                                 bytData[3] = (byte)(ret >> 24 & 0xFF);

                                 H = Byte2Float(bytData[0], bytData[1]);
                                 T = Byte2Float(bytData[2], bytData[3]);
                                 Debug.Print("H = "   H.ToString()   " T = "   T.ToString());

                                 string payload_json = "{"  
                                "\"id\": "   DateTime.Now.Ticks   ","  
                                "\"params\":{"  
                                   "\"temperature\":"   T   ","  
                                   "\"humidity\":"   H   ","  
                                "},"  
                                "\"method\":\"thing.event.property.post\""  
                                "}";

                                 string Data = Guid.NewGuid().ToString();
                                 mqttClient.Publish(post_topic, Encoding.UTF8.GetBytes(payload_json), MqttMsgBase.QOS_LEVEL_AT_LEAST_ONCE, false);
                                 Debug.Print(payload_json);
                             }
                        }
                        catch {   ErrorCount; break; }

                        string info = "MQTT[S]"   SendCount   " [R]"   ReceiveCount   " [E]"   ErrorCount;
                        Debug.Print(info);
                        System.Threading.Thread.Sleep(60000);  //1分钟访问一次 一天1440次
                    }
                }

                //释放相关资源
                try
                {
                    mqttClient.ConnectionClosed -= new MqttClient.ConnectionClosedEventHandler(mqttClient_ConnectionClosed);
                    mqttClient.MqttMsgPublished -= new MqttClient.MqttMsgPublishedEventHandler(mqttClient_MqttMsgPublished);
                    mqttClient.MqttMsgPublishReceived -= new MqttClient.MqttMsgPublishEventHandler(mqttClient_MqttMsgPublishReceived);
                    mqttClient.MqttMsgSubscribed -= new MqttClient.MqttMsgSubscribedEventHandler(mqttClient_MqttMsgSubscribed);
                    mqttClient.MqttMsgUnsubscribed -= new MqttClient.MqttMsgUnsubscribedEventHandler(mqttClient_MqttMsgUnsubscribed);
                    mqttClient.Disconnect();
                }
                catch { }
                //3秒后重连MQTT
                System.Threading.Thread.Sleep(3000);
            }
        }

        //取消订阅完成
        static void mqttClient_MqttMsgUnsubscribed(object sender, uPLibrary.Networking.M2Mqtt.Messages.MqttMsgUnsubscribedEventArgs e)
        {
            Debug.Print("MqttMsgUnsubscribed:"   e.MessageId.ToString());
        }

        //消息订阅完成
        static void mqttClient_MqttMsgSubscribed(object sender, uPLibrary.Networking.M2Mqtt.Messages.MqttMsgSubscribedEventArgs e)
        {
            Debug.Print("MqttMsgSubscribed:"   e.MessageId.ToString());      
        }

        //信息接收完成
        static void mqttClient_MqttMsgPublishReceived(object sender, uPLibrary.Networking.M2Mqtt.Messages.MqttMsgPublishEventArgs e)
        {
            ReceiveCount  ;
            Debug.Print("MqttMsgPublishReceived:"   e.Topic);

            string json = "";
            if (e.Message.Length > 0)
            {
                //{"method":"thing.service.property.set","id":"196011725","params":{"LED":1},"version":"1.0.0"}
                json = new string(System.Text.UTF8Encoding.UTF8.GetChars(e.Message));
                Debug.Print("Message:"   json);

                string strLED  =json.Substring(json.IndexOf("LED") 5,1);
                led.Write((strLED == "1"));
            }
        }

        //消息发布成功
        static void mqttClient_MqttMsgPublished(object sender, uPLibrary.Networking.M2Mqtt.Messages.MqttMsgPublishedEventArgs e)
        {
            SendCount  ;
            Debug.Print("MqttMsgPublished:"   e.MessageId.ToString());
        }

        //连接断开
        static void mqttClient_ConnectionClosed(object sender, EventArgs e)
        {
            Debug.Print("ConnectionClosed!!!");
              ErrorCount;
        }

        static float Byte2Float(byte data1, byte data2)
        {
            float temp1 = data1;
            float temp2 = 0;
            if (data2 < 10)
            {
                temp2 = (float)(data2 / 10.0);
            }
            else if (data2 < 100)
            {
                temp2 = (float)(data2 / 100.0);
            }
            else
            {
                temp2 = (float)(data2 / 1000.0);
            }
            return temp1   temp2;
        }
    }
}