To use MQTT-C, follow these core steps:
- Instantiate a
struct mqtt_client. - Initialize the client using
mqtt_init(). - Connect to a broker using
mqtt_connect(). - Use
mqtt_subscribe() to listen to topics or mqtt_publish() to send messages.
MQTT-C is designed to be portable, thread-safe, and lightweight, making it suitable for both embedded systems and PCs.
struct mqtt_client client; /* instantiate the client */
mqtt_init(&client, ...); /* initialize the client */
mqtt_connect(&client, ...); /* send a connection request to the broker. */
/* subscribe to "toaster/temperature" with a max QoS level of 0 */
mqtt_subscribe(&client, "toaster/temperature", 0);
/* publish coffee temperature with a QoS level of 1 */
int temperature = 67;
mqtt_publish(&client, "coffee/temperature", &temperature, sizeof(int), MQTT_PUBLISH_QOS_1);