Hi, I been working on a small peice of code in Xamarin Forms (my first project) to send a mqtt message upon a button press.
Ive written the code to publish the mqtt message to the test.mosquitto.org server within a C# console app and that seems to be working OK.
`using System;
using System.Net.Mqtt;
using System.Text;
namespace MqttTest.Client
{
class Program
{
const string topic = "test/test/button";
static void Main (string[] args)
{
var config = new MqttConfiguration { Port = 1883 };
var client = MqttClient.CreateAsync("test.mosquitto.org", config).Result;
var clientId = "myClientID";
string message = "test";
client.ConnectAsync (new MqttClientCredentials (clientId)).Wait ();
client.SubscribeAsync (topic, MqttQualityOfService.AtLeastOnce).Wait ();
//Publishes "message" Var
client.PublishAsync(new MqttApplicationMessage(topic, Encoding.UTF8.GetBytes($"{message}")), MqttQualityOfService.AtLeastOnce).Wait();
}
}
}
`
Ive now written a very simple xamarin cross platform app with 1 button, 1 button_clicked event and the code for the button clicked event which was written in the above console app.
`using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using System.Net.Mqtt;
namespace App1
{
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
}
const string topic = "test/test/button";
private void Button_Clicked(object sender, EventArgs e)
{
var config = new MqttConfiguration { Port = 1883 };
var client = MqttClient.CreateAsync("test.mosquitto.org", config).Result;
var clientId = "clientIdhGHvpYY9uM";
string message = "Hello";
client.ConnectAsync(new MqttClientCredentials(clientId)).Wait();
client.SubscribeAsync(topic, MqttQualityOfService.AtLeastOnce).Wait();
client.PublishAsync(new MqttApplicationMessage(topic, Encoding.UTF8.GetBytes($"{message}")), MqttQualityOfService.AtLeastOnce).Wait();
}
}
}
`
Upon testing the app in the emulator, it loads up OK but when I click the button, it freezes the app and does not publish to the test mqtt server.
Can anyone offer any advice on how to get this working
thank you