示例#1
0
        /// <summary>
        /// MQTT subscribe to a topic.  Remember, these subscriptionns are ephemeral.
        /// </summary>
        /// <param name="topicUriString"></param>
        /// <param name="qos"></param>
        /// <param name="action"></param>
        /// <returns></returns>
        public async Task SubscribeAsync(string topicUriString, QualityOfServiceLevelType qos, Action <string, string, byte[]> action)
        {
            try
            {
                Dictionary <string, QualityOfServiceLevelType> dict = new Dictionary <string, QualityOfServiceLevelType>();
                dict.Add(topicUriString, qos);
                dispatcher.Register(topicUriString, action);
                SubscribeMessage msg = new SubscribeMessage(session.NewId(), dict);


                //if (channel.RequireBlocking)
                //{
                //    channel.SendAsync(msg.Encode()).GetAwaiter();
                //    //Task t = channel.SendAsync(msg.Encode());
                //    //Task.WaitAll(t);
                //}
                //else
                //{
                await channel.SendAsync(msg.Encode());

                //}
            }
            catch (Exception ex)
            {
                OnChannelError?.Invoke(this, new ChannelErrorEventArgs(channel.Id, ex));
            }
        }
示例#2
0
        /// <summary>
        /// Unsubscribe from an ephemeral subscription.
        /// </summary>
        /// <param name="topics"></param>
        /// <returns></returns>
        public async Task UnsubscribeAsync(IEnumerable <string> topics)
        {
            try
            {
                UnsubscribeMessage msg = new UnsubscribeMessage(session.NewId(), topics);

                //if (channel.RequireBlocking)
                //{
                //    Task t = channel.SendAsync(msg.Encode());
                //    Task.WaitAll(t);
                //}
                //else
                //{
                await channel.SendAsync(msg.Encode());

                //}

                foreach (var topic in topics)
                {
                    dispatcher.Unregister(topic);
                }
            }
            catch (Exception ex)
            {
                OnChannelError?.Invoke(this, new ChannelErrorEventArgs(channel.Id, ex));
            }
        }
示例#3
0
        /// <summary>
        /// MQTT subscribe to a topic.  Remember, these subscriptions are ephemeral.
        /// </summary>
        /// <param name="subscriptions"></param>
        /// <returns></returns>
        public async Task SubscribeAsync(Tuple <string, QualityOfServiceLevelType, Action <string, string, byte[]> >[] subscriptions)
        {
            try
            {
                Dictionary <string, QualityOfServiceLevelType> dict = new Dictionary <string, QualityOfServiceLevelType>();

                foreach (var tuple in subscriptions)
                {
                    dict.Add(tuple.Item1, tuple.Item2);
                    dispatcher.Register(tuple.Item1, tuple.Item3);
                }

                SubscribeMessage msg = new SubscribeMessage(session.NewId(), dict);

                //if (channel.RequireBlocking)
                //{
                //    channel.SendAsync(msg.Encode()).GetAwaiter();
                //    //Task t = channel.SendAsync(msg.Encode());
                //    //Task.WaitAll(t);
                //}
                //else
                //{
                await channel.SendAsync(msg.Encode());

                //}
            }
            catch (Exception ex)
            {
                OnChannelError?.Invoke(this, new ChannelErrorEventArgs(channel.Id, ex));
            }
        }
示例#4
0
        public async Task <ConnectAckCode> ConnectAsync(string clientId, string username, string password,
                                                        int keepaliveSeconds)
        {
            code = null;

            ConnectMessage msg = new ConnectMessage(clientId, username, password, keepaliveSeconds, true);

            if (!Channel.IsConnected)
            {
                try
                {
                    await Channel.OpenAsync();
                }
                catch (Exception ex)
                {
                    OnChannelError?.Invoke(this, new ChannelErrorEventArgs(Channel.Id, ex));
                    return(ConnectAckCode.ServerUnavailable);
                }

                try
                {
                    Receive(Channel);
                }
                catch (Exception ex)
                {
                    OnChannelError?.Invoke(this, new ChannelErrorEventArgs(Channel.Id, ex));
                    return(ConnectAckCode.ServerUnavailable);
                }
            }

            try
            {
                await Channel.SendAsync(msg.Encode());

                DateTime expiry = DateTime.UtcNow.AddMilliseconds(timeoutMilliseconds);
                while (!code.HasValue)
                {
                    await Task.Delay(10);

                    if (DateTime.UtcNow > expiry)
                    {
                        throw new TimeoutException("MQTT connection timed out.");
                    }
                }

                return(code.Value);
            }
            catch (Exception ex)
            {
                OnChannelError?.Invoke(this, new ChannelErrorEventArgs(Channel.Id, ex));
                return(ConnectAckCode.ServerUnavailable);
            }
        }
示例#5
0
        /// <summary>
        /// MQTT publish to a topic.
        /// </summary>
        /// <param name="qos"></param>
        /// <param name="topicUriString"></param>
        /// <param name="contentType"></param>
        /// <param name="data"></param>
        /// <param name="indexes"></param>
        /// <param name="messageId"></param>
        /// <returns></returns>
        public async Task PublishAsync(QualityOfServiceLevelType qos, string topicUriString, string contentType, byte[] data, string cacheKey = null, IEnumerable <KeyValuePair <string, string> > indexes = null, string messageId = null)
        {
            try
            {
                string indexString = GetIndexString(indexes);

                UriBuilder builder     = new UriBuilder(topicUriString);
                string     queryString = messageId == null?String.Format("{0}={1}", SkunkLab.Protocols.Utilities.QueryStringConstants.CONTENT_TYPE, contentType) : String.Format("{0}={1}&{2}={3}", QueryStringConstants.CONTENT_TYPE, contentType, QueryStringConstants.MESSAGE_ID, messageId);

                if (!string.IsNullOrEmpty(cacheKey))
                {
                    queryString = queryString + String.Format("&{0}={1}", QueryStringConstants.CACHE_KEY, cacheKey);
                }

                if (!string.IsNullOrEmpty(indexString))
                {
                    queryString = queryString + "&" + indexString;
                }


                builder.Query = queryString;

                PublishMessage msg = new PublishMessage(false, qos, false, 0, builder.ToString().ToLowerInvariant(), data);
                if (qos != QualityOfServiceLevelType.AtMostOnce)
                {
                    msg.MessageId = session.NewId();
                    session.Quarantine(msg, DirectionType.Out);
                }

                queue.Enqueue(msg.Encode());

                while (queue.Count > 0)
                {
                    byte[] message = queue.Dequeue();

                    //if (channel.RequireBlocking)
                    //{
                    //    //Task t = channel.SendAsync(message);
                    //    //Task.WaitAll(t);
                    //}
                    //else
                    //{
                    await channel.SendAsync(message);

                    //}
                }
            }
            catch (Exception ex)
            {
                OnChannelError?.Invoke(this, new ChannelErrorEventArgs(channel.Id, ex));
            }
        }
示例#6
0
 /// <summary>
 /// MQTT subscribe to a topic.  Remember, these subscriptionns are ephemeral.
 /// </summary>
 /// <param name="topicUriString"></param>
 /// <param name="qos"></param>
 /// <param name="action"></param>
 /// <returns></returns>
 public async Task SubscribeAsync(string topicUriString, QualityOfServiceLevelType qos, Action <string, string, byte[]> action)
 {
     try
     {
         Dictionary <string, QualityOfServiceLevelType> dict = new Dictionary <string, QualityOfServiceLevelType>();
         dict.Add(topicUriString.ToLowerInvariant(), qos);
         dispatcher.Register(topicUriString.ToLowerInvariant(), action);
         SubscribeMessage msg = new SubscribeMessage(session.NewId(), dict);
         await channel.SendAsync(msg.Encode());
     }
     catch (Exception ex)
     {
         OnChannelError?.Invoke(this, new ChannelErrorEventArgs(channel.Id, ex));
     }
 }
示例#7
0
        public async Task UnsubscribeAsync(string topic)
        {
            try
            {
                UnsubscribeMessage msg = new UnsubscribeMessage(session.NewId(), new[] { topic });

                await Channel.SendAsync(msg.Encode());

                dispatcher.Unregister(topic);
            }
            catch (Exception ex)
            {
                OnChannelError?.Invoke(this, new ChannelErrorEventArgs(Channel.Id, ex));
            }
        }
示例#8
0
        public async Task UnsubscribeAsync(IEnumerable <string> topics)
        {
            try
            {
                UnsubscribeMessage msg = new UnsubscribeMessage(session.NewId(), topics);

                await Channel.SendAsync(msg.Encode());

                foreach (string topic in topics)
                {
                    dispatcher.Unregister(topic);
                }
            }
            catch (Exception ex)
            {
                OnChannelError?.Invoke(this, new ChannelErrorEventArgs(Channel.Id, ex));
            }
        }
示例#9
0
        private void Channel_OnReceive(object sender, ChannelReceivedEventArgs args)
        {
            MqttMessage        msg     = MqttMessage.DecodeMessage(args.Message);
            MqttMessageHandler handler = MqttMessageHandler.Create(session, msg, dispatcher);

            try
            {
                MqttMessage message = handler.ProcessAsync().GetAwaiter().GetResult();
                if (message != null)
                {
                    channel.SendAsync(message.Encode()).GetAwaiter();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Trace.TraceError(ex.Message);
                OnChannelError?.Invoke(this, new ChannelErrorEventArgs(channel.Id, ex));
            }

            //Task task = Task.Factory.StartNew(async () =>
            //{
            //    try
            //    {
            //        MqttMessage message = await handler.ProcessAsync();
            //        if (message != null)
            //        {
            //            await channel.SendAsync(message.Encode());
            //        }
            //    }
            //    catch(Exception ex)
            //    {
            //        Console.WriteLine(ex.Message);
            //        Trace.TraceError(ex.Message);
            //    }
            //});

            //Task.WaitAll(task);

            //if (task.Exception != null)
            //{
            //    OnChannelError?.Invoke(this, new ChannelErrorEventArgs(channel.Id, task.Exception.InnerException));
            //}
        }
示例#10
0
        private void Channel_OnReceive(object sender, ChannelReceivedEventArgs args)
        {
            MqttMessage        msg     = MqttMessage.DecodeMessage(args.Message);
            MqttMessageHandler handler = MqttMessageHandler.Create(session, msg, dispatcher);

            try
            {
                MqttMessage message = handler.ProcessAsync().GetAwaiter().GetResult();
                if (message != null)
                {
                    Channel.SendAsync(message.Encode()).GetAwaiter();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Trace.TraceError(ex.Message);
                OnChannelError?.Invoke(this, new ChannelErrorEventArgs(Channel.Id, ex));
            }
        }
示例#11
0
        public async Task SubscribeAsync(
            Tuple <string, QualityOfServiceLevelType, Action <string, string, byte[]> >[] subscriptions)
        {
            try
            {
                Dictionary <string, QualityOfServiceLevelType>
                dict = new Dictionary <string, QualityOfServiceLevelType>();

                foreach (var tuple in subscriptions)
                {
                    dict.Add(tuple.Item1, tuple.Item2);
                    dispatcher.Register(tuple.Item1, tuple.Item3);
                }

                SubscribeMessage msg = new SubscribeMessage(session.NewId(), dict);

                await Channel.SendAsync(msg.Encode());
            }
            catch (Exception ex)
            {
                OnChannelError?.Invoke(this, new ChannelErrorEventArgs(Channel.Id, ex));
            }
        }
示例#12
0
        /// <summary>
        /// Unsubscribe from an ephemeral subscription.
        /// </summary>
        /// <param name="topic"></param>
        /// <returns></returns>
        public async Task UnsubscribeAsync(string topic)
        {
            try
            {
                UnsubscribeMessage msg = new UnsubscribeMessage(session.NewId(), new string[] { topic });

                //if (channel.RequireBlocking)
                //{
                //    Task t = channel.SendAsync(msg.Encode());
                //    Task.WaitAll(t);
                //}
                //else
                //{
                await channel.SendAsync(msg.Encode());

                //}

                dispatcher.Unregister(topic);
            }
            catch (Exception ex)
            {
                OnChannelError?.Invoke(this, new ChannelErrorEventArgs(channel.Id, ex));
            }
        }
示例#13
0
 private void Channel_OnError(object sender, ChannelErrorEventArgs args)
 {
     OnChannelError?.Invoke(this, args);
 }