internal async Task Subscribe(string endTopic, Func <string, byte[], Task> action)
        {
            var topic       = $"{ Properties.Settings.Default.MqttApplicationName}/{Properties.Settings.Default.ClientId}/{endTopic}";
            var topicFilter = new TopicFilterBuilder()
                              .WithTopic(topic)
                              .WithExactlyOnceQoS()
                              .Build();

            var topicSub = new MqttClientSubscribeOptionsBuilder()
                           .WithTopicFilter(topicFilter)
                           .Build();

            var res = await this.client.SubscribeAsync(topicSub).ConfigureAwait(false);

            client.UseApplicationMessageReceivedHandler(e =>
            {
                if (e.ApplicationMessage.Topic == topic)
                {
                    try
                    {
                        action(topic, e.ApplicationMessage.Payload);
                    }
                    catch (Exception ex)
                    {
                        logger.Error(ex);
                    }
                }
            });
        }
Пример #2
0
        public MqttDriver(string mqttBrokerHost, int tcpPort, IList <LoraControllerFullInfo> loraControllers, IChannelCommandManagerDriverSide <string, IInteleconCommand> commandManagerDriverSide)
        {
            _mqttBrokerHost           = mqttBrokerHost;
            _tcpPort                  = tcpPort;
            _loraControllers          = loraControllers;
            _commandManagerDriverSide = commandManagerDriverSide;
            _commandManagerDriverSide.CommandRequestAccepted += CommandManagerDriverSideOnCommandRequestAccepted;

            _lastSixsCache = new AttachedLastDataCache();

            var subscriptionList = loraControllers.GroupBy(lc => lc.RxTopicName).Select(g => g.Key);

            var topicFilters = new List <TopicFilter>();

            foreach (var topicName in subscriptionList)
            {
                Log.Log("[MQTT DRIVER] .ctor topic name to subscribe added: " + topicName);
                var tfb = new TopicFilterBuilder();
                tfb.WithTopic(topicName);
                topicFilters.Add(tfb.Build());
            }

            _topicFilters = topicFilters;
            Log.Log("[MQTT DRIVER] .ctor topics to subscribe to generated, count = " + _topicFilters.Count);

            RunAsync().Wait();

            Log.Log("[MQTT DRIVER] .ctor complete");
        }
Пример #3
0
        private IEnumerable <TopicFilter> WrapTopicFilters(IEnumerable <ITopicFilter> topicFilters)
        {
            return(topicFilters.Select(tFilter =>
            {
                var tf = new TopicFilterBuilder().WithTopic(tFilter.Topic);

                switch (tFilter.QualityOfServiceLevel)
                {
                case QoSLevel.AtMostOnce:
                    tf.WithAtMostOnceQoS();
                    break;

                case QoSLevel.AtLeastOnce:
                    tf.WithAtLeastOnceQoS();
                    break;

                case QoSLevel.ExactlyOnce:
                    tf.WithExactlyOnceQoS();
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }
                return tf.Build();
            }));
        }
Пример #4
0
        private async void Subscribe_Click(object sender, EventArgs e)
        {
            if (mqttClient == null || !mqttClient.IsConnected)
            {
                return;
            }
            if (!string.IsNullOrWhiteSpace(topicSubscribe.Text))
            {
                TopicFilterBuilder builder = new TopicFilterBuilder()
                                             .WithTopic(topicSubscribe.Text);
                if (qosSubscribe.SelectedIndex == -1)
                {
                    qosSubscribe.SelectedIndex = 0;
                }
                builder.WithQualityOfServiceLevel((MqttQualityOfServiceLevel)qosSubscribe.SelectedIndex);
                try
                {
                    await mqttClient.SubscribeAsync(builder.Build());

                    if (!subscriptions.Items.Contains(topicSubscribe.Text))
                    {
                        subscriptions.Items.Add(topicSubscribe.Text);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(this, ex.Message);
                }
            }
        }
Пример #5
0
        /// <inheritdoc />
        public async Task ConnectAsync()
        {
            this.MqttClient.UseApplicationMessageReceivedHandler(async e =>
            {
                if (!this.Handlers.TryGetValue(e.ApplicationMessage.Topic, out var handlers))
                {
                    return;
                }

                var message = e.ApplicationMessage.ConvertPayloadToString();

                var metric = JsonConvert.DeserializeObject <Metric>(message);
                if (metric == null)
                {
                    return;
                }

                foreach (var handler in handlers)
                {
                    await handler(metric);
                }
            });

            await this.MqttClient.ConnectAsync(this.MqttClientOptions);

            var filter = new TopicFilterBuilder()
                         .WithTopic("#")
                         .Build();

            await this.MqttClient.SubscribeAsync(filter);
        }
Пример #6
0
        public MqttClientSubscribeOptionsBuilder WithTopicFilter(TopicFilterBuilder topicFilterBuilder)
        {
            if (topicFilterBuilder == null)
            {
                throw new ArgumentNullException(nameof(topicFilterBuilder));
            }

            return(WithTopicFilter(topicFilterBuilder.Build()));
        }
Пример #7
0
        /// <summary>
        /// 订阅主题
        /// </summary>
        /// <param name="topic"></param>
        public bool SubscribeMessage()
        {
            try
            {
                if (mqttNetClient.MqttClientObj == null)
                {
                    return(false);
                }
                if (mqttNetClient.MqttClientObj.IsConnected == false)
                {
                    mqttNetClient.MqttClientObj.ConnectAsync(mqttNetClient.MqttClientOptions);
                }

                if (mqttNetClient.MqttClientObj.IsConnected == false)
                {
                    LogHelper.Log.Info("Publish >>Connected Failed! ");
                    return(false);
                }
                List <TopicFilter> listTopic = new List <TopicFilter>();
                if (mqttNetClient.Topic.Count() > 0)
                {
                    foreach (var topic in mqttNetClient.Topic)
                    {
                        if (MqttQualityLevel == MqttQualityOfServiceLevel.AtMostOnce)
                        {
                            var topicFilterBuilder = new TopicFilterBuilder().WithTopic(topic)
                                                     .WithAtMostOnceQoS().Build();
                            listTopic.Add(topicFilterBuilder);
                        }
                        else if (MqttQualityLevel == MqttQualityOfServiceLevel.AtLeastOnce)
                        {
                            var topicFilterBuilder = new TopicFilterBuilder().WithTopic(topic)
                                                     .WithAtLeastOnceQoS().Build();
                            listTopic.Add(topicFilterBuilder);
                        }
                        else if (MqttQualityLevel == MqttQualityOfServiceLevel.ExactlyOnce)
                        {
                            var topicFilterBuilder = new TopicFilterBuilder().WithTopic(topic)
                                                     .WithExactlyOnceQoS().Build();
                            listTopic.Add(topicFilterBuilder);
                        }
                    }
                    if (listTopic.Count < 1)
                    {
                        return(false);
                    }
                    mqttNetClient.MqttClientObj.SubscribeAsync(listTopic.ToArray());
                    return(true);
                }
                return(false);
            }
            catch (Exception exp)
            {
                LogHelper.Log.Error("Subscrible >>" + exp.Message);
                return(false);
            }
        }
Пример #8
0
        public async void Subscribe()
        {
            var topicBuilder = new TopicFilterBuilder()
                               .WithTopic("test/messages")
                               .Build();
            await MqttClient.SubscribeAsync(topicBuilder);

            MqttClient.UseApplicationMessageReceivedHandler(e =>
            {
                MessageRecievedHandler(this, e);
            });
        }
Пример #9
0
        public MQTTClient()
        {
            var mqttClient = new MqttFactory().CreateMqttClient();

            var optionBuilder = new MqttClientOptionsBuilder();

            optionBuilder
            .WithClientId("c001")
            .WithTcpServer(opts =>
            {
                opts.Server = "127.0.0.1";
                opts.Port   = 108;
            })
            .WithCredentials("u001", "p001")
            .WithCleanSession(true);

            var options = optionBuilder.Build();

            mqttClient.ConnectAsync(options, CancellationToken.None).Wait();

            var recieveHander = new MsgRecieveHandler();

            mqttClient.ApplicationMessageReceivedHandler = recieveHander;


            var topicBuilder = new TopicFilterBuilder();

            topicBuilder.WithTopic("家/客厅/空调/#")
            .WithAtMostOnceQoS();
            var topicHome = topicBuilder.Build();

            var subscribOptionBuilder = new MqttClientSubscribeOptionsBuilder();

            subscribOptionBuilder.WithTopicFilter(topicHome);

            var subOpt = subscribOptionBuilder.Build();

            mqttClient.SubscribeAsync(subOpt, CancellationToken.None).Wait();

            var appMsg = new MqttApplicationMessage();

            appMsg.Topic   = "家/客厅/空调/开关";
            appMsg.Payload = Encoding.UTF8.GetBytes("我来了~");
            appMsg.QualityOfServiceLevel = MqttQualityOfServiceLevel.AtMostOnce;
            appMsg.Retain = false;


            mqttClient.PublishAsync(appMsg, CancellationToken.None).Wait();
            //var appMsg = new MqttApplicationMessage("家/客厅/空调/开关",
            //    Encoding.UTF8.GetBytes("消息内容"),
            //    MqttQualityOfServiceLevel.AtMostOnce, false);
        }
Пример #10
0
        private async Task OnConnected(MqttClientConnectedEventArgs e)
        {
            Console.WriteLine("Connected to MQTT host");

            var topicSubscription = new TopicFilterBuilder()
                                    .WithTopic(MqttTopic)
                                    .WithExactlyOnceQoS()
                                    .Build();

            await _client.SubscribeAsync(topicSubscription);

            Console.WriteLine($"Subscribed to {MqttTopic}");
        }
Пример #11
0
        private async Task SubscribeToTopic(string topic)
        {
            _logger.LogInformation($"Subscribing to topic '{topic}'");

            var startTopicFilter = new TopicFilterBuilder()
                                   .WithTopic(topic)
                                   .WithAtLeastOnceQoS()
                                   .Build();

            await _mqttClient.SubscribeAsync(startTopicFilter);

            _logger.LogInformation("Subscribing to topic 'mqtttimer/+/stop'");
        }
Пример #12
0
        public MqttClientSubscribeOptionsBuilder WithTopicFilter(Action <TopicFilterBuilder> topicFilterBuilder)
        {
            if (topicFilterBuilder == null)
            {
                throw new ArgumentNullException(nameof(topicFilterBuilder));
            }

            var internalTopicFilterBuilder = new TopicFilterBuilder();

            topicFilterBuilder(internalTopicFilterBuilder);

            return(WithTopicFilter(internalTopicFilterBuilder));
        }
Пример #13
0
        /// <summary>
        /// TODO su
        /// </summary>
        /// <param name="topics"></param>
        /// <returns></returns>
        public async Task SubscribeAsync(IEnumerable <MQTTTopicConfiguration> topics)
        {
            var returnList = new List <MQTTTopicConfiguration>();
            var errorList  = new List <Error>();


            var topicBuilder = new TopicFilterBuilder();

            foreach (var topic in topics)
            {
                topicBuilder.WithTopic(topic.Name).WithQualityOfServiceLevel((MqttQualityOfServiceLevel)topic.QoS);
            }
            var result = await _client.SubscribeAsync(topicBuilder.Build());
        }
Пример #14
0
        public static void StartMain()
        {
            try
            {
                var factory = new MqttFactory();

                var mqttClient = factory.CreateMqttClient();

                var options = new MqttClientOptionsBuilder()
                              .WithTcpServer(ServerUrl, Port)
                              .WithCredentials(UserId, Password)
                              .WithClientId(Guid.NewGuid().ToString().Substring(0, 5))
                              .Build();

                mqttClient.ConnectAsync(options);

                mqttClient.UseConnectedHandler(async e =>
                {
                    Console.WriteLine("Connected >>Success");
                    // Subscribe to a topic
                    var topicFilterBulder = new TopicFilterBuilder().WithTopic(Topic).Build();
                    await mqttClient.SubscribeAsync(topicFilterBulder);
                    Console.WriteLine("Subscribe >>" + Topic);
                });

                mqttClient.UseDisconnectedHandler(async e =>
                {
                    Console.WriteLine("Disconnected >>Disconnected Server");
                    await Task.Delay(TimeSpan.FromSeconds(5));
                    try
                    {
                        await mqttClient.ConnectAsync(options);
                    }
                    catch (Exception exp)
                    {
                        Console.WriteLine("Disconnected >>Exception" + exp.Message);
                    }
                });

                mqttClient.UseApplicationMessageReceivedHandler(e =>
                {
                    Console.WriteLine("MessageReceived >>" + Encoding.UTF8.GetString(e.ApplicationMessage.Payload));
                });
                Console.WriteLine(mqttClient.IsConnected.ToString());
            }
            catch (Exception exp)
            {
                Console.WriteLine("MessageReceived >>" + exp.Message);
            }
        }
Пример #15
0
        public static async Task startClient()
        {
            MqttClientService mqttClientService = new MqttClientService();
            IMqttClient       mqttClient        = mqttClientService.CreateMqttClient();

            mqttClient.ApplicationMessageReceived += MqttClient_ApplicationMessageReceived;
            mqttClient.Connected    += MqttClient_Connected;
            mqttClient.Disconnected += MqttClient_Disconnected;

            MqttClientOptions mqttClientOptions = CreateOptions(ProtocolType.TCP, "127.0.0.1");
            await mqttClientService.ConnectServer(mqttClient, mqttClientOptions);

            var topicFilter = new TopicFilterBuilder().WithTopic("A/B/C").WithQualityOfServiceLevel(MqttQualityOfServiceLevel.AtLeastOnce);
            await mqttClientService.SubscribeMessage(mqttClient, topicFilter);
        }
Пример #16
0
        public async Task Subscribe()
        {
            Reconnect();

            _logger.LogInformation("Register subscription");
            client.UseConnectedHandler(async e =>
            {
                var topicFilter = new TopicFilterBuilder()
                                  .WithTopic(_configuration.Value.Topic)
                                  .Build();

                _logger.LogInformation($"Subscribe to topic {topicFilter.Topic}");
                await client.SubscribeAsync(topicFilter);
                _logger.LogInformation("Subscribed");
            });
            _logger.LogInformation("Subscription registered");

            ConsumeMessage();
            await Connect();
        }
Пример #17
0
        /// <summary>
        /// 连接服务器并按标题订阅内容
        /// </summary>
        /// <param name="e"></param>
        /// <returns></returns>
        private async Task Connected(MqttClientConnectedEventArgs e)
        {
            try
            {
                List <TopicFilter> listTopic = new List <TopicFilter>();
                if (listTopic.Count <= 0)
                {
                    var topicFilterBulder = new TopicFilterBuilder().WithTopic(Variable.getTopic()).Build();
                    listTopic.Add(topicFilterBulder);
                    //Console.WriteLine("Connected >>Subscribe " + Topic);
                }
                await mqttClient.SubscribeAsync(listTopic.ToArray());

                Console.WriteLine("Connected >>Subscribe Success");
            }
            catch (Exception exp)
            {
                Console.WriteLine(exp.Message);
            }
        }
Пример #18
0
        public async Task RegisterMessageHandler(
            Func <MqttMessage, CancellationToken, Task> messageHander)
        {
            if (!_started)
            {
                await _syncLock.WaitAsync();

                try
                {
                    if (!_started)
                    {
                        var topicFilter = new TopicFilterBuilder()
                                          .WithTopic(_topicName)
                                          .Build();

                        await _innerMqttClient.SubscribeAsync(topicFilter);

                        var options = new ManagedMqttClientOptionsBuilder()
                                      .WithAutoReconnectDelay(TimeSpan.FromSeconds(5))
                                      .WithClientOptions(new MqttClientOptionsBuilder()
                                                         .WithClientId(Guid.NewGuid().ToString())
                                                         .WithTcpServer(_config.Host, _config.Port)
                                                         .WithCredentials(_config.UserName, _config.Password)
                                                         .WithTls()
                                                         .Build())
                                      .Build();

                        await _innerMqttClient.StartAsync(options);

                        _started = false;
                    }
                }
                finally
                {
                    _syncLock.Release();
                }
            }

            throw new NotImplementedException();
        }
Пример #19
0
        public async Task Initialize()
        {
            var factory = new MqttFactory();

            mqttClient = factory.CreateMqttClient();

            var options = new MqttClientOptionsBuilder()
                          .WithTcpServer(url, 1883)
                          .Build();

            mqttClient.UseConnectedHandler(async e =>
            {
                var topicFilters = new TopicFilterBuilder()
                                   .WithTopic("FX/FromNode")
                                   .WithTopic("FX/FromPython")
                                   .Build();

                await mqttClient.SubscribeAsync(topicFilters);
            });

            await mqttClient.ConnectAsync(options, CancellationToken.None);
        }
Пример #20
0
        public static async Task ReqRepTest(int LoopNum)
        {
            string requestTopic = "mytopic/A/request";
            var    sw           = new System.Diagnostics.Stopwatch();

            sw.Start();
            using (var cts = new CancellationTokenSource())
                using (var startedev = new ManualResetEventSlim())
                    using (var connectedev = new ManualResetEventSlim())
                        using (var recvev = new ManualResetEventSlim())
                        {
                            var fac = new MqttFactory();
                            await Task.WhenAll(
                                Task.Run(async() =>
                            {
                                var svr        = fac.CreateMqttServer();
                                var msgbuilder = new MqttApplicationMessageBuilder().WithPayload("req");
                                svr.ApplicationMessageReceived += async(sender, ev) =>
                                {
                                    if (ev.ApplicationMessage.Topic.Equals(requestTopic, StringComparison.Ordinal))
                                    {
                                        var reqmsg = MessagePackSerializer.Deserialize <ReqMsg>(ev.ApplicationMessage.Payload);
                                        var msg    = msgbuilder.WithTopic(reqmsg.ReplyTopic).Build();
                                        await svr.PublishAsync(msg);
                                    }
                                };
                                svr.Started += (sender, ev) =>
                                {
                                    startedev.Set();
                                };
                                var opt = new MqttServerOptionsBuilder()
                                          .WithDefaultEndpoint()
                                          .WithDefaultEndpointBoundIPAddress(IPAddress.Loopback)
                                          .WithDefaultEndpointPort(10012)
                                          .Build();
                                await svr.StartAsync(opt).ConfigureAwait(false);
                                cts.Token.WaitHandle.WaitOne();
                                await svr.StopAsync().ConfigureAwait(false);
                            })
                                ,
                                Task.Run(async() =>
                            {
                                var client = fac.CreateMqttClient();
                                string replyTopic = "mytopic/A/reply";
                                var queue = new ConcurrentQueue <TaskCompletionSource <byte[]> >();
                                client.ApplicationMessageReceived += (sender, ev) =>
                                {
                                    if (queue.TryDequeue(out var tcs))
                                    {
                                        tcs.TrySetResult(ev.ApplicationMessage.Payload);
                                    }
                                };
                                client.Connected += (sender, ev) =>
                                {
                                    connectedev.Set();
                                };
                                var clientopt = new MqttClientOptionsBuilder()
                                                .WithClientId("clid")
                                                .WithTcpServer("localhost", 10012)
                                                .Build()
                                ;
                                await client.ConnectAsync(clientopt).ConfigureAwait(false);
                                connectedev.Wait();
                                var topicFilter = new TopicFilterBuilder()
                                                  .WithTopic(replyTopic)
                                                  .WithAtLeastOnceQoS()
                                                  .Build()
                                ;
                                await client.SubscribeAsync(topicFilter).ConfigureAwait(false);
                                Console.WriteLine($"client task loop started:{sw.Elapsed}");
                                var beginTime = sw.Elapsed;
                                var msgbuilder = new MqttApplicationMessageBuilder().WithTopic(requestTopic);
                                for (int i = 0; i < LoopNum; i++)
                                {
                                    var reqpayload = MessagePackSerializer.Serialize(new ReqMsg(replyTopic, "hoge"));
                                    var msg = msgbuilder
                                              .WithPayload(reqpayload)
                                              .Build();
                                    ;
                                    var reqtcs = new TaskCompletionSource <byte[]>();
                                    queue.Enqueue(reqtcs);
                                    await client.PublishAsync(msg).ConfigureAwait(false);
                                    await reqtcs.Task;
                                }
                                var endTime = sw.Elapsed;
                                Console.WriteLine($"elapsed(mqtt):{sw.Elapsed},rps={LoopNum/(endTime.Subtract(beginTime).TotalSeconds)}");
                            }).ContinueWith(t =>
                            {
                                Console.WriteLine($"all client task done:{sw.Elapsed}");
                                cts.Cancel();
                                if (t.IsCanceled)
                                {
                                    throw new TaskCanceledException("server task cancelled", t.Exception);
                                }
                                else if (t.IsFaulted)
                                {
                                    throw new AggregateException(t.Exception);
                                }
                            })
                                ).ConfigureAwait(false);
                        }
        }
Пример #21
0
        private void Reset()
        {
            bool hasError = true;

            while (hasError)
            {
                lastUpdate = DateTime.Now;


                // Serial port reset
                if (SerialPortEnabled)
                {
                    try
                    {
                        if (serialPort != null && serialPort.IsOpen)
                        {
                            serialPort.Close();
                            serialPort.Dispose();
                            serialPort = null;
                        }
                        serialPort               = new SerialPort();
                        serialPort.PortName      = PortName;
                        serialPort.DataReceived += SerialPort_DataReceived;

                        Setup(serialPort);

                        serialPort.Open();
                        serialPort.ReadExisting();
                        Console.WriteLine($"{serialPort.PortName} Connected.");
                        hasError = false;
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"{serialPort.PortName} Connection failed. : {ex.Message}");
                        Retry();
                    }
                }
                else
                {
                    Setup(new SerialPort()); // dummy
                    hasError = false;
                }

                // MQTT client setup
                try
                {
                    if (client != null)
                    {
                        client.Dispose();
                    }
                    client = null;
                    client = factory.CreateMqttClient();

                    var options = new MqttClientOptionsBuilder()
                                  .WithTcpServer(Host, Port)
                                  .Build();

                    // Set topic filters
                    client.UseConnectedHandler(async e =>
                    {
                        if (Topics != null && Topics.Length > 0)
                        {
                            var filters = new TopicFilter[Topics.Length];
                            for (int i = 0; i < filters.Length; i++)
                            {
                                filters[i] = new TopicFilterBuilder().WithTopic(Topics[i]).Build();
                            }
                            await client.SubscribeAsync(filters);
                        }
                    });
                    // Message receive event
                    client.UseApplicationMessageReceivedHandler(e => {
                        string topic = e.ApplicationMessage.Topic;
                        string data  = Encoding.UTF8.GetString(e.ApplicationMessage.Payload);
                        OnTopicReceived(topic, data);
                    });
                    // Disconnect Event
                    client.UseDisconnectedHandler(async e =>
                    {
                        Console.WriteLine("MQTT Connection Closed.");
                        await Task.Delay(TimeSpan.FromSeconds(5));
                        Reset();
                    });
                    clientId = Guid.NewGuid().ToString();
                    Task.Run(async() => {
                        await client.ConnectAsync(options);
                        Console.WriteLine("MQTT Connected.");
                    });
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"MQTT Connection failed. : {ex.Message}");
                    Reset();
                }
            }
        }
Пример #22
0
 public async Task SubscribeMessage(IMqttClient mqttClient, TopicFilterBuilder topicFilterBuilder)
 {
     //var a = new TopicFilterBuilder().WithTopic("").WithQualityOfServiceLevel(MqttQualityOfServiceLevel.AtLeastOnce);
     await mqttClient.SubscribeAsync(topicFilterBuilder.Build());
 }
Пример #23
0
        private async Task <bool> Init()
        {
            try
            {
                // var options = new MqttClientOptions() { ClientId = userInfo.Guid + "-" + userInfo.Name };
                var options = new MqttClientOptions()
                {
                    ClientId = Guid.NewGuid().ToString("D")
                };
                options.ChannelOptions = new MqttClientTcpOptions()
                {
                    Server = ServerIp,
                    Port   = Port
                };
                options.Credentials = new MqttClientCredentials()
                {
                    Username = "******",
                    Password = "******"
                };
                options.CleanSession          = true;
                options.KeepAlivePeriod       = TimeSpan.FromSeconds(100.5);
                options.KeepAliveSendInterval = TimeSpan.FromSeconds(20000);
                if (_mqttClient == null)
                {
                    _mqttClient = new MqttFactory().CreateMqttClient();
                }
                var handler = new MqttApplicationMessageReceivedHandler();
                _mqttClient.ApplicationMessageReceivedHandler = handler;
                var r = await _mqttClient.ConnectAsync(options);

                if (r.ResultCode == MQTTnet.Client.Connecting.MqttClientConnectResultCode.Success)
                {
                    var msgTopicFilter = new TopicFilterBuilder().WithTopic(MQTTTopic.Msg.ToString() + "-" + App.CurrentUser.Id)
                                         .WithQualityOfServiceLevel(MqttQualityOfServiceLevel.ExactlyOnce).Build();

                    var onlineTopicFilter = new TopicFilterBuilder().WithTopic(MQTTTopic.Online.ToString())
                                            .WithQualityOfServiceLevel(MqttQualityOfServiceLevel.ExactlyOnce).Build();
                    var offlineTopicFilter = new TopicFilterBuilder().WithTopic(MQTTTopic.Offline.ToString())
                                             .WithQualityOfServiceLevel(MqttQualityOfServiceLevel.ExactlyOnce).Build();
                    var registerTopicFilter = new TopicFilterBuilder().WithTopic(MQTTTopic.Register.ToString())
                                              .WithQualityOfServiceLevel(MqttQualityOfServiceLevel.ExactlyOnce).Build();
                    var currentOptions = new MqttClientSubscribeOptions();
                    currentOptions.TopicFilters.Add(msgTopicFilter);
                    currentOptions.TopicFilters.Add(onlineTopicFilter);
                    currentOptions.TopicFilters.Add(offlineTopicFilter);
                    currentOptions.TopicFilters.Add(registerTopicFilter);
                    var cancel = new CancellationToken();
                    await _mqttClient.SubscribeAsync(currentOptions);

                    return(true);
                }
                else
                {
                    ToastHelper.Instance.ShortAlert("Server Error!");
                    return(false);
                }
                //r.Wait(cancel);
            }
            catch (Exception ex)
            {
                ToastHelper.Instance.ShortAlert("Exception!");
                return(false);
            }
        }
Пример #24
0
        public static async Task TestMany(int loopNum, int taskNum)
        {
            var fac = new MqttFactory();

            using (var cts = new CancellationTokenSource())
            {
                var sw = new System.Diagnostics.Stopwatch();
                sw.Start();
                await Task.WhenAll(
                    Task.Run(async() =>
                {
                    var svr      = fac.CreateMqttServer();
                    svr.Started += (sender, ev) =>
                    {
                        Console.WriteLine($"{sw.Elapsed} svr started");
                    };
                    svr.ClientConnected += (sender, ev) =>
                    {
                        Console.WriteLine($"{sw.Elapsed} client connected(S): {ev.Client.ClientId}");
                    };
                    svr.ClientDisconnected += (sender, ev) =>
                    {
                        Console.WriteLine($"{sw.Elapsed} client disconnected(S): {ev.Client.ClientId}");
                    };
                    var opt = new MqttServerOptionsBuilder()
                              .WithDefaultEndpoint()
                              .WithDefaultEndpointBoundIPAddress(IPAddress.Loopback)
                              .WithDefaultEndpointPort(10012)
                              .Build();
                    await svr.StartAsync(opt).ConfigureAwait(false);
                    cts.Token.WaitHandle.WaitOne();
                    await svr.StopAsync().ConfigureAwait(false);
                })
                    ,
                    Task.Run(async() =>
                {
                    await Task.Delay(100).ConfigureAwait(false);
                    var client = fac.CreateMqttClient();
                    var clientopt = new MqttClientOptionsBuilder()
                                    .WithClientId("clid")
                                    .WithTcpServer("localhost", 10012)
                                    .Build()
                    ;
                    // var opt = new ManagedMqttClientOptionsBuilder()
                    //     .WithClientOptions(clientopt)
                    //     .WithAutoReconnectDelay(TimeSpan.FromMilliseconds(100))
                    //     .Build();
                    using (var connectedEvent = new ManualResetEventSlim(false))
                    {
                        client.ApplicationMessageReceived += (sender, ev) =>
                        {
                            Console.WriteLine($"{sw.Elapsed} recv {ev.ApplicationMessage.Topic},{ev.ApplicationMessage.Payload[0]}");
                        };
                        client.Connected += (sender, ev) =>
                        {
                            Console.WriteLine($"{sw.Elapsed} client connected");
                            connectedEvent.Set();
                        };
                        client.Disconnected += (sender, ev) =>
                        {
                            Console.WriteLine($"{sw.Elapsed} client disconnected");
                        };
                        var topicFilter = new TopicFilterBuilder()
                                          .WithTopic("mytopic/A").WithAtLeastOnceQoS().Build();
                        Console.WriteLine($"{sw.Elapsed} begin connection");
                        await client.ConnectAsync(clientopt).ConfigureAwait(false);
                        // await client.StartAsync(opt).ConfigureAwait(false);
                        connectedEvent.Wait();
                        if (!client.IsConnected)
                        {
                            Console.WriteLine($"not connected");
                        }
                        else
                        {
                            Console.WriteLine($"{sw.Elapsed} connection established");
                        }
                        await client.SubscribeAsync(new[] { topicFilter }).ConfigureAwait(false);
                        Console.WriteLine($"{sw.Elapsed} subscribing done");
                        var msgbuilder = new MqttApplicationMessageBuilder();
                        msgbuilder = msgbuilder.WithTopic("mytopic/A").WithAtLeastOnceQoS();
                        var dat = new byte[1];
                        for (int i = 0; i < 100; i++)
                        {
                            await Task.Yield();
                            dat[0] = (byte)(i % 255);
                            var msg = msgbuilder.WithPayload(dat).Build();
                            await client.PublishAsync(msg).ConfigureAwait(false);
                            Console.WriteLine($"{sw.Elapsed}: publish{i}");
                        }
                        await client.UnsubscribeAsync(new[] { topicFilter.Topic }).ConfigureAwait(false);
                        await client.DisconnectAsync().ConfigureAwait(false);
                        // await client.StopAsync().ConfigureAwait(false);
                        // cts.Cancel();
                    }

                    // var opt = new MqttClientOptionsBuilder()
                    //     .Build();
                    // await client.ConnectAsync(opt).ConfigureAwait(false);
                    // var topicFilter = new TopicFilterBuilder()
                    //     .WithTopic("topic")
                    //     .Build();
                    // var subresults = await client.SubscribeAsync(new TopicFilter[] {topicFilter}).ConfigureAwait(false);
                    // foreach(var subresult in subresults)
                    // {
                    // }
                }).ContinueWith(t =>
                {
                    cts.Cancel();
                })
                    );

                sw.Stop();
            }
        }