Receiving MQTT messages

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 :slight_smile:

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

I have used M2Mqtt successfully. I referred to GitHub - vovacooper/Unity3d_MQTT: MQTT protocol running on Unity3d to eventually solve my problem.

It should be noted that MQTT over websockets do not work in Unity (MQTT over WebSockets · Issue #7 · eclipse/paho.mqtt.m2mqtt · GitHub) Other than that, it works well.

@EdwinChua – I’m trying to figure out how to do this also, using IBM Bluemix PaaS MQTT. Unlike you I do not have code implemented yet, but wanted to pass along the libraries I’m sifting through and ask you if any of them resolves implementation issues. They’re supposed to all work.

MqttDotNet

nMQTT

M2MQTT

KittyHawkMQ

StriderMqtt

Please let me know if this helps as I’m going to run into a requirement to implement this in a prototype.

Is sending and receiving process in a parallel manner?