Skip to content

Instantly share code, notes, and snippets.

@Vienchau
Last active April 18, 2023 08:30
Show Gist options
  • Save Vienchau/5a59977871802b44a98da1768a251b85 to your computer and use it in GitHub Desktop.
Save Vienchau/5a59977871802b44a98da1768a251b85 to your computer and use it in GitHub Desktop.
Simple mosquitto subscribe implement
#include "curldefine.h"
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <mosquitto.h>
#include <string.h>
/*SUB TASK DEFINE*/
#define TOPIC "MQTT/Topic1"
#define CERT_EMQX "/tmp/tmp/broker.emqx.io-ca.crt"
#define BROKER_EMQX "broker.emqx.io"
void on_message(struct mosquitto *mosq, void *obj, const struct mosquitto_message *msg)
{
}
void on_connect(struct mosquitto *mosq, void *obj, int rc)
{
printf("ID: %d\n", *(int *)obj);
if (rc)
{
printf("TASK 3 could not connect to broker (In on_connect)! Error code: %d \n", rc);
exit(-1);
}
mosquitto_subscribe(mosq, NULL, TOPIC, 0);
}
int main()
{
int rc, id = 3;
struct mosquitto *mosq;
mosquitto_lib_init();
mosq = mosquitto_new("TASK", true, &id);
if (mosq == NULL)
{
fprintf(stderr, "Error: Out of memory.\n");
return 1;
}
// printf("mosq pointer address: %d\n", mosq);
if (mosq)
{
/*Connect and Subscribe message configure*/
mosquitto_connect_callback_set(mosq, on_connect);
mosquitto_message_callback_set(mosq, on_message);
/*Openssl configure*/
mosquitto_tls_insecure_set(mosq, true);
mosquitto_tls_set(mosq, CERT_EMQX, NULL, NULL, NULL, NULL);
// mosquitto_threaded_set(mosq, true);
rc = mosquitto_connect(mosq, BROKER_EMQX, 8883, 60);
if (rc != MOSQ_ERR_SUCCESS)
{
printf("go throught error fuction! \n");
mosquitto_destroy(mosq);
fprintf(stderr, "Error: %s\n", mosquitto_strerror(rc));
return 1;
}
printf("go throught connect fuction! \n");
}
if (rc != MOSQ_ERR_SUCCESS)
{
printf("Client could not connect to broker! Error code: %d \n", rc);
return 1;
}
mosquitto_loop_forever(mosq, -1, 1);
mosquitto_disconnect(mosq);
mosquitto_destroy(mosq);
mosquitto_lib_cleanup();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment