通过Broker向Xamarin Forms发送消息

fzwojiic  于 2022-12-25  发布在  其他
关注(0)|答案(1)|浏览(155)

我使用MQTT.fx和
"test.mosquitto.org"
作为代理。现在我想从代理发送一个消息到Visual Studio(在那里我与客户端/代理连接)。这是如何工作的?我现在有:

    • 编辑:**显而易见

//等待客户端.发布异步(新的MqttApplicationMessage(主题,编码. UTF8.获取字节($" {消息} ")),MqttQualityOfService. ExactlyOnce); //服务质量2
目前无法运行...

private async void OnButton2Clicked(object sender, EventArgs e)
        {
            try 
            {   
                testLabel2.Text = "test";
                await client.SubscribeAsync(topic, MqttQualityOfService.ExactlyOnce); //QOS 2
                //await client.PublishAsync(new MqttApplicationMessage(topic, Encoding.UTF8.GetBytes($"{message}")), MqttQualityOfService.ExactlyOnce); //QOS 2
                OnMessageReceived();
            }

            catch (Exception ex)
            {
                testLabel2.Text = "Ausnahme gefunden: " + ex.Message;
            }
        }

        ///////////////////////////////////////////////
        private void OnMessageReceived()
        {
                MessagingCenter.Subscribe<IMqttClient>(topic, "Hallooo", (sender) =>
                {
                    testLabel2.Text = "Du hast eine Nachricht bekommen";
                });
        }
erhoui1w

erhoui1w1#

private async void SubscriptionTemp() **// Here I make a method, to subscribe a temperature.**
        {
            if (MainPage.client2.IsConnected) **//Check if IMqttClient is connected**
            {
                await MainPage.client2.SubscribeAsync(topicTemp, MqttQualityOfService.AtMostOnce);       // QOS 0

                MainPage.client2
                        .MessageStream
                        .Where(msg => msg.Topic == topicTemp)
                        .Subscribe(msg => onTempRelayReceived(msg));
            }
        }

        private void onTempRelayReceived(MqttApplicationMessage msg)
        {
            string msgEncoded = (Encoding.UTF8.GetString(msg.Payload)); // **Here I assign the payload received from mqtt as a string.**
            tempRelay = double.Parse(msgEncoded); 
        }

相关问题