Skip to content

Instantly share code, notes, and snippets.

@prohazko2
Last active October 6, 2020 23:22
Show Gist options
  • Save prohazko2/ff9ed664d92aa5c9b1d0752ff2bae4e9 to your computer and use it in GitHub Desktop.
Save prohazko2/ff9ed664d92aa5c9b1d0752ff2bae4e9 to your computer and use it in GitHub Desktop.
libmosquitto test
# > sudo apt install libmosquitto-dev
# > make
# > ./mqtt
mqtt: mqtt.o
$(CC) $(LDFLAGS) mqtt.o -o mqtt -lmosquitto
mqtt.o: mqtt.c
$(CC) $(CFLAGS) -c mqtt.c -lmosquitto
clean:
rm *.o mqtt
#include <signal.h>
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <mosquitto.h>
#define MQTT_ID "mqtt-<clientid>"
#define MQTT_HOST "sandbox.rightech.io"
#define MQTT_PORT 1883
static int run = 1;
void handle_signal(int s)
{
run = 0;
}
void connect_callback(struct mosquitto *mosq, void *obj, int result)
{
printf("connect callback, rc=%d\n", result);
}
void message_callback(struct mosquitto *mosq, void *obj, const struct mosquitto_message *message)
{
bool match = 0;
printf("got message '%.*s' for topic '%s'\n", message->payloadlen, (char *)message->payload, message->topic);
}
int main(int argc, char *argv[])
{
uint8_t reconnect = true;
struct mosquitto *mosq;
int rc = 0;
signal(SIGINT, handle_signal);
signal(SIGTERM, handle_signal);
mosquitto_lib_init();
mosq = mosquitto_new(MQTT_ID, true, 0);
if (mosq)
{
mosquitto_connect_callback_set(mosq, connect_callback);
mosquitto_message_callback_set(mosq, message_callback);
rc = mosquitto_connect(mosq, MQTT_HOST, MQTT_PORT, 60);
mosquitto_subscribe(mosq, NULL, "/#", 0);
while (run)
{
rc = mosquitto_loop(mosq, -1, 1);
if (run && rc)
{
printf("connection error!\n");
sleep(10);
mosquitto_reconnect(mosq);
}
}
mosquitto_destroy(mosq);
}
mosquitto_lib_cleanup();
return rc;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment