using MQTTnet.Client.Connecting;
using MQTTnet.Client.Options;
using MQTTnet.Client.Publishing;
using System.Collections.Generic;
using System.Threading.Tasks;
using Xamarin.Essentials;
using XSales.Maps.Mobile.Global;
using XSales.Maps.Mobile.Models;
namespace XSales.Maps.Mobile.Mqtt
private IMqttClientOptions manageClientOptions;
public IMqttClient mqttClient;
private IMqttClientOptions clientOptions;
private MqttFactory factory;
private static string clientId = "03cb09bf-0d04-4228-8b71-b87ed10e7492";
public Action<MqttClientConnectedEventArgs> mqttActionConnected;
public Action<MqttApplicationMessageReceivedEventArgs> mqttMessageReceived;
public MQTTclient(string url)
factory = new MqttFactory();
mqttClient = factory.CreateMqttClient();
var site = url.Split(':');
var port = Int32.Parse(site[1]);
clientOptions = new MqttClientOptionsBuilder()
.WithCommunicationTimeout(new TimeSpan(0,30,0))
.WithTcpServer(uri, port)
public void ConnectClientAsync()
if (!mqttClient.IsConnected)
mqttClient.UseDisconnectedHandler(e =>
Util.Log(Util.LogType.Debug, MethodBase.GetCurrentMethod(), JsonConvert.SerializeObject(e));
Util.Log(Util.LogType.Debug, MethodBase.GetCurrentMethod(), "### DISCONNECTED FROM SERVER ###");
mqttClient.UseConnectedHandler(async e =>
Util.Log(Util.LogType.Information, MethodBase.GetCurrentMethod(), "### CONNECTED WITH SERVER ###");
await mqttClient.SubscribeAsync(new TopicFilterBuilder().WithTopic("topic/tracking").Build());
Util.Log(Util.LogType.Debug, MethodBase.GetCurrentMethod(), "### SUBSCRIBED ###");
mqttClient.UseApplicationMessageReceivedHandler(mqttMessageReceived);
mqttClient.ConnectAsync(clientOptions, CancellationToken.None).Wait();
public async Task ClientDisconnect()
await mqttClient.DisconnectAsync();
public async Task PublishAsync(string topic, string payload, bool retainFlag = true, int qos = 2)
if (mqttClient.IsConnected)
var message = new MqttApplicationMessageBuilder()
.WithQualityOfServiceLevel(MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce)
.WithRetainFlag(retainFlag)
Util.Log(Util.LogType.Debug, MethodBase.GetCurrentMethod(),$"### SENDING MESSAGE TO SERVER ### {payload}");
await mqttClient.PublishAsync(message, CancellationToken.None);
catch (TaskCanceledException tce)
Util.Log(Util.LogType.Debug, MethodBase.GetCurrentMethod(), $"Task Cancelled: {tce.Message}");
Util.Log(Util.LogType.Debug, MethodBase.GetCurrentMethod(), $"No: {ex.Message} | {ex.Source}");