Search code examples
c#xamarinxamarin.formsxamarin.androidmqtt

Sending a message to Xamarin Forms via Broker


I am using MQTT.fx and

"test.mosquitto.org"

locally as a broker. Now i want to send a message from the broker to Visual Studio (where I am connected with the client/broker). How does that work? What I have since now is:

Edit: Obviously

//await client.PublishAsync(new MqttApplicationMessage(topic, Encoding.UTF8.GetBytes($"{message}")), MqttQualityOfService.ExactlyOnce); //QOS 2

is not working at the moment...

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";
                });
        }


Solution

  • 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); 
            }