messageQueue.c 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. #include "messageQueue.h"
  2. #if ORT_MQTT_ENABLED == 1
  3. // includes
  4. #include <stdio.h>
  5. #include <string.h>
  6. #include <stdlib.h>
  7. #include "mosquitto.h"
  8. #include "runtime.h"
  9. #define MQTT_HOST "localhost"
  10. #define MQTT_PORT 1883
  11. // TODO: add ifndef to these ones
  12. #define MQTT_QOS 0
  13. #define MQTT_KEEPALIVE 60
  14. #define MQTT_MAX_CONNECT_TRIES 10
  15. #define MQTT_CONNECT_WAIT 5
  16. // global vars
  17. struct topicList {
  18. char** list;
  19. int numElements;
  20. } ;
  21. struct mosquitto *mosqPtrs[MQ_NUM_CLIENTS];
  22. // local functions
  23. void mqtt_connect_callback(struct mosquitto *mosq, void *userdata, int result)
  24. {
  25. int i;
  26. if(!result){
  27. /* invoke js callback on successful connect. */
  28. // printf("Connect with userdata '%s'\n", (char*)userdata);
  29. invokeCallback((char*)userdata);
  30. }else{
  31. fprintf(stderr, "Connect failed\n");
  32. }
  33. }
  34. void mqtt_subscribe_callback(struct mosquitto *mosq, void *userdata, int mid, int qos_count, const int *granted_qos)
  35. {
  36. int i;
  37. char buf[MAX_CHAR_LEN];
  38. printf("Subscribed (mid: %d): %d", mid, granted_qos[0]);
  39. for(i=1; i<qos_count; i++){
  40. printf(", %d", granted_qos[i]);
  41. }
  42. printf("\n");
  43. // invoke callback if any
  44. sprintf(buf, "s%d", mid);
  45. invokeCallback(buf);
  46. }
  47. void mqtt_message_callback(struct mosquitto *mosq, void *userdata, const struct mosquitto_message *message)
  48. {
  49. int i;
  50. char payload[MAX_PAYLOAD_SIZE];
  51. printf("Message arrived to topic: %s, message is %d chars long\n", message->topic, message->payloadlen);
  52. // pass the topic and message to the runtime
  53. handleMessage((char*)message->topic, (char*)message->payload);
  54. }
  55. void mqtt_disconnect_callback(struct mosquitto *mosq, void *userdata, int rc) {
  56. printf("Message Queue disconnected - %s (%d)\n", mosquitto_strerror(rc), rc);
  57. // TODO: potentially attempt to reconnect here?
  58. }
  59. char *_generateRandomChars(int length, char charset[]) {
  60. char *randomString = NULL;
  61. if (length) {
  62. randomString = malloc(sizeof(char) * ((size_t)length +1));
  63. if (randomString) {
  64. for (int n = 0;n < length;n++) {
  65. int key = rand() % (int)(sizeof(charset) -1);
  66. randomString[n] = charset[key];
  67. }
  68. randomString[(size_t)length] = '\0';
  69. }
  70. }
  71. return randomString;
  72. }
  73. char *generateRandomString(int length) {
  74. static char charset[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  75. return _generateRandomChars(length, charset);
  76. }
  77. char *generateRandomNumber(int length) {
  78. static char charset[] = "0123456789";
  79. return _generateRandomChars(length, charset);
  80. }
  81. /* Returns an integer in the range [0, n).
  82. *
  83. * Uses rand(), and so is affected-by/affects the same seed.
  84. */
  85. int generateRandomInteger(int n) {
  86. if ((n - 1) == RAND_MAX) {
  87. return rand();
  88. } else {
  89. // Supporting larger values for n would requires an even more
  90. // elaborate implementation that combines multiple calls to rand()
  91. // assert (n <= RAND_MAX);
  92. // Chop off all of the values that would cause skew...
  93. int end = RAND_MAX / n; // truncate skew
  94. // assert (end > 0)
  95. end *= n;
  96. // ... and ignore results from rand() that fall above that limit.
  97. // (Worst case the loop condition should succeed 50% of the time,
  98. // so we can expect to bail out of this loop pretty quickly.)
  99. int r;
  100. while ((r = rand()) >= end);
  101. return r % n;
  102. }
  103. }
  104. int _setTls(int clientType, char *cafilePath, char* certfilePath, char* keyfilePath) {
  105. int status;
  106. if (cafilePath == NULL || certfilePath == NULL || keyfilePath == NULL) {
  107. status = mosquitto_tls_set(
  108. mosqPtrs[clientType],
  109. (const char*)MQ_SERCURE_CA_FILE, //const char *cafile,
  110. NULL, //const char *capath, - note: can be NULL if cafile is defined
  111. (const char*)MQ_SERCURE_CERT_FILE, //const char *certfile,
  112. (const char*)MQ_SERCURE_KEY_FILE, //const char *keyfile,
  113. NULL //int (*pw_callback)(char *buf, int size, int rwflag, void *userdata)
  114. );
  115. } else {
  116. status = mosquitto_tls_set(
  117. mosqPtrs[clientType],
  118. (const char*)cafilePath, //const char *cafile,
  119. NULL, //const char *capath, - note: can be NULL if cafile is defined
  120. (const char*)certfilePath, //const char *certfile,
  121. (const char*)keyfilePath, //const char *keyfile,
  122. NULL //int (*pw_callback)(char *buf, int size, int rwflag, void *userdata)
  123. );
  124. }
  125. if (status != MOSQ_ERR_SUCCESS) {
  126. fprintf(stderr, "ERROR:: TLS Setup failed: %s (%d)\n", mosquitto_strerror(status), status);
  127. return 1;
  128. }
  129. return 0;
  130. }
  131. int _connectMessageQueue(int clientType, char* host, int port, char* clientId, int bTls, char* willTopic, char* willPayload) {
  132. int status = 0;
  133. if (clientId == NULL) {
  134. clientId = generateRandomString(CLIENT_ID_LEN);
  135. }
  136. // instantiate new client (pass clientId as userdata)
  137. mosqPtrs[clientType] = mosquitto_new(clientId, true, clientId);
  138. if(!mosqPtrs[clientType]){
  139. fprintf(stderr, "ERROR: Out of memory - could not instantiate message queue client\n");
  140. return 1;
  141. }
  142. printf("connecting to message queue at %s:%d, clientId is '%s', ptr is %d\n", host, port, clientId, clientType);
  143. if (bTls) {
  144. _setTls(clientType, NULL, NULL, NULL);
  145. }
  146. // set callback functions
  147. mosquitto_connect_callback_set(mosqPtrs[clientType], mqtt_connect_callback);
  148. mosquitto_message_callback_set(mosqPtrs[clientType], mqtt_message_callback);
  149. mosquitto_subscribe_callback_set(mosqPtrs[clientType], mqtt_subscribe_callback);
  150. mosquitto_disconnect_callback_set(mosqPtrs[clientType], mqtt_disconnect_callback);
  151. // set will (if any)
  152. if (willTopic != NULL && willPayload != NULL) {
  153. status = mosquitto_will_set( mosqPtrs[clientType],
  154. willTopic, // topic
  155. strlen(willPayload), // payloadlen
  156. willPayload, // pauload
  157. MQTT_QOS, // qos
  158. false // retain (boolean)
  159. );
  160. if (status != MOSQ_ERR_SUCCESS) {
  161. fprintf(stderr, "ERROR: message queue unable to set will: %s (%d)\n", mosquitto_strerror(status), status);
  162. }
  163. }
  164. // start the connection
  165. printf("Initializing mqtt connection to %s:%d\n", host, port);
  166. status = mosquitto_connect(mosqPtrs[clientType], host, port, MQTT_KEEPALIVE);
  167. if(status != MOSQ_ERR_SUCCESS) {
  168. fprintf(stderr, "ERROR: message queue unable to connect: %s (%d)\n", mosquitto_strerror(status), status);
  169. mosquitto_destroy(mosqPtrs[clientType]);
  170. return 1;
  171. }
  172. // start the loop
  173. status = mosquitto_loop_start(mosqPtrs[clientType]);
  174. if(status != MOSQ_ERR_SUCCESS){
  175. fprintf(stderr, "ERROR: Unable to start message client loop: %s (%d)\n", mosquitto_strerror(status), status);
  176. mosquitto_destroy(mosqPtrs[clientType]);
  177. return 1;
  178. }
  179. return status;
  180. }
  181. int _connectMessageQueueSequence(int clientType, char* host, int port, char* clientId, int bTls, char* willTopic, char* willPayload) {
  182. int count = 0;
  183. int status = 1;
  184. while (count < MQTT_MAX_CONNECT_TRIES) {
  185. if (_connectMessageQueue(clientType, host, port, clientId, bTls, willTopic, willPayload) == 0) {
  186. printf("message queue initialized (%d)\n", count);
  187. status = 0;
  188. break;
  189. }
  190. count++;
  191. sleep(MQTT_CONNECT_WAIT);
  192. }
  193. return status;
  194. }
  195. #endif // ORT_MQTT_ENABLED
  196. // API functions
  197. void initMessageQueue() {
  198. #if ORT_MQTT_ENABLED == 1
  199. mosquitto_lib_init();
  200. for (int i = 0; i < MQ_NUM_CLIENTS; i++) {
  201. mosqPtrs[i] = NULL;
  202. }
  203. #endif // ORT_MQTT_ENABLED
  204. }
  205. void destroyMessageQueue () {
  206. /* mqtt release */
  207. #if ORT_MQTT_ENABLED == 1
  208. for (int i = 0; i < MQ_NUM_CLIENTS; i++) {
  209. if (mosqPtrs[i] != NULL) {
  210. mosquitto_destroy(mosqPtrs[i]);
  211. }
  212. }
  213. mosquitto_lib_cleanup();
  214. #endif // ORT_MQTT_ENABLED
  215. }
  216. int connectMessageQueue(int clientType, char* host, int port, char* clientId, char* willTopic, char* willPayload) {
  217. int status = 0;
  218. #if ORT_MQTT_ENABLED == 1
  219. status = _connectMessageQueueSequence(clientType, host, port, clientId, 0, willTopic, willPayload);
  220. #endif // ORT_MQTT_ENABLED
  221. return status;
  222. }
  223. int connectMessageQueueSecure(int clientType, char* host, int port, char* clientId, char* willTopic, char* willPayload) {
  224. int status = 0;
  225. #if ORT_MQTT_ENABLED == 1
  226. if (host == NULL || strcmp(host,JS_NULL) == 0) {
  227. host = MQ_REMOTE_HOST;
  228. }
  229. status = _connectMessageQueueSequence(clientType, host, port, clientId, 1, willTopic, willPayload);
  230. #endif // ORT_MQTT_ENABLED
  231. return status;
  232. }
  233. int sendMessage (int clientType, char* topic, char* payload) {
  234. int status = 0;
  235. #if ORT_MQTT_ENABLED == 1
  236. struct mosquitto *mosqPtr = mosqPtrs[clientType];
  237. if (mosqPtr != NULL) {
  238. status = mosquitto_publish( mosqPtr,
  239. NULL,
  240. topic,
  241. strlen(payload),
  242. payload,
  243. MQTT_QOS,
  244. false
  245. );
  246. } else {
  247. fprintf(stderr, "Error: invalid pointer (%d) for publish.\n", clientType);
  248. }
  249. #endif // ORT_MQTT_ENABLED
  250. return status;
  251. }
  252. int messageQueueSubscribe (int clientType, char* topic, int* id) {
  253. int status = -1;
  254. #if ORT_MQTT_ENABLED == 1
  255. struct mosquitto *mosqPtr = mosqPtrs[clientType];
  256. if (mosqPtr != NULL) {
  257. printf("Subscribe to topic '%s' ", topic);
  258. status = mosquitto_subscribe( mosqPtr,
  259. id,
  260. topic,
  261. MQTT_QOS
  262. );
  263. if (status == MOSQ_ERR_SUCCESS) {
  264. printf("successful\n");
  265. } else if (status == MOSQ_ERR_NO_CONN) {
  266. printf("not successful, not connected to a broker\n");
  267. }
  268. } else {
  269. fprintf(stderr, "Error: invalid pointer (%d) for subscrube.\n", clientType);
  270. }
  271. #endif // ORT_MQTT_ENABLED
  272. return status;
  273. }