SystemAgent/src/impl/user_mqtt_impl.c

60 lines
1.7 KiB
C
Raw Normal View History

2021-07-18 17:26:17 +00:00
#include <stdio.h>
#include <string.h>
2021-07-25 18:11:36 +00:00
#include <time.h>
#include <errno.h>
2021-07-18 17:26:17 +00:00
#include "user_common.h"
2021-07-18 17:26:17 +00:00
#include "impl/user_mqtt_impl.h"
2021-07-25 15:22:04 +00:00
#include "utils/user_log_util.h"
// TODO: Add callbacks here as static functions.
2021-07-25 18:11:36 +00:00
int user_mqtt_impl_init(user_mqtt_impl_t *handle) {
int mosq_major, mosq_minor, mosq_revision;
mosquitto_lib_init();
mosquitto_lib_version(&mosq_major, &mosq_minor, &mosq_revision);
USER_LOG(USER_LOG_INFO, "libmosquitto library version %d.%d rev. %d.", mosq_major, mosq_minor, mosq_revision);
// Init mosquitto instance.
handle->mosq = mosquitto_new("ID", false, handle);
if(handle->mosq == NULL) {
int err = errno;
USER_LOG(USER_LOG_ERROR, "mosquitto client creation failed, reason: (%s).", strerror(err));
return -1;
}
// Enable multi-thread support.
mosquitto_threaded_set(handle->mosq, true);
2021-07-25 18:11:36 +00:00
return 0;
}
int user_mqtt_impl_deinit(user_mqtt_impl_t *handle) {
mosquitto_destroy(handle->mosq);
2021-07-25 18:11:36 +00:00
mosquitto_lib_cleanup();
return 0;
}
int user_mqtt_network_loop(user_mqtt_impl_t *handle) {
return mosquitto_loop(handle->mosq, 1000, 1);
}
2021-07-18 17:26:17 +00:00
mqtt_influx_ret_t user_mqtt_get_nsec_timestamp_cb(user_mqtt_impl_t *handle, char *timestamp_string) {
UNUSED(handle);
2021-07-25 18:11:36 +00:00
struct timespec ts;
clock_gettime(CLOCK_REALTIME, &ts);
uint64_t ts_int = ts.tv_sec * 1e9 + ts.tv_nsec;
sprintf(timestamp_string, "%lu", ts_int);
2021-07-18 17:26:17 +00:00
return MQTT_INFLUX_OK;
}
mqtt_influx_ret_t user_mqtt_publish_message_cb(user_mqtt_impl_t *handle, char *data) {
2021-07-25 18:11:36 +00:00
USER_LOG(USER_LOG_DEBUG, "MQTT message: %s", data);
2021-07-25 15:22:04 +00:00
// TODO: Exception handling required.
mosquitto_publish(handle->mosq, NULL, handle->topic, strlen(data), data, 1, false);
2021-07-25 15:22:04 +00:00
return MQTT_INFLUX_OK;
2021-07-18 17:26:17 +00:00
}