Example code of MQTT subscribing and publishing - winnubstj/Gimbl GitHub Wiki
Subscribing and publishing to topics are handled by a custom 'channel' class. A channel object is instantiated with the expected message format supplied as a generic type parameter. The user can add listener functions to this event.
Here is an example of subscribing to a MQTT topic ("Unity/") that returns a message of a known format.
// class describing the message format.
public class MSG
{
public string a;
public int b;
}
// Setup Listener.
MQTTChannel<MSG> channel = new MQTTChannel<MSG>("Unity/");
channel.Event.AddListener(OnMessage);
// Send data
MSG msg = new MSG() { a = "Hello!", b = 200 };
channel.Send(msg);
// Called function.
void OnMessage(MSG msg)
{
Debug.Log(msg.a);
}
You can also setup a more simple "trigger"-like channel if you just want to be informed of a message being send on a specific topic:
// Trigger example.
MQTTChannel trigger = new MQTTChannel("Unity/");
trigger.Event.AddListener(OnTrigger);
trigger.Send();
void OnTrigger()
{
Debug.Log("Got Triggered!");
}