WPF mqtt连阿里云

  •  安装M2Mqtt程序包

  •  拿设备三要数

 


  • 上代码

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using ThirdParty.Json.LitJson;
using uPLibrary.Networking.M2Mqtt;
using uPLibrary.Networking.M2Mqtt.Messages;
using Water_System.ViewModels;

namespace Water_System.Base
{
    public class Mqtt_Service
    {

        static string ProductKey = "a1q3cmCTxD5";  
        static string DeviceName = "WPF_";   
        static string DeviceSecret = "a35b319469de7150b5ab8b2574b85865";  
        static string RegionId = "cn-shanghai";

        static string PubTopic ="/sys"+ "/" + ProductKey + "/" + DeviceName + "/thing/event/property/post";
        //static string SubTopic = "/"+"a1q3cmCTxD5/App_/user/Up_data_wpf";
        static string SubTopic = "/sys/a1q3cmCTxD5/WPF_/thing/event/property/post";
        public static MqttClient client;
        public static  JsonData ph;
        public static int flag = 0,Trycount=0;


        static string mqttUserName, targetServer, mqttPassword, mqttClientId;
        static string s = "params:{LED:1}";

        public static string receive_message = "";

        private static bool IsConnect=true,_Toclose = false;


          //发布消息
        public static void publish(int i)
        {
            if (i == 1) {
     s = "{\"method\" : \"thing.event.property.post\",\"params\":{\"water_PH\":1}}";}
     else {
              s = "{\"params\":{\"water_PH\":0}}"; }
            
   
            String content = s;
            client.Publish(PubTopic, Encoding.ASCII.GetBytes(content));
        }

           //订阅topic
        public static void subtopic()
        {
            client.Subscribe(new string[] { SubTopic }, new byte[] {0});
        }

           //连接mqtt
        public static void ConnectMqtt()
        {
            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";
            mqttClientId = clientId + "|securemode=3,signmethod=" + signmethod + ",timestamp=" + t + "|";
            targetServer = ProductKey + ".iot-as-mqtt." + RegionId + ".aliyuncs.com";
            Dictionary<string, string> dict = new Dictionary<string, string>();
            dict.Add("productKey", ProductKey);
            dict.Add("deviceName", DeviceName);
            dict.Add("clientId", clientId);
            dict.Add("timestamp", t);
            mqttUserName = DeviceName + "&" + ProductKey;
            mqttPassword = IotSignUtils.sign(dict, DeviceSecret, signmethod);
            client = new MqttClient(targetServer);
            client.ProtocolVersion = MqttProtocolVersion.Version_3_1_1;
            client.Connect(mqttClientId, mqttUserName, mqttPassword, true, 60);

            //订阅
          // client.Subscribe(new string[] { SubTopic }, new byte[] { 0 });

            if (client.IsConnected)
            {
                Trace.WriteLine("my debug message");
            }
            Task.Run(() => {
               client.MqttMsgPublishReceived += Client_MqttMsgPublishReceived; 
                //委托可放置其他地方
            });
            
        }

        //接收数据
        public  static void Client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
        {
            // handle message received
            string topic = e.Topic;
            string message = System.Text.Encoding.Default.GetString(e.Message);
            System.Console.WriteLine(message);
            //解析json数据
            JsonData JsonData1 = JsonMapper.ToObject(message);
          
        }

    //加密
    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());
            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();
        }
    }

}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值