.NET Core 跨平台物联网开发:设置委托事件(二)

系列教程目录

 (一) 连接阿里云IOT

 (二) 设置委托事件

 (三) 上报属性

 (四)  SDK文档 属性、方法、委托、类

 http://pan.whuanle.cn/index.php?dir=uploads/阿里云IOT/AliIOTXFclient-dll类库&response

下载三个库,头部引入 即可使用

using AliIOTXFClient;

示例下载地址

http://pan.whuanle.cn/index.php?dir=uploads/阿里云IOT/demo示例

本章示例 AliIOTXF.Twe

生命周期

 

事件类型

目前只设置了五个委托事件

XFMQTT.ConnectionClosedEventHandler 
XFMQTT.PubedEventHandler
XFMQTT.PubEventHandler
XFMQTT.SubedEventHandler
XFMQTT.UnSubedEventHandler
委托 说明
XFMQTT.PubEventHandler 订阅回调 - 当收到服务器消息时
XFMQTT.PubedEventHandler 当 QOS=1或2时,收到订阅触发
XFMQTT.SubedEventHandler 向服务器发布 Topic 时
XFMQTT.SubedEventHandler 向服务器发布 Topic 失败时
XFMQTT.ConnectionClosedEventHandler 断开连接

MQTT是一种可靠的消息推送协议,QOS保证了消息必须完整地推送给另一端,关于QOS具体可以百度~

  • QOS = 0 ,最多一次
  • QOS = 1,至少一次
  • QOS = 2,只有一次

代表消息推送地可靠程度,当 QOS = 1是,在网络波动等情况下,可能会存在多次重复的一次推送。

 

使用默认的委托方法:

            // 使用默认的委托事件
            client.UseDefaultEventHandler();

 通过上一篇文章,程序已经可以运行、连接到阿里云服务器,并且可以订阅发布消息。

这些操作都会触发事件,通过 UseDefaultEventHandler() 方法,使用的默认的方法绑定到事件。

自定义事件方法

删除 这一行代码

client.UseDefaultEventHandler();

头部引入

using uPLibrary.Networking.M2Mqtt.Messages;

注意,这五个委托方法的参数是不一样的。 

 

XFMQTT.PubEventHandler

订阅回调 - 当收到服务器消息时触发

委托方法如下

         委托方法(object sender, MqttMsgPublishEventArgs e)
        {

        }

MqttMsgPublishEventArgs 是与接收消息有关的对象,其属性如下:

        // message topic
        private string topic;
        // message data
        private byte[] message;
        // duplicate delivery
        private bool dupFlag;
        // quality of service level
        private byte qosLevel;
        // retain flag
        private bool retain;   

SDK 默认的委托方法

        public void Default_PubEventHandler(object sender, MqttMsgPublishEventArgs e)
        {
            // handle message received
            string topic = e.Topic;
            string message = Encoding.ASCII.GetString(e.Message);
            Console.WriteLine("- - - - - - - - - - ");
            Console.WriteLine("get topic message,Date: " + DateTime.Now.ToLongTimeString());
            Console.WriteLine("topic: " + topic);
            Console.WriteLine("get messgae :\n" + message);
        }

那么我们来写一个自定义委托方法

里面的怎么写都行,方法名称随意

        public static void 收到消息(object sender, MqttMsgPublishEventArgs e)
        {
            Console.WriteLine("topic名称:"+e.Topic);
            Console.WriteLine("接收时间:" + DateTime.Now.ToLongDateString());
            Console.WriteLine("消息内容:\n"+Encoding.ASCII.GetString(e.Message));
        }

在删除 client.UseDefaultEventHandler(); 的位置加上

client.PubEventHandler += 收到消息;

XFMQTT.PubedEventHandler

当 QOS=1或2时,收到订阅触发

原型

委托方法(object sender, MqttMsgPublishedEventArgs e)
    {

    }

 MqttMsgPublishedEventArgs 属性

        // message identifier
        ushort messageId;

        // published flag
        bool isPublished;

SDK 默认方法

        public void Default_PubedEventHandler(object sender, MqttMsgPublishedEventArgs e)
        {
            Console.WriteLine("- - - - - - - - - - ");
            Console.WriteLine("published,Date: " + DateTime.Now.ToLongTimeString());
            Console.WriteLine("MessageId: " + e.MessageId + "    Is Published: " + e.IsPublished);
        }

我们来自定义写,方法名称随意

        public static void 重复收到消息(object sender, MqttMsgPublishedEventArgs e)
        {
            Console.WriteLine("接收时间: " + DateTime.Now.ToLongTimeString());
            Console.WriteLine("消息id: " + e.MessageId + "    Is Published: " + e.IsPublished);
        }

加上

client.PubedEventHandler += 重复收到消息;

 

XFMQTT.SubedEventHandler

向服务器发布 Topic 时触发

原型

void 发布消息时(object sender, MqttMsgSubscribedEventArgs e)

MqttMsgSubscribedEventArgs 属性

        /// <summary>
        /// Message identifier
        /// </summary>
        public ushort MessageId {get;set;}

        /// <summary>
        /// List of granted QOS Levels
        /// </summary>
        public byte[] GrantedQoSLevels{get;set;}

        // message identifier
        ushort messageId;
        // granted QOS levels
        byte[] grantedQosLevels;

SDK 默认写法

        public void Default_SubedEventHandler(object sender, MqttMsgSubscribedEventArgs e)
        {
            Console.WriteLine("- - - - - - - - - - ");
            Console.WriteLine("Sub topic,Date: " + DateTime.Now.ToLongTimeString());
            Console.WriteLine("MessageId: " + e.MessageId);
            Console.WriteLine("List of granted QOS Levels:    " + Encoding.UTF8.GetString(e.GrantedQoSLevels));
        }

我们来自定义写,方法名称随意

        public static void 发布消息时(object sender, MqttMsgSubscribedEventArgs e)
        {
            Console.WriteLine("向服务器发送了消息");
            Console.WriteLine("发送时间: " + DateTime.Now.ToLongTimeString());
            Console.WriteLine("消息id: " + e.MessageId);
            Console.WriteLine("QOS 为 :    " + Encoding.UTF8.GetString(e.GrantedQoSLevels));
        }

加上

client.SubedEventHandler += 发布消息时;

 

XFMQTT.UnSubedEventHandler

向服务器发布 Topic 失败时触发

void 发送失败(object sender, MqttMsgUnsubscribedEventArgs )
{

}

MqttMsgUnsubscribedEventArgs 属性

        /// <summary>
        /// Message identifier
        /// </summary>
        public ushort MessageId
        {
            get { return this.messageId; }
            internal set { this.messageId = value; }
        }

SDK 写法

        public void Default_UnSubedEventHandler(object sender, MqttMsgUnsubscribedEventArgs e)
        {
            Console.WriteLine("- - - - - - - - - - ");
            Console.WriteLine("Sub topic error,Date: " + DateTime.Now.ToLongTimeString());
            Console.WriteLine("MessageId:    " + e.MessageId);
        }

 

我们自定义写

        public static void 发送失败(object sender, MqttMsgUnsubscribedEventArgs e)
        {
            Console.WriteLine("消息发送失败 ");
            Console.WriteLine("时间: " + DateTime.Now.ToLongTimeString());
            Console.WriteLine("失败的消息 MessageId:    " + e.MessageId);
        }

加上

client.UnSubedEventHandler += 发送失败;

XFMQTT.ConnectionClosedEventHandler

断开连接时触发

 SDK 写法

        public void Default_ConnectionClosedEventHandler(object sender, EventArgs e)
        {
            Console.WriteLine("- - - - - - - - - - ");
            Console.WriteLine("Connect Closed error,Date: " + DateTime.Now.ToLongTimeString());
        }

自定义写

        public static void 断开连接(object sender, EventArgs e)
        {
            Console.WriteLine("日。。。连接断开了: " + DateTime.Now.ToLongTimeString());
        }

加上

client.ConnectionClosedEventHandler += 断开连接;

 

完整代码

        static void Main(string[] args)
        {
            // 创建连接对象
            XFMQTT client = new XFMQTT("a1BiPoNawLI", "Raspberry");
            // 初始化客户端配置
            client.Init("2NOaBeqXcIzLQEhlJFEfKbWeug0o3m0c", "cn-shanghai");
            // 要订阅的Topic
            string[] topic = { client.CombineHeadTopic("PubData") };

            // 使用自定义的委托事件
            client.PubEventHandler += 收到消息;
            client.PubedEventHandler += 重复收到消息;
            client.SubedEventHandler += 发布消息时;
            client.UnSubedEventHandler += 发送失败;
            client.ConnectionClosedEventHandler += 断开连接;
            // 连接服务器
            client.ConnectMqtt(topic);

            while (true)
            {
                string str = Console.ReadLine();

                // 推送内容到特定的 Topic
                client.Subscribe(client.CombineHeadTopic("SubData"), str);
            }

            Console.ReadKey();
        }
        public static void 收到消息(object sender, MqttMsgPublishEventArgs e)
        {
            Console.WriteLine("topic名称:"+e.Topic);
            Console.WriteLine("接收时间:" + DateTime.Now.ToLongDateString());
            Console.WriteLine("消息内容:\n"+Encoding.ASCII.GetString(e.Message));
        }
        public static void 重复收到消息(object sender, MqttMsgPublishedEventArgs e)
        {
            Console.WriteLine("接收时间: " + DateTime.Now.ToLongTimeString());
            Console.WriteLine("消息id: " + e.MessageId + "    Is Published: " + e.IsPublished);
        }
        public static void 发布消息时(object sender, MqttMsgSubscribedEventArgs e)
        {
            Console.WriteLine("向服务器发送了消息");
            Console.WriteLine("发送时间: " + DateTime.Now.ToLongTimeString());
            Console.WriteLine("消息id: " + e.MessageId);
            Console.WriteLine("QOS 为 :    " + Encoding.UTF8.GetString(e.GrantedQoSLevels));
        }
        public static void 发送失败(object sender, MqttMsgUnsubscribedEventArgs e)
        {
            Console.WriteLine("消息发送失败 ");
            Console.WriteLine("时间: " + DateTime.Now.ToLongTimeString());
            Console.WriteLine("失败的消息 MessageId:    " + e.MessageId);
        }
        public static void 断开连接(object sender, EventArgs e)
        {
            Console.WriteLine("日。。。连接断开了: " + DateTime.Now.ToLongTimeString());
        }

但是这样子不好,换种写法

    class Program
    {
        static void Main(string[] args)
        {
            // 创建连接对象
            XFMQTT client = new XFMQTT("a1BiPoNawLI", "Raspberry");
            // 初始化客户端配置
            client.Init("2NOaBeqXcIzLQEhlJFEfKbWeug0o3m0c", "cn-shanghai");
            // 要订阅的Topic
            string[] topic = { client.CombineHeadTopic("PubData") };

            // 使用自定义的委托事件
            事件类 事件 = new 事件类();
            client.PubEventHandler += 事件.收到消息;
            client.PubedEventHandler += 事件.重复收到消息;
            client.SubedEventHandler += 事件.发布消息时;
            client.UnSubedEventHandler += 事件.发送失败;
            client.ConnectionClosedEventHandler += 事件.断开连接;
            // 连接服务器
            client.ConnectMqtt(topic);

            while (true)
            {
                string str = Console.ReadLine();

                // 推送内容到特定的 Topic
                client.Subscribe(client.CombineHeadTopic("SubData"), str);
            }

            Console.ReadKey();
        }
    }
    public class 事件类
    {
        public  void 收到消息(object sender, MqttMsgPublishEventArgs e)
        {
            Console.WriteLine("topic名称:" + e.Topic);
            Console.WriteLine("接收时间:" + DateTime.Now.ToLongDateString());
            Console.WriteLine("消息内容:\n" + Encoding.ASCII.GetString(e.Message));
        }
        public  void 重复收到消息(object sender, MqttMsgPublishedEventArgs e)
        {
            Console.WriteLine("接收时间: " + DateTime.Now.ToLongTimeString());
            Console.WriteLine("消息id: " + e.MessageId + "    Is Published: " + e.IsPublished);
        }
        public void 发布消息时(object sender, MqttMsgSubscribedEventArgs e)
        {
            Console.WriteLine("向服务器发送了消息");
            Console.WriteLine("发送时间: " + DateTime.Now.ToLongTimeString());
            Console.WriteLine("消息id: " + e.MessageId);
            Console.WriteLine("QOS 为 :    " + Encoding.UTF8.GetString(e.GrantedQoSLevels));
        }
        public void 发送失败(object sender, MqttMsgUnsubscribedEventArgs e)
        {
            Console.WriteLine("消息发送失败 ");
            Console.WriteLine("时间: " + DateTime.Now.ToLongTimeString());
            Console.WriteLine("失败的消息 MessageId:    " + e.MessageId);
        }
        public  void 断开连接(object sender, EventArgs e)
        {
            Console.WriteLine("日。。。连接断开了: " + DateTime.Now.ToLongTimeString());
        }
    }

 

使用默认事件方法与自定义事件方法并不冲突。

 

 // 使用默认事件方法
            client.UseDefaultEventHandler();
            // 使用自定义的委托事件
            事件类 事件 = new 事件类();
            client.PubEventHandler += 事件.收到消息;
            client.PubedEventHandler += 事件.重复收到消息;
            client.SubedEventHandler += 事件.发布消息时;
            client.UnSubedEventHandler += 事件.发送失败;
            client.ConnectionClosedEventHandler += 事件.断开连接;

 

为便于理解,上面事件方法使用了中文名称,请根据实际修改。

posted @ 2019-05-01 18:14  痴者工良  阅读(1069)  评论(0编辑  收藏  举报