mqtt-example.c 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678
  1. /*
  2. * Copyright (c) 2006-2018 RT-Thread Development Team. All rights reserved.
  3. * License-Identifier: Apache-2.0
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License"); you may
  6. * not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  13. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. *
  17. */
  18. #include <stdio.h>
  19. #include <stdlib.h>
  20. #include <string.h>
  21. #include <stdarg.h>
  22. #include "iot_import.h"
  23. #include "iot_export.h"
  24. #include "rtthread.h"
  25. #if defined(MQTT_ID2_AUTH) && defined(ON_DAILY)
  26. #define PRODUCT_KEY "9rx2yMNV5l0"
  27. #define DEVICE_NAME "sh_online_sample_mqtt"
  28. #define DEVICE_SECRET "v9mqGzepKEphLhXmAoiaUIR2HZ7XwTky"
  29. #elif defined(ON_DAILY)
  30. #define PRODUCT_KEY "gsYfsxQJgeD"
  31. #define DEVICE_NAME "DailyEnvDN"
  32. #define DEVICE_SECRET "y1vzFkEgcuXnvkAfm627pwarx4HRNikX"
  33. #elif defined(MQTT_ID2_AUTH)
  34. #define PRODUCT_KEY "micKUvuzOps"
  35. #define DEVICE_NAME "00AAAAAABBBBBB4B645F5800"
  36. #define DEVICE_SECRET "v9mqGzepKEphLhXmAoiaUIR2HZ7XwTky"
  37. #else
  38. #ifdef PKG_USING_ALI_IOTKIT_PRODUCT_KEY
  39. #define PRODUCT_KEY PKG_USING_ALI_IOTKIT_PRODUCT_KEY
  40. #else
  41. #define PRODUCT_KEY "yfTuLfBJTiL"
  42. #endif
  43. #ifdef PKG_USING_ALI_IOTKIT_DEVICE_NAME
  44. #define DEVICE_NAME PKG_USING_ALI_IOTKIT_DEVICE_NAME
  45. #else
  46. #define DEVICE_NAME "TestDeviceForDemo"
  47. #endif
  48. #ifdef PKG_USING_ALI_IOTKIT_DEVICE_SECRET
  49. #define DEVICE_SECRET PKG_USING_ALI_IOTKIT_DEVICE_SECRET
  50. #else
  51. #define DEVICE_SECRET "fSCl9Ns5YPnYN8Ocg0VEel1kXFnRlV6c"
  52. #endif
  53. #endif
  54. #ifdef PKG_USING_ALI_IOTKIT_IS_LINKDEVELOP
  55. /* ALINK TSL Device attribute report */
  56. #define ALINK_PROPERTY_POST_PUB "/sys/"PRODUCT_KEY"/"DEVICE_NAME"/thing/event/property/post"
  57. #define ALINK_PROPERTY_POST_REPLY_SUB "/sys/"PRODUCT_KEY"/"DEVICE_NAME"/thing/event/property/post_reply"
  58. #define ALINK_PROPERTY_SET_REPLY_SUB "/sys/"PRODUCT_KEY"/"DEVICE_NAME"/thing/event/property/set_reply"
  59. #define ALINK_SERVICE_SET_SUB "/sys/"PRODUCT_KEY"/"DEVICE_NAME"/thing/service/property/set"
  60. #else
  61. #define TOPIC_UPDATE "/"PRODUCT_KEY"/"DEVICE_NAME"/update"
  62. #define TOPIC_ERROR "/"PRODUCT_KEY"/"DEVICE_NAME"/update/error"
  63. #define TOPIC_GET "/"PRODUCT_KEY"/"DEVICE_NAME"/get"
  64. #define TOPIC_DATA "/"PRODUCT_KEY"/"DEVICE_NAME"/data"
  65. #endif
  66. /* These are pre-defined topics format*/
  67. #define TOPIC_UPDATE_FMT "/%s/%s/update"
  68. #define TOPIC_ERROR_FMT "/%s/%s/update/error"
  69. #define TOPIC_GET_FMT "/%s/%s/get"
  70. #define TOPIC_DATA_FMT "/%s/%s/data"
  71. #define MQTT_MSGLEN (1024)
  72. #define EXAMPLE_TRACE(fmt, ...) \
  73. do { \
  74. HAL_Printf("%s|%03d :: ", __func__, __LINE__); \
  75. HAL_Printf(fmt, ##__VA_ARGS__); \
  76. HAL_Printf("%s", "\r\n"); \
  77. } while(0)
  78. static char __product_key[PRODUCT_KEY_LEN + 1];
  79. static char __device_name[DEVICE_NAME_LEN + 1];
  80. static char __device_secret[DEVICE_SECRET_LEN + 1];
  81. static int user_argc;
  82. static char *user_param = NULL;
  83. static void *pclient;
  84. static uint8_t is_running = 0;
  85. static char* rt_strlwr(char *str)
  86. {
  87. if(str == NULL)
  88. return NULL;
  89. char *p = str;
  90. while (*p != '\0')
  91. {
  92. if(*p >= 'A' && *p <= 'Z')
  93. *p = (*p) + 0x20;
  94. p++;
  95. }
  96. return str;
  97. }
  98. static void event_handle(void *pcontext, void *pclient, iotx_mqtt_event_msg_pt msg)
  99. {
  100. iotx_mqtt_topic_info_pt topic_info = (iotx_mqtt_topic_info_pt)msg->msg;
  101. if (topic_info == NULL)
  102. {
  103. rt_kprintf("Topic info is null! Exit.");
  104. return;
  105. }
  106. uintptr_t packet_id = (uintptr_t)topic_info->packet_id;
  107. switch (msg->event_type) {
  108. case IOTX_MQTT_EVENT_UNDEF:
  109. EXAMPLE_TRACE("undefined event occur.");
  110. break;
  111. case IOTX_MQTT_EVENT_DISCONNECT:
  112. EXAMPLE_TRACE("MQTT disconnect.");
  113. break;
  114. case IOTX_MQTT_EVENT_RECONNECT:
  115. EXAMPLE_TRACE("MQTT reconnect.");
  116. break;
  117. case IOTX_MQTT_EVENT_SUBCRIBE_SUCCESS:
  118. EXAMPLE_TRACE("subscribe success, packet-id=%u", (unsigned int)packet_id);
  119. break;
  120. case IOTX_MQTT_EVENT_SUBCRIBE_TIMEOUT:
  121. EXAMPLE_TRACE("subscribe wait ack timeout, packet-id=%u", (unsigned int)packet_id);
  122. break;
  123. case IOTX_MQTT_EVENT_SUBCRIBE_NACK:
  124. EXAMPLE_TRACE("subscribe nack, packet-id=%u", (unsigned int)packet_id);
  125. break;
  126. case IOTX_MQTT_EVENT_UNSUBCRIBE_SUCCESS:
  127. EXAMPLE_TRACE("unsubscribe success, packet-id=%u", (unsigned int)packet_id);
  128. break;
  129. case IOTX_MQTT_EVENT_UNSUBCRIBE_TIMEOUT:
  130. EXAMPLE_TRACE("unsubscribe timeout, packet-id=%u", (unsigned int)packet_id);
  131. break;
  132. case IOTX_MQTT_EVENT_UNSUBCRIBE_NACK:
  133. EXAMPLE_TRACE("unsubscribe nack, packet-id=%u", (unsigned int)packet_id);
  134. break;
  135. case IOTX_MQTT_EVENT_PUBLISH_SUCCESS:
  136. EXAMPLE_TRACE("publish success, packet-id=%u", (unsigned int)packet_id);
  137. break;
  138. case IOTX_MQTT_EVENT_PUBLISH_TIMEOUT:
  139. EXAMPLE_TRACE("publish timeout, packet-id=%u", (unsigned int)packet_id);
  140. break;
  141. case IOTX_MQTT_EVENT_PUBLISH_NACK:
  142. EXAMPLE_TRACE("publish nack, packet-id=%u", (unsigned int)packet_id);
  143. break;
  144. case IOTX_MQTT_EVENT_PUBLISH_RECVEIVED:
  145. EXAMPLE_TRACE("topic message arrived but without any related handle: topic=%.*s, topic_msg=%.*s",
  146. topic_info->topic_len,
  147. topic_info->ptopic,
  148. topic_info->payload_len,
  149. topic_info->payload);
  150. break;
  151. case IOTX_MQTT_EVENT_BUFFER_OVERFLOW:
  152. EXAMPLE_TRACE("buffer overflow, %s", msg->msg);
  153. break;
  154. default:
  155. EXAMPLE_TRACE("Should NOT arrive here.");
  156. break;
  157. }
  158. }
  159. static void _demo_message_arrive(void *pcontext, void *pclient, iotx_mqtt_event_msg_pt msg)
  160. {
  161. iotx_mqtt_topic_info_pt ptopic_info = (iotx_mqtt_topic_info_pt) msg->msg;
  162. /* print topic name and topic message */
  163. EXAMPLE_TRACE("----");
  164. EXAMPLE_TRACE("packetId: %d", ptopic_info->packet_id);
  165. EXAMPLE_TRACE("Topic: '%.*s' (Length: %d)",
  166. ptopic_info->topic_len,
  167. ptopic_info->ptopic,
  168. ptopic_info->topic_len);
  169. EXAMPLE_TRACE("Payload: '%.*s' (Length: %d)",
  170. ptopic_info->payload_len,
  171. ptopic_info->payload,
  172. ptopic_info->payload_len);
  173. EXAMPLE_TRACE("----");
  174. }
  175. #ifndef MQTT_ID2_AUTH
  176. static void mqtt_client(void)
  177. {
  178. int rc = 0;
  179. iotx_conn_info_pt pconn_info;
  180. iotx_mqtt_param_t mqtt_params;
  181. char *msg_buf = NULL, *msg_readbuf = NULL;
  182. IOT_OpenLog("mqtt");
  183. IOT_SetLogLevel(IOT_LOG_DEBUG);
  184. if (NULL == (msg_buf = (char *)HAL_Malloc(MQTT_MSGLEN))) {
  185. EXAMPLE_TRACE("not enough memory");
  186. rc = -1;
  187. goto do_exit;
  188. }
  189. if (NULL == (msg_readbuf = (char *)HAL_Malloc(MQTT_MSGLEN))) {
  190. EXAMPLE_TRACE("not enough memory");
  191. rc = -1;
  192. goto do_exit;
  193. }
  194. HAL_GetProductKey(__product_key);
  195. HAL_GetDeviceName(__device_name);
  196. HAL_GetDeviceSecret(__device_secret);
  197. /* Device AUTH */
  198. if (0 != IOT_SetupConnInfo(__product_key, __device_name, __device_secret, (void **)&pconn_info)) {
  199. EXAMPLE_TRACE("AUTH request failed!");
  200. rc = -1;
  201. goto do_exit;
  202. }
  203. /* Initialize MQTT parameter */
  204. memset(&mqtt_params, 0x0, sizeof(mqtt_params));
  205. mqtt_params.port = pconn_info->port;
  206. mqtt_params.host = pconn_info->host_name;
  207. mqtt_params.client_id = pconn_info->client_id;
  208. mqtt_params.username = pconn_info->username;
  209. mqtt_params.password = pconn_info->password;
  210. mqtt_params.pub_key = pconn_info->pub_key;
  211. mqtt_params.request_timeout_ms = 2000;
  212. mqtt_params.clean_session = 0;
  213. mqtt_params.keepalive_interval_ms = 60000;
  214. mqtt_params.pread_buf = msg_readbuf;
  215. mqtt_params.read_buf_size = MQTT_MSGLEN;
  216. mqtt_params.pwrite_buf = msg_buf;
  217. mqtt_params.write_buf_size = MQTT_MSGLEN;
  218. mqtt_params.handle_event.h_fp = event_handle;
  219. mqtt_params.handle_event.pcontext = NULL;
  220. /* Convert uppercase letters in host to lowercase */
  221. rt_kprintf("host: %s\r\n", rt_strlwr((char*)mqtt_params.host));
  222. /* Construct a MQTT client with specify parameter */
  223. pclient = IOT_MQTT_Construct(&mqtt_params);
  224. if (NULL == pclient) {
  225. EXAMPLE_TRACE("MQTT construct failed");
  226. rc = -1;
  227. goto do_exit;
  228. }
  229. #ifdef PKG_USING_ALI_IOTKIT_IS_LINKDEVELOP
  230. /* Subscribe the specific topic */
  231. rc = IOT_MQTT_Subscribe(pclient, ALINK_SERVICE_SET_SUB, IOTX_MQTT_QOS1, _demo_message_arrive, NULL);
  232. #else
  233. rc = IOT_MQTT_Subscribe(pclient, TOPIC_DATA, IOTX_MQTT_QOS1, _demo_message_arrive, NULL);
  234. #endif
  235. if (rc < 0) {
  236. IOT_MQTT_Destroy(&pclient);
  237. EXAMPLE_TRACE("IOT_MQTT_Subscribe() failed, rc = %d", rc);
  238. rc = -1;
  239. goto do_exit;
  240. }
  241. #ifdef PKG_USING_ALI_IOTKIT_IS_LINKDEVELOP
  242. /* Subscribe the specific topic */
  243. rc = IOT_MQTT_Subscribe(pclient, ALINK_PROPERTY_POST_REPLY_SUB, IOTX_MQTT_QOS1, _demo_message_arrive, NULL);
  244. if (rc < 0) {
  245. IOT_MQTT_Destroy(&pclient);
  246. EXAMPLE_TRACE("IOT_MQTT_Subscribe() failed, rc = %d", rc);
  247. rc = -1;
  248. goto do_exit;
  249. }
  250. #endif
  251. IOT_MQTT_Yield(pclient, 200);
  252. do {
  253. /* handle the MQTT packet received from TCP or SSL connection */
  254. IOT_MQTT_Yield(pclient, 200);
  255. HAL_SleepMs(2000);
  256. } while (is_running);
  257. IOT_MQTT_Yield(pclient, 200);
  258. #ifdef PKG_USING_ALI_IOTKIT_IS_LINKDEVELOP
  259. IOT_MQTT_Unsubscribe(pclient, ALINK_PROPERTY_POST_REPLY_SUB);
  260. IOT_MQTT_Unsubscribe(pclient, ALINK_SERVICE_SET_SUB);
  261. #else
  262. IOT_MQTT_Unsubscribe(pclient, TOPIC_DATA);
  263. #endif
  264. IOT_MQTT_Yield(pclient, 200);
  265. IOT_MQTT_Destroy(&pclient);
  266. do_exit:
  267. if (NULL != msg_buf) {
  268. HAL_Free(msg_buf);
  269. }
  270. if (NULL != msg_readbuf) {
  271. HAL_Free(msg_readbuf);
  272. }
  273. if (NULL != user_param)
  274. HAL_Free(user_param);
  275. user_param = NULL;
  276. IOT_DumpMemoryStats(IOT_LOG_DEBUG);
  277. IOT_CloseLog();
  278. is_running = 0;
  279. EXAMPLE_TRACE("out of sample!");
  280. }
  281. #endif /* MQTT_ID2_AUTH */
  282. #ifdef MQTT_ID2_AUTH
  283. #include "tfs.h"
  284. static char __device_id2[TFS_ID2_LEN + 1];
  285. static void mqtt_client_secure()
  286. {
  287. int rc = 0, msg_len, cnt = 0;
  288. void *pclient;
  289. iotx_conn_info_pt pconn_info;
  290. iotx_mqtt_param_t mqtt_params;
  291. iotx_mqtt_topic_info_t topic_msg;
  292. char msg_pub[128];
  293. char *msg_buf = NULL, *msg_readbuf = NULL;
  294. char topic_update[IOTX_URI_MAX_LEN] = {0};
  295. char topic_error[IOTX_URI_MAX_LEN] = {0};
  296. char topic_get[IOTX_URI_MAX_LEN] = {0};
  297. char topic_data[IOTX_URI_MAX_LEN] = {0};
  298. IOT_OpenLog("mqtt");
  299. IOT_SetLogLevel(IOT_LOG_DEBUG);
  300. if (NULL == (msg_buf = (char *)HAL_Malloc(MQTT_MSGLEN))) {
  301. EXAMPLE_TRACE("not enough memory");
  302. rc = -1;
  303. goto do_exit;
  304. }
  305. if (NULL == (msg_readbuf = (char *)HAL_Malloc(MQTT_MSGLEN))) {
  306. EXAMPLE_TRACE("not enough memory");
  307. rc = -1;
  308. goto do_exit;
  309. }
  310. HAL_GetProductKey(__product_key);
  311. HAL_GetID2(__device_id2);
  312. /* Device AUTH */
  313. rc = IOT_SetupConnInfoSecure(__product_key, __device_id2, __device_id2, (void **)&pconn_info);
  314. if (rc != 0) {
  315. EXAMPLE_TRACE("AUTH request failed!");
  316. goto do_exit;
  317. }
  318. HAL_Snprintf(topic_update,IOTX_URI_MAX_LEN,TOPIC_UPDATE_FMT,__product_key,__device_id2);
  319. HAL_Snprintf(topic_error,IOTX_URI_MAX_LEN,TOPIC_ERROR_FMT,__product_key,__device_id2);
  320. HAL_Snprintf(topic_get,IOTX_URI_MAX_LEN,TOPIC_GET_FMT,__product_key,__device_id2);
  321. HAL_Snprintf(topic_data,IOTX_URI_MAX_LEN,TOPIC_DATA_FMT,__product_key,__device_id2);
  322. /* Initialize MQTT parameter */
  323. memset(&mqtt_params, 0x0, sizeof(mqtt_params));
  324. mqtt_params.port = pconn_info->port;
  325. mqtt_params.host = pconn_info->host_name;
  326. mqtt_params.client_id = pconn_info->client_id;
  327. mqtt_params.username = pconn_info->username;
  328. mqtt_params.password = pconn_info->password;
  329. mqtt_params.pub_key = pconn_info->pub_key;
  330. mqtt_params.request_timeout_ms = 2000;
  331. mqtt_params.clean_session = 0;
  332. mqtt_params.keepalive_interval_ms = 60000;
  333. mqtt_params.pread_buf = msg_readbuf;
  334. mqtt_params.read_buf_size = MQTT_MSGLEN;
  335. mqtt_params.pwrite_buf = msg_buf;
  336. mqtt_params.write_buf_size = MQTT_MSGLEN;
  337. mqtt_params.handle_event.h_fp = event_handle;
  338. mqtt_params.handle_event.pcontext = NULL;
  339. /* Construct a MQTT client with specify parameter */
  340. pclient = IOT_MQTT_ConstructSecure(&mqtt_params);
  341. if (NULL == pclient) {
  342. EXAMPLE_TRACE("MQTT construct failed");
  343. rc = -1;
  344. goto do_exit;
  345. }
  346. /* Subscribe the specific topic */
  347. rc = IOT_MQTT_Subscribe(pclient, topic_data, IOTX_MQTT_QOS1, _demo_message_arrive, NULL);
  348. if (rc < 0) {
  349. IOT_MQTT_Destroy(&pclient);
  350. EXAMPLE_TRACE("IOT_MQTT_Subscribe() failed, rc = %d", rc);
  351. rc = -1;
  352. goto do_exit;
  353. }
  354. HAL_SleepMs(1000);
  355. /* Initialize topic information */
  356. memset(&topic_msg, 0x0, sizeof(iotx_mqtt_topic_info_t));
  357. strcpy(msg_pub, "message: hello! start!");
  358. topic_msg.qos = IOTX_MQTT_QOS1;
  359. topic_msg.retain = 0;
  360. topic_msg.dup = 0;
  361. topic_msg.payload = (void *)msg_pub;
  362. topic_msg.payload_len = strlen(msg_pub);
  363. rc = IOT_MQTT_Publish(pclient, topic_data, &topic_msg);
  364. EXAMPLE_TRACE("rc = IOT_MQTT_Publish() = %d", rc);
  365. do {
  366. /* Generate topic message */
  367. cnt++;
  368. msg_len = snprintf(msg_pub, sizeof(msg_pub), "{\"attr_name\":\"temperature\", \"attr_value\":\"%d\"}", cnt);
  369. if (msg_len < 0) {
  370. EXAMPLE_TRACE("Error occur! Exit program");
  371. rc = -1;
  372. break;
  373. }
  374. topic_msg.payload = (void *)msg_pub;
  375. topic_msg.payload_len = msg_len;
  376. rc = IOT_MQTT_Publish(pclient, topic_data, &topic_msg);
  377. if (rc < 0) {
  378. EXAMPLE_TRACE("error occur when publish");
  379. rc = -1;
  380. break;
  381. }
  382. EXAMPLE_TRACE("packet-id=%u, publish topic msg='0x%02x%02x%02x%02x'...",
  383. (uint32_t)rc,
  384. msg_pub[0], msg_pub[1], msg_pub[2], msg_pub[3]
  385. );
  386. /* handle the MQTT packet received from TCP or SSL connection */
  387. IOT_MQTT_Yield(pclient, 200);
  388. /* infinite loop if running with 'loop' argument */
  389. if (user_argc >= 2 && user_param && !strcmp("loop", user_param)) {
  390. HAL_SleepMs(2000);
  391. cnt = 0;
  392. }
  393. } while (cnt < 1);
  394. IOT_MQTT_Unsubscribe(pclient, TOPIC_DATA);
  395. HAL_SleepMs(200);
  396. IOT_MQTT_Destroy(&pclient);
  397. do_exit:
  398. if (NULL != msg_buf) {
  399. HAL_Free(msg_buf);
  400. }
  401. if (NULL != msg_readbuf) {
  402. HAL_Free(msg_readbuf);
  403. }
  404. if (NULL != user_param)
  405. HAL_Free(user_param);
  406. user_param = NULL;
  407. IOT_DumpMemoryStats(IOT_LOG_DEBUG);
  408. IOT_CloseLog();
  409. EXAMPLE_TRACE("out of sample!");
  410. }
  411. #endif /* MQTT_ID2_AUTH*/
  412. static int ali_mqtt_test_pub(void)
  413. {
  414. int rc = 0;
  415. static uint16_t pub_msg_cnt = 0;
  416. uint8_t rgb_switch = 0, rand_num_r = 0, rand_num_g = 0, rand_num_b = 0;
  417. char msg_pub[512];
  418. iotx_mqtt_topic_info_t topic_msg;
  419. if (!is_running)
  420. {
  421. HAL_Printf("MQTT test is not running! Please start MQTT first by using the \"ali_mqtt_test start\" command");
  422. return 0;
  423. }
  424. if (user_param && !strcmp("open", user_param))
  425. {
  426. rgb_switch = 1;
  427. }
  428. else if (user_param && !strcmp("close", user_param))
  429. {
  430. rgb_switch = 0;
  431. }
  432. else
  433. {
  434. return 0;
  435. }
  436. srand((int)(rt_tick_get()) / (pub_msg_cnt + 1));
  437. rand_num_r = (uint8_t)(rand()%255);
  438. srand((int)(rt_tick_get()) / (pub_msg_cnt + 2));
  439. rand_num_g = (uint8_t)(rand()%255);
  440. srand((int)(rt_tick_get()) / (pub_msg_cnt + 3));
  441. rand_num_b = (uint8_t)(rand()%255);
  442. /* Initialize topic information */
  443. memset(msg_pub, 0x0, sizeof(msg_pub));
  444. snprintf(msg_pub, sizeof(msg_pub),
  445. "{\"id\" : \"%d\",\"version\":\"1.0\",\"params\" : "
  446. "{\"RGBColor\" : {\"Red\":%d,\"Green\":%d,\"Blue\":%d},"
  447. "\"LightSwitch\" : %d},"
  448. "\"method\":\"thing.event.property.post\"}",
  449. ++pub_msg_cnt, rand_num_r, rand_num_g, rand_num_b, rgb_switch);
  450. memset(&topic_msg, 0x0, sizeof(iotx_mqtt_topic_info_t));
  451. topic_msg.qos = IOTX_MQTT_QOS1;
  452. topic_msg.retain = 0;
  453. topic_msg.dup = 0;
  454. topic_msg.payload = (void *)msg_pub;
  455. topic_msg.payload_len = strlen(msg_pub);
  456. #ifdef PKG_USING_ALI_IOTKIT_IS_LINKDEVELOP
  457. rc = IOT_MQTT_Publish(pclient, ALINK_PROPERTY_POST_PUB, &topic_msg);
  458. if (rc < 0) {
  459. IOT_MQTT_Destroy(&pclient);
  460. EXAMPLE_TRACE("error occur when publish");
  461. rc = -1;
  462. return rc;
  463. }
  464. EXAMPLE_TRACE("\n publish message: \n topic: %s\n payload: %s\n rc = %d", ALINK_PROPERTY_POST_PUB, topic_msg.payload, rc);
  465. #else
  466. rc = IOT_MQTT_Publish(pclient, TOPIC_UPDATE, &topic_msg);
  467. if (rc < 0) {
  468. IOT_MQTT_Destroy(&pclient);
  469. EXAMPLE_TRACE("error occur when publish");
  470. rc = -1;
  471. return rc;
  472. }
  473. EXAMPLE_TRACE("\n publish message: \n topic: %s\n payload: \%s\n rc = %d", TOPIC_UPDATE, topic_msg.payload, rc);
  474. rc = IOT_MQTT_Publish(pclient, TOPIC_DATA, &topic_msg);
  475. if (rc < 0) {
  476. IOT_MQTT_Destroy(&pclient);
  477. EXAMPLE_TRACE("error occur when publish");
  478. rc = -1;
  479. return rc;
  480. }
  481. EXAMPLE_TRACE("\n publish message: \n topic: %s\n payload: \%s\n rc = %d", TOPIC_DATA, topic_msg.payload, rc);
  482. #endif
  483. return 0;
  484. }
  485. static int ali_mqtt_main(int argc, char **argv)
  486. {
  487. rt_thread_t tid;
  488. user_argc = argc;
  489. if (2 == user_argc)
  490. {
  491. if (!strcmp("start", argv[1]))
  492. {
  493. if (1 == is_running)
  494. {
  495. HAL_Printf("MQTT test is already running! Please stop running first by using the \"ali_mqtt_test stop\" command\n");
  496. return 0;
  497. }
  498. is_running = 1;
  499. }
  500. else if (!strcmp("stop", argv[1]))
  501. {
  502. if (0 == is_running)
  503. {
  504. HAL_Printf("MQTT test is already stopped!\n");
  505. return 0;
  506. }
  507. is_running = 0;
  508. // stop mqtt test
  509. return 0;
  510. }
  511. else
  512. {
  513. HAL_Printf("Input param error! Example: ali_mqtt_test start/stop or ali_mqtt_test pub open/close\n");
  514. return 0;
  515. }
  516. }
  517. else if(3 == user_argc)
  518. {
  519. if (!strcmp("pub", argv[1]))
  520. {
  521. user_param = (char*)rt_strdup((const char*)argv[2]);
  522. HAL_Printf("param:%s\n", user_param);
  523. // publish
  524. ali_mqtt_test_pub();
  525. return 0;
  526. }
  527. else
  528. {
  529. HAL_Printf("Input param error! Example: ali_mqtt_test start/stop or ali_mqtt_test pub open/close\n");
  530. return 0;
  531. }
  532. }
  533. else
  534. {
  535. HAL_Printf("Input param error! Example: ali_mqtt_test start/stop or ali_mqtt_test pub open/close\n");
  536. return 0;
  537. }
  538. #ifdef IOTX_PRJ_VERSION
  539. HAL_Printf("iotkit-embedded sdk version: %s\n", IOTX_PRJ_VERSION);
  540. #endif
  541. HAL_SetProductKey(PRODUCT_KEY);
  542. HAL_SetDeviceName(DEVICE_NAME);
  543. HAL_SetDeviceSecret(DEVICE_SECRET);
  544. #ifndef MQTT_ID2_AUTH
  545. tid = rt_thread_create("ali-mqtt",
  546. (void (*)(void *))mqtt_client, NULL,
  547. 6 * 1024, RT_THREAD_PRIORITY_MAX / 2 - 1, 10);
  548. #else
  549. tid = rt_thread_create("ali-mqtt",
  550. mqtt_client_secure, NULL,
  551. 6 * 1024, RT_THREAD_PRIORITY_MAX / 2 - 1, 10);
  552. #endif
  553. if (tid != RT_NULL)
  554. rt_thread_startup(tid);
  555. return 0;
  556. }
  557. #ifdef RT_USING_FINSH
  558. #include <finsh.h>
  559. MSH_CMD_EXPORT_ALIAS(ali_mqtt_main, ali_mqtt_test, Example: ali_mqtt_test start/pub [open/close]/stop);
  560. #endif