Ejemplo n.º 1
0
        private async void Button_Click_1(object sender, RoutedEventArgs e)
        {
            try
            {
                var message = new MqttApplicationMessageBuilder()
                              .WithTopic(txtTopic.Text)
                              .WithPayload(txtMessage.Text)
                              .WithExactlyOnceQoS()
                              //.WithRetainFlag()
                              .Build();

                //for (int i= 0; i < 50; i++) {
                //await mqttClient.PublishAsync(message);

                var response = await rpcClient.ExecuteAsync(timeout, "Reply", "testRPC", qos);

                Console.WriteLine("RPC Response: " + Encoding.UTF8.GetString(response));


                //await mqttClient.SubscribeAsync(new TopicFilterBuilder().WithTopic("MQTTnet.RPC/+/Response").Build());
            }
            catch (Exception ex) {
                Console.WriteLine("Error When Sending RPC:" + ex);
            }
            //}
        }
Ejemplo n.º 2
0
        public IEnumerable <string> Get()
        {
            var factory    = new MqttFactory();
            var mqttClient = factory.CreateMqttClient();
            var rpcClient  = new MqttRpcClient(mqttClient);

            var options = new MqttClientOptionsBuilder()
                          .WithWebSocketServer("10.195.97.228:1883/mqtt")
                          .Build();

            mqttClient.ConnectAsync(options);


            var message = new MqttApplicationMessageBuilder()
                          .WithTopic("MyTopic")
                          .WithPayload("Hello World")
                          .WithExactlyOnceQoS()
                          .WithRetainFlag()
                          .Build();

            var timeout  = TimeSpan.FromSeconds(5);
            var qos      = MqttQualityOfServiceLevel.AtMostOnce;
            var response = rpcClient.ExecuteAsync(timeout, "myMethod", "Hello World", qos);

            return(new string[] { "value1", "value2" });
        }
Ejemplo n.º 3
0
        public async Task Execute_Success_MQTT_V5_Mixed_Clients()
        {
            using (var testEnvironment = CreateTestEnvironment())
            {
                await testEnvironment.StartServer();

                var responseSender = await testEnvironment.ConnectClient();

                await responseSender.SubscribeAsync("MQTTnet.RPC/+/ping", MqttQualityOfServiceLevel.AtMostOnce);

                responseSender.ApplicationMessageReceivedAsync += async e =>
                {
                    Assert.IsNull(e.ApplicationMessage.ResponseTopic);
                    await responseSender.PublishStringAsync(e.ApplicationMessage.Topic + "/response", "pong");
                };

                var requestSender = await testEnvironment.ConnectClient(new MqttClientOptionsBuilder().WithProtocolVersion(MqttProtocolVersion.V500));

                using (var rpcClient = new MqttRpcClient(requestSender, new MqttRpcClientOptionsBuilder().Build()))
                {
                    var response = await rpcClient.ExecuteAsync(TimeSpan.FromSeconds(5), "ping", "", MqttQualityOfServiceLevel.AtMostOnce);

                    Assert.AreEqual("pong", Encoding.UTF8.GetString(response));
                }
            }
        }
Ejemplo n.º 4
0
        async Task Execute_Success(MqttQualityOfServiceLevel qosLevel, MqttProtocolVersion protocolVersion)
        {
            using (var testEnvironment = new TestEnvironment(TestContext))
            {
                await testEnvironment.StartServer();

                var responseSender = await testEnvironment.ConnectClient(new MqttClientOptionsBuilder().WithProtocolVersion(protocolVersion));

                await responseSender.SubscribeAsync("MQTTnet.RPC/+/ping", qosLevel);

                responseSender.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(async e =>
                {
                    await responseSender.PublishAsync(e.ApplicationMessage.Topic + "/response", "pong");
                });

                var requestSender = await testEnvironment.ConnectClient();

                using (var rpcClient = new MqttRpcClient(requestSender, new MqttRpcClientOptionsBuilder().Build()))
                {
                    var response = await rpcClient.ExecuteAsync(TimeSpan.FromSeconds(5), "ping", "", qosLevel);

                    Assert.AreEqual("pong", Encoding.UTF8.GetString(response));
                }
            }
        }
Ejemplo n.º 5
0
        /// <summary>
        ///     methodName : xxx.yyy
        /// </summary>
        /// <param name="methodName"></param>
        /// <param name="msg"></param>
        /// <param name="timeoutSeconds"></param>
        /// <returns></returns>
        public async Task <string> RpcPub(string methodName, string msg, int timeoutSeconds = 15)
        {
            var rpcClient = new MqttRpcClient(_client.InternalClient.InternalClient, new MqttRpcClientOptions());

            var response = await rpcClient
                           .ExecuteAsync(TimeSpan.FromSeconds(timeoutSeconds), methodName, msg,
                                         MqttQualityOfServiceLevel.ExactlyOnce)
                           .ConfigureAwait(false);

            return(Encoding.UTF8.GetString(response));
        }
Ejemplo n.º 6
0
        public async Task Execute_Timeout()
        {
            using (var testEnvironment = new TestEnvironment())
            {
                await testEnvironment.StartServerAsync();

                var requestSender = await testEnvironment.ConnectClientAsync();

                var rpcClient = new MqttRpcClient(requestSender);
                await rpcClient.ExecuteAsync(TimeSpan.FromSeconds(2), "ping", "", MqttQualityOfServiceLevel.AtMostOnce);
            }
        }
Ejemplo n.º 7
0
        public async Task Execute_With_Custom_Topic_Names()
        {
            using (var testEnvironment = new TestEnvironment(TestContext))
            {
                await testEnvironment.StartServerAsync();

                var requestSender = await testEnvironment.ConnectClientAsync();

                var rpcClient = new MqttRpcClient(requestSender, new MqttRpcClientOptionsBuilder().WithTopicGenerationStrategy(new TestTopicStrategy()).Build());
                await rpcClient.ExecuteAsync(TimeSpan.FromSeconds(2), "ping", "", MqttQualityOfServiceLevel.AtMostOnce);
            }
        }
Ejemplo n.º 8
0
        private async void ExecuteRpc(object sender, RoutedEventArgs e)
        {
            var qos = MqttQualityOfServiceLevel.AtMostOnce;

            if (RpcQoS1.IsChecked == true)
            {
                qos = MqttQualityOfServiceLevel.AtLeastOnce;
            }

            if (RpcQoS2.IsChecked == true)
            {
                qos = MqttQualityOfServiceLevel.ExactlyOnce;
            }

            var payload = new byte[0];

            if (RpcText.IsChecked == true)
            {
                payload = Encoding.UTF8.GetBytes(RpcPayload.Text);
            }

            if (RpcBase64.IsChecked == true)
            {
                payload = Convert.FromBase64String(RpcPayload.Text);
            }


            try
            {
                var rpcClient = new MqttRpcClient(_mqttClient);
                await rpcClient.EnableAsync();

                var response = await rpcClient.ExecuteAsync(TimeSpan.FromSeconds(5), RpcMethod.Text, payload, qos);

                await rpcClient.DisableAsync();

                RpcResponses.Items.Add(RpcMethod.Text + " >>> " + Encoding.UTF8.GetString(response));
            }
            catch (MqttCommunicationTimedOutException)
            {
                RpcResponses.Items.Add(RpcMethod.Text + " >>> [TIMEOUT]");
            }
        }
Ejemplo n.º 9
0
        public async Task InitializePublisher(ClientConfiguration configuration)
        {
            var options = new MqttClientOptionsBuilder()
                          .WithClientId(configuration.ClientId)
                          .WithCleanSession(false)
                          .WithTcpServer(configuration.Host, configuration.Port)
                          .WithCredentials(configuration.Username, configuration.Password)
                          .WithKeepAlivePeriod(TimeSpan.FromMilliseconds(configuration.KeepAlivePeriod))
                          .WithCommunicationTimeout(TimeSpan.FromMilliseconds(configuration.CommunicationTimeout)).Build();

            var mqttClient    = new MqttFactory().CreateMqttClient();
            var connectResult = await mqttClient.ConnectAsync(options);

            Console.WriteLine($"Publisher connection result : {connectResult.ResultCode}");

            var rpcOptions = new MqttRpcClientOptions()
            {
                TopicGenerationStrategy = new DefaultMqttRpcClientTopicGenerationStrategy()
            };

            var rpcClient = new MqttRpcClient(mqttClient, rpcOptions);

            var command = new CommandDto
            {
                Id      = 1,
                Message = "Say Hello world!"
            };

            var payload = JsonConvert.SerializeObject(command);

            Console.WriteLine($"Publisher requesting work \"DoWork\" with Id : 1");

            var responseMqtt = await rpcClient.ExecuteAsync(TimeSpan.FromSeconds(50), "DoWork", payload, MqttQualityOfServiceLevel.AtLeastOnce);

            var response = Encoding.Default.GetString(responseMqtt);

            Console.WriteLine($"Publisher got response : {response}");
        }
Ejemplo n.º 10
0
        public async Task Execute_Success()
        {
            using (var testEnvironment = new TestEnvironment())
            {
                await testEnvironment.StartServerAsync();

                var responseSender = await testEnvironment.ConnectClientAsync();

                await responseSender.SubscribeAsync("MQTTnet.RPC/+/ping");

                responseSender.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(async e =>
                {
                    await responseSender.PublishAsync(e.ApplicationMessage.Topic + "/response", "pong");
                });

                var requestSender = await testEnvironment.ConnectClientAsync();

                var rpcClient = new MqttRpcClient(requestSender);
                var response  = await rpcClient.ExecuteAsync(TimeSpan.FromSeconds(5), "ping", "", MqttQualityOfServiceLevel.AtMostOnce);

                Assert.AreEqual("pong", Encoding.UTF8.GetString(response));
            }
        }
Ejemplo n.º 11
0
        public async Task Execute_Timeout_MQTT_V5_Mixed_Clients()
        {
            using (var testEnvironment = new TestEnvironment(TestContext))
            {
                await testEnvironment.StartServer();

                var responseSender = await testEnvironment.ConnectClient();

                await responseSender.SubscribeAsync("MQTTnet.RPC/+/ping", MqttQualityOfServiceLevel.AtMostOnce);

                responseSender.ApplicationMessageReceivedAsync += async e =>
                {
                    Assert.IsNull(e.ApplicationMessage.ResponseTopic);
                    await PlatformAbstractionLayer.CompletedTask;
                };

                var requestSender = await testEnvironment.ConnectClient(new MqttClientOptionsBuilder().WithProtocolVersion(MqttProtocolVersion.V500));

                using (var rpcClient = new MqttRpcClient(requestSender, new MqttRpcClientOptionsBuilder().Build()))
                {
                    var response = await rpcClient.ExecuteAsync(TimeSpan.FromSeconds(2), "ping", "", MqttQualityOfServiceLevel.AtMostOnce);
                }
            }
        }