阿里云上通过MQTT协议,实现多设备的相互数据的稳定动态传输和使用(本地设备均采用c#窗体代码)第二篇-----本地设备开发(Demo)

引言

  本段代码的含义在之前的一篇文章里有介绍,本文为完整代码的展示,之前介绍用的文章,点击此处即可查看

Demo代码:

using System;
using System.Net;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using uPLibrary.Networking.M2Mqtt;
using uPLibrary.Networking.M2Mqtt.Messages;
using System.Windows.Forms;
using System.Security.Cryptography;
namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        //阿里云的数据
        static string ProductKey = "***";//输入自己的ProductKey
        static string DeviceName = "***";//输入自己的DeviceName
        static string DeviceSecret = "***";//输入自己的DeviceSecret
        static string RegionId = "cn-shanghai";
        static string PubTopic = "/" + ProductKey + "/" + DeviceName + "/user/update";
        static string SubTopic = "/" + ProductKey + "/" + DeviceName + "/user/get";
        public Form1()
        {
            InitializeComponent();
            System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;
        }
        private void label1_Click(object sender, EventArgs e)
        {

        }
        private void button1_Click(object sender, EventArgs e)
        {
            label3.Text = "数据已经上传!";
            //开始连接阿里云
            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);
        }
        public 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;

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

            //发布消息,发布的消息为我们在textBox1上的Text
            String content = textBox1.Text;
            //他上传的数据需要时byte[],所以我们先需要将string类转换成byte[]
            byte[] by1 = System.Text.Encoding.ASCII.GetBytes(content);
            var id = client.Publish(PubTopic, by1);
        }
        public void Client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
        {
            //对获得的message的处理
            string topic = e.Topic;
            string message = Encoding.ASCII.GetString(e.Message);//从被订阅端获取消息
            int length = message.Length;//我们先得到这条message的长度,
            //因为是string所以调用他的length函数就可以了
            label2.Text = message.Substring(0, length);//label3原先是null,
            //后来就会变成message的内容,从头开始读,长度就是length
        }
    }
    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();
        }
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值