概述
- 安装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();
}
}
}
最后
以上就是踏实时光为你收集整理的WPF mqtt连阿里云的全部内容,希望文章能够帮你解决WPF mqtt连阿里云所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复