74 lines
1.7 KiB
C
74 lines
1.7 KiB
C
#include <stdio.h>
|
|
|
|
#include <errno.h>
|
|
#include <string.h>
|
|
|
|
// https://mosquitto.org/api/files/mosquitto-h.html
|
|
#include <mosquitto.h>
|
|
|
|
struct mosquitto *connectMqtt(char *user, char *pass)
|
|
{
|
|
int err;
|
|
struct mosquitto *mqtt;
|
|
|
|
err = mosquitto_lib_init();
|
|
if (err)
|
|
{
|
|
fprintf(stderr, "Error initalizing mosquitto lib (%d): %s\n", err, mosquitto_strerror(err));
|
|
return NULL;
|
|
}
|
|
|
|
mqtt = mosquitto_new(user, true, NULL);
|
|
if (mqtt == NULL)
|
|
{
|
|
fprintf(stderr, "Error creating mosquitto instance (%d): %s\n", errno, strerror(errno));
|
|
return NULL;
|
|
}
|
|
|
|
err = mosquitto_username_pw_set(mqtt, user, pass);
|
|
if (err)
|
|
{
|
|
fprintf(stderr, "Error setting username & password (%d): %s\n", err, mosquitto_strerror(err));
|
|
return NULL;
|
|
}
|
|
|
|
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));
|
|
}
|
|
return NULL;
|
|
}
|
|
|
|
return mqtt;
|
|
}
|
|
|
|
int sendMqtt(struct mosquitto *mqtt, char *topic, char *payload, int payloadLength)
|
|
{
|
|
int err;
|
|
|
|
err = mosquitto_publish(mqtt, NULL, topic, payloadLength, payload, 0, false);
|
|
if (err)
|
|
{
|
|
fprintf(stderr, "Error publishing message (%d): %s\n", err, mosquitto_strerror(err));
|
|
return -1;
|
|
}
|
|
else
|
|
{
|
|
return 0;
|
|
}
|
|
}
|
|
|
|
void disconnectMqtt(struct mosquitto *mqtt)
|
|
{
|
|
// ignore errors
|
|
mosquitto_disconnect(mqtt);
|
|
mosquitto_destroy(mqtt);
|
|
} |