diff options
Diffstat (limited to 'analysis/rtt/src/mqtt_client.c')
| -rw-r--r-- | analysis/rtt/src/mqtt_client.c | 48 |
1 files changed, 48 insertions, 0 deletions
diff --git a/analysis/rtt/src/mqtt_client.c b/analysis/rtt/src/mqtt_client.c new file mode 100644 index 0000000..43a06d8 --- /dev/null +++ b/analysis/rtt/src/mqtt_client.c | |||
| @@ -0,0 +1,48 @@ | |||
| 1 | #include "mqtt_client.h" | ||
| 2 | #include "logger.h" | ||
| 3 | #include <stdio.h> | ||
| 4 | #include <stdlib.h> | ||
| 5 | |||
| 6 | #define WINDOW_SEC 1 | ||
| 7 | |||
| 8 | static void on_message(struct mosquitto *mosq, void *userdata, | ||
| 9 | const struct mosquitto_message *msg); | ||
| 10 | |||
| 11 | int mqtt_client_init(mqtt_client_t *client, const char *broker_address, | ||
| 12 | int port, const char *topic) { | ||
| 13 | mosquitto_lib_init(); | ||
| 14 | client->mosq = mosquitto_new(NULL, true, NULL); | ||
| 15 | if (!client->mosq) { | ||
| 16 | fprintf(stderr, "Cannot create MQTT client\n"); | ||
| 17 | return 1; | ||
| 18 | } | ||
| 19 | |||
| 20 | mosquitto_message_callback_set(client->mosq, on_message); | ||
| 21 | |||
| 22 | if (mosquitto_connect(client->mosq, broker_address, port, 60) != | ||
| 23 | MOSQ_ERR_SUCCESS) { | ||
| 24 | fprintf(stderr, "Nie można połączyć się z brokerem MQTT\n"); | ||
| 25 | return 1; | ||
| 26 | } | ||
| 27 | |||
| 28 | if (mosquitto_subscribe(client->mosq, NULL, topic, 0) != MOSQ_ERR_SUCCESS) { | ||
| 29 | fprintf(stderr, "Cannot subscribe to topic\n"); | ||
| 30 | return 1; | ||
| 31 | } | ||
| 32 | |||
| 33 | return 0; | ||
| 34 | } | ||
| 35 | |||
| 36 | void mqtt_client_cleanup(mqtt_client_t *client) { | ||
| 37 | mosquitto_destroy(client->mosq); | ||
| 38 | mosquitto_lib_cleanup(); | ||
| 39 | } | ||
| 40 | |||
| 41 | void mqtt_client_loop(mqtt_client_t *client) { | ||
| 42 | mosquitto_loop_forever(client->mosq, -1, 1); | ||
| 43 | } | ||
| 44 | |||
| 45 | static void on_message(struct mosquitto *mosq, void *userdata, | ||
| 46 | const struct mosquitto_message *msg) { | ||
| 47 | logger_handle_message(msg->payload, msg->payloadlen); | ||
| 48 | } | ||
