在好例子网,分享、交流、成长!
您当前所在位置:首页C# 开发实例C#语言基础 → C#对接阿里云物联网平台示例源码(NetGadgeteer 温度、湿度、LED)

C#对接阿里云物联网平台示例源码(NetGadgeteer 温度、湿度、LED)

C#语言基础

下载此实例
  • 开发语言:C#
  • 实例大小:0.37M
  • 下载次数:116
  • 浏览次数:990
  • 发布时间:2019-03-24
  • 实例类别:C#语言基础
  • 发 布 人:crazycode
  • 文件格式:.rar
  • 所需积分:2
 相关标签: C# 源码 NET

实例介绍

【实例简介】

【实例截图】

from clipboard

【核心代码】

//阿里云文档: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;
        }
    }
}

标签: C# 源码 NET

实例下载地址

C#对接阿里云物联网平台示例源码(NetGadgeteer 温度、湿度、LED)

不能下载?内容有错? 点击这里报错 + 投诉 + 提问

好例子网口号:伸出你的我的手 — 分享

网友评论

发表评论

(您的评论需要经过审核才能显示)

查看所有0条评论>>

小贴士

感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。

  • 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
  • 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
  • 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
  • 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。

关于好例子网

本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明

;
报警