通过阿里云的ProductKey,DeviceName,DeviceSecret,RegionId三元组数据,执行以下代码,
app.config文件
<add name="ProductKey" connectionString="a1eAKoQBN"/> <add name="DeviceName" connectionString="test"/> <add name="DeviceSecret" connectionString="2d9c5027f05f8e047dba4ef7bd8e24"/> <add name="RegionId" connectionString="cn-shanghai"/> <add name="PubTopic" connectionString="user/update"/> <add name="SubTopic" connectionString="user/get"/>main文件
using uPLibrary.Networking.M2Mqtt; using uPLibrary.Networking.M2Mqtt.Messages; //iot private static readonly string ProductKey = ConfigurationManager.ConnectionStrings["ProductKey"].ConnectionString; private static readonly string DeviceName = ConfigurationManager.ConnectionStrings["DeviceName"].ConnectionString; private static readonly string DeviceSecret = ConfigurationManager.ConnectionStrings["DeviceSecret"].ConnectionString; private static readonly string RegionId = ConfigurationManager.ConnectionStrings["RegionId"].ConnectionString; private static readonly string PubTopicUser = "/" + ProductKey + "/" + DeviceName + "/" + ConfigurationManager.ConnectionStrings["PubTopic"].ConnectionString; private static readonly string SubTopicUser = "/" + ProductKey + "/" + DeviceName + "/" + ConfigurationManager.ConnectionStrings["SubTopic"].ConnectionString; private static readonly string PubTopic = "/sys/" + ProductKey + "/" + DeviceName + "/" + "thing/event/property/post"; private static readonly string SubTopic = "/sys/" + ProductKey + "/" + DeviceName + "/" + "thing/service/property/set"; 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> { { "productKey", ProductKey }, { "deviceName", DeviceName }, { "clientId", clientId }, { "timestamp", t } }; string mqttBrokerAddress = ProductKey + ".iot-as-mqtt." + RegionId + ".aliyuncs.com"; string mqttClientId = clientId + "|securemode=3,signmethod=" + signmethod + ",timestamp=" + t + "|"; string mqttUserName = DeviceName + "&" + ProductKey; string mqttPassword = Sign(dict, DeviceSecret, signmethod);