Roger Light has just committed not one, but two lovely new functions called mosquitto_subscribe_simple()
and mosquitto_subscribe_callback()
to the develop branch of libmosquitto.
This first, mosquitto_subscribe_simple()
, allows us to wait for a broker to give us a specific number of messages in just one function.
#include <stdio.h>
#include <mosquitto.h>
#define mqtt_host "127.0.0.1"
#define mqtt_port 1883
#define COUNT 1
int main(int argc, char *argv[])
{
struct mosquitto_message *msg, *mp;
int n, rc;
mosquitto_lib_init();
rc = mosquitto_subscribe_simple(
&msg, /* struct mosquitto_message ** */
COUNT, /* desired message count */
1, /* want retained */
"config/param", /* topic */
0, /* QoS */
mqtt_host, /* host */
mqtt_port, /* port */
"jp-one", /* clientID */
60, /* keepalive */
1, /* clean session */
NULL, /* username */
NULL, /* password */
NULL, /* libmosquitto_will */
NULL /* libmosquitto_tls */
);
if (rc != MOSQ_ERR_SUCCESS) {
printf("rc = %d %s\n", rc, mosquitto_strerror(rc));
goto out;
}
for (n = 0, mp = msg; n < COUNT; n++, mp++) {
printf("%s %s\n", mp->topic, mp->payload);
}
out:
mosquitto_lib_cleanup();
return (rc);
}
Assume I have a topic with a retained value which I want in a C program. By configuring COUNT
to be 1
and setting want retain to true, mosquitto_subscribe_simple()
will connect to the specified broker, subscribe to the topic, wait for the message, and immediately return, making the message available in msg
.
If we ask for more than one message, mosquitto_subscribe_simple()
will wait accordingly.
The second new function is called mosquitto_subscribe_callback()
and expects a callback function you provide. This callback function is invoked for each and every message you’ve subscribed to. You return 0
from your function to have libmosquitto continue to listen for messages, or 1
to have it stop.
#include <stdio.h>
#include <mosquitto.h>
#define mqtt_host "127.0.0.1"
#define mqtt_port 1883
int func(struct mosquitto *mosq, void *userdata, const struct mosquitto_message *m)
{
char *ud = (char *)userdata;
printf("%s -> %s %s\n", ud, m->topic, m->payload);
return (0); /* True to break out of loop */
}
int main(int argc, char *argv[])
{
int rc;
mosquitto_lib_init();
rc = mosquitto_subscribe_callback(
func, /* callback function */
"hello", /* user data for callback */
"test", /* topic */
0, /* QoS */
mqtt_host, /* host */
mqtt_port, /* port */
"jp-cb", /* clientID */
60, /* keepalive */
1, /* clean session */
NULL, /* username */
NULL, /* password */
NULL, /* libmosquitto_will */
NULL /* libmosquitto_tls */
);
if (rc != MOSQ_ERR_SUCCESS) {
printf("rc = %d %s\n", rc, mosquitto_strerror(rc));
}
mosquitto_lib_cleanup();
return (rc);
}
The user data you specify on invocation is passed directly into our func()
.
Roger has added a similar routines to Paho Python, which he also maintains. These are currently in the develop branch.