Hi all,
I am trying to receive MQTT messages in a Unity project. The messages are not coming in reliably. Any clues to why this might be happening?
What I’ve tried:
- Running the script as a windows console application
- Verified that the output is being published and received correctly by using MQTTlens (Chrome app), and in the console app.
- I am sending 4 messages every 5 seconds. I’ve tried varying it between 1 and 10 seconds.
What happens:
- Debug.Log in Unity shows that messages are being received, then after receiving about 30-60 messages, it stops
- Occasionally, nothing is received
My MQTT util is attached to a canvas in my scene, and is attached below.
Thank you for your help
public class CustomMqttUtils : MonoBehaviour
{
MqttClient client;
private void Start()
{
client = Connect("localhost");
Subscribe(client, "#");
}
private void Update()
{
if (!client.IsConnected)
{
client = Connect("localhost");
Subscribe(client, "#");
}
}
public static MqttClient Connect(string host)
{
MqttClient client = new MqttClient(host);
string clientId = Guid.NewGuid().ToString();
client.Connect(clientId);
return client;
}
public static void Subscribe(MqttClient client, string topic)
{
// register to message received
client.MqttMsgPublishReceived += Client_MqttMsgPublishReceived;
string clientId = Guid.NewGuid().ToString();
client.Connect(clientId);
client.Subscribe(new string[] { topic }, new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE });
}
public static void Client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
{
Debug.Log(e.Topic + " : " + Encoding.UTF8.GetString(e.Message));
}
public static void Publish(MqttClient client, string title, string value)
{
string strValue = Convert.ToString(value);
client.Publish(title, Encoding.UTF8.GetBytes(strValue));
}
}