史上最简单的C#客户端连接阿里云物联网平台

C#客户端连接阿里云物联网平台

创建新项目 Windows窗口应用(.NET Framework)

在这里插入图片描述

管理NuGet程序包

在这里插入图片描述

添加MqttSign.cs

using System;
using System.Security.Cryptography;

namespace WaterSamplePCNet
{
    class CryptoUtil
    {
        public static String hmacSha256(String plainText, String key)
        {
            var encoding = new System.Text.UTF8Encoding();
            byte[] plainTextBytes = encoding.GetBytes(plainText);
            byte[] keyBytes = encoding.GetBytes(key);

            HMACSHA256 hmac = new HMACSHA256(keyBytes);
            byte[] sign = hmac.ComputeHash(plainTextBytes);
            return BitConverter.ToString(sign).Replace("-", string.Empty);
        }
    }
    public class MqttSign
    {
        private String username = "";

        private String password = "";

        private String clientid = "";

        public String getUsername() { return this.username; }

        public String getPassword() { return this.password; }

        public String getClientid() { return this.clientid; }

        public bool calculate(String productKey, String deviceName, String deviceSecret)
        {
            if (productKey == null || deviceName == null || deviceSecret == null)
            {
                return false;
            }

            //MQTT用户名
            this.username = deviceName + "&" + productKey;

            //MQTT密码
            String timestamp = Convert.ToInt64((DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalMilliseconds).ToString();
            String plainPasswd = "clientId" + productKey + "." + deviceName + "deviceName" +
                    deviceName + "productKey" + productKey + "timestamp" + timestamp;
            this.password = CryptoUtil.hmacSha256(plainPasswd, deviceSecret);

            //MQTT ClientId
            this.clientid = productKey + "." + deviceName + "|" + "timestamp=" + timestamp +
                    ",_v=paho-c#-1.0.0,securemode=2,signmethod=hmacsha256|";

            return true;
        }
    }
}

全局变量

        string productKey = "a1X2bEn****";
        string deviceName = "example1";
        string deviceSecret = "ga7XA6KdlEeiPXQPpRbAjOZXwG8y****";
        MqttClient mqttClient = null;

连接

private void connectBtn_Click(object sender, EventArgs e)
        {

            // 计算MQTT连接参数。
            MqttSign sign = new MqttSign();
            sign.calculate(productKey, deviceName, deviceSecret);

            Console.WriteLine("username: " + sign.getUsername());
            Console.WriteLine("password: " + sign.getPassword());
            Console.WriteLine("clientid: " + sign.getClientid());

            // 使用Paho连接阿里云物联网平台。
            int port = 443;
            string broker = productKey + ".iot-as-mqtt.cn-shanghai.aliyuncs.com";

            mqttClient = new MqttClient(broker, port, true, MqttSslProtocols.TLSv1_2, null, null);
            mqttClient.Connect(sign.getClientid(), sign.getUsername(), sign.getPassword());

            Console.WriteLine("Broker: " + broker + " Connected");
        }

订阅

        private void subscribeBtn_Click(object sender, EventArgs e)
        {
            // Paho MQTT消息订阅。
            string topicReply = "/sys/" + productKey + "/" + deviceName + "/thing/event/property/post_reply";

            mqttClient.MqttMsgPublishReceived += MqttPostProperty_MqttMsgPublishReceived;
            mqttClient.Subscribe(new string[] { topicReply }, new byte[] { MqttMsgBase.QOS_LEVEL_AT_MOST_ONCE });
        }

        private static void MqttPostProperty_MqttMsgPublishReceived(object sender, uPLibrary.Networking.M2Mqtt.Messages.MqttMsgPublishEventArgs e)
        {
            Console.WriteLine("reply topic  :" + e.Topic);
            Console.WriteLine("reply payload:" + e.Message.ToString());
        }

发布

        private void publishBtn_Click(object sender, EventArgs e)
        {
            // Paho MQTT消息发布。
            string topic = "/sys/" + productKey + "/" + deviceName + "/thing/event/property/post";
            string message = "{\"id\":\"1\",\"version\":\"1.0\",\"params\":{\"LightSwitch\":0}}";
            mqttClient.Publish(topic, Encoding.UTF8.GetBytes(message));
        }

在这里插入图片描述

  • 12
    点赞
  • 57
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 6
    评论
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小康师兄

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值