Advertisement
Guest User

Untitled

a guest
Apr 22nd, 2019
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.64 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <mosquitto.h>
  3. #include <stdlib.h>
  4. #include <string.h>
  5. #include <unistd.h>
  6.  
  7. struct mosquitto *mosq = NULL;
  8. char *topic = NULL;
  9. int rv;
  10. int MQTT_PORT = 8883;
  11. int keepalive = 60;
  12. bool clean_session = true;
  13. char *CA_CERT = "./keys/ca.crt";
  14. char *CLIENT_CRT = "./keys/client.crt";
  15. char *CLIENT_KEY = "./keys/client.key";
  16. char *MQTT_BROKER = "62.63.205.142";
  17. char *MQTT_TOPIC = "/topic";
  18.  
  19.  
  20. void mosq_log_callback(struct mosquitto *mosq, void *userdata, int level, const char *str)
  21. {
  22. switch (level)
  23. {
  24. //case MOSQ_LOG_DEBUG:
  25. //case MOSQ_LOG_INFO:
  26. //case MOSQ_LOG_NOTICE:
  27. case MOSQ_LOG_WARNING:
  28. case MOSQ_LOG_ERR:
  29. {
  30. printf("%i:%s\n", level, str);
  31. }
  32. }
  33. }
  34.  
  35. int mqtt_setup(void)
  36. {
  37. mosquitto_lib_init();
  38.  
  39. mosq = mosquitto_new(NULL, clean_session, NULL);
  40. if (!mosq)
  41. {
  42. fprintf(stderr, "Error: Out of memory.\n");
  43. return -1;
  44. }
  45.  
  46. mosquitto_log_callback_set(mosq, mosq_log_callback);
  47.  
  48. rv = mosquitto_tls_set(mosq, CA_CERT, NULL, CLIENT_CRT, CLIENT_KEY, NULL);
  49. rv = mosquitto_tls_opts_set(mosq, 1, NULL, NULL);
  50. rv = mosquitto_connect(mosq, MQTT_BROKER, MQTT_PORT, keepalive);
  51.  
  52. if (rv != 0)
  53. fprintf(stderr, "mosquitto_connect failed. rv = %d\n", rv);
  54.  
  55. return 0;
  56. }
  57.  
  58. int main(int argc, char *argv[])
  59. {
  60. if (mqtt_setup() == 0)
  61. {
  62. printf("Setup done, connected to broker. \n");
  63.  
  64. rv = mosquitto_publish(mosq, NULL, MQTT_TOPIC, 11, "hello world", 0, false);
  65.  
  66. if (rv != 0)
  67. {
  68. fprintf(stderr, "mosquitto_publish failed. rv = %d\n", rv);
  69. }
  70. else
  71. {
  72. printf("mosquitto_publish successful. \n");
  73. }
  74. mosquitto_loop_forever(mosq, -1, 1);
  75. return 0;
  76. }
  77. else
  78. {
  79. printf("setup failed");
  80. return -1;
  81. }
  82.  
  83. mosquitto_lib_cleanup();
  84. return 0;
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement