引言
本段代碼的含義在之前的一篇文章裏有介紹,本文爲完整代碼的展示,之前介紹用的文章,點擊此處即可查看
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();
}
}
}