#include #include #include // https://mosquitto.org/api/files/mosquitto-h.html #include struct mosquitto *connectMqtt(char *user, char *pass, void (*messageCallback)(struct mosquitto *, void *, const struct mosquitto_message *)) { 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; } // FIXME: I am hard coded :( 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; } mosquitto_message_callback_set(mqtt, messageCallback); 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 to %s (%d): %s\n", topic, err, mosquitto_strerror(err)); return -1; } else { return 0; } } int recvMqtt(struct mosquitto *mqtt, char *topic) { int err; err = mosquitto_subscribe(mqtt, NULL, topic, 0); if (err) { fprintf(stderr, "Error subscribing to %s (%d): %s", topic, err, mosquitto_strerror(err)); return -1; } else { return 0; } } void disconnectMqtt(struct mosquitto *mqtt) { // ignore errors mosquitto_disconnect(mqtt); mosquitto_destroy(mqtt); mosquitto_lib_cleanup(); }