2024-01-22 21:20:10 +01:00

65 lines
1.6 KiB
C

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
// https://mosquitto.org/api/files/mosquitto-h.html
#include <mosquitto.h>
#include "mqtt.h"
int main(int argc, char *argv[])
{
int err;
struct mosquitto *mqtt;
err = mosquitto_lib_init();
if (err)
{
fprintf(stderr, "Error initalizing mosquitto lib (%d): %s\n", err, mosquitto_strerror(err));
exit(EXIT_FAILURE);
}
mqtt = mosquitto_new(MQTT_USER, true, NULL);
if (mqtt == NULL)
{
fprintf(stderr, "Error creating mosquitto instance (%d): %s\n", errno, strerror(errno));
exit(EXIT_FAILURE);
}
err = mosquitto_username_pw_set(mqtt, MQTT_USER, MQTT_PASS);
if (err)
{
fprintf(stderr, "Error setting username & password (%d): %s\n", err, mosquitto_strerror(err));
exit(EXIT_FAILURE);
}
err = mosquitto_connect(mqtt, "openhab.sugarland.lan", 1883, 10);
if (err)
{
fprintf(stderr, "Error on connection of type ");
if (err == MOSQ_ERR_ERRNO)
{
fprintf(stderr, "system (%d): %s\n", errno, strerror(errno));
}
else
{
fprintf(stderr, "mosquitto (%d): %s\n", err, mosquitto_strerror(err));
}
exit(EXIT_FAILURE);
}
char *foo = "blah";
err = mosquitto_publish(mqtt, NULL, "/xplane/foo", strlen(foo), foo, 0, false);
if (err)
{
fprintf(stderr, "Error publishing message (%d): %s\n", err, mosquitto_strerror(err));
exit(EXIT_FAILURE);
}
err = mosquitto_disconnect(mqtt);
// ignore error
mosquitto_destroy(mqtt);
}