gateway_sample.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  1. /*
  2. * Tencent is pleased to support the open source community by making IoT Hub
  3. available.
  4. * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.
  5. * Licensed under the MIT License (the "License"); you may not use this file
  6. except in
  7. * compliance with the License. You may obtain a copy of the License at
  8. * http://opensource.org/licenses/MIT
  9. * Unless required by applicable law or agreed to in writing, software
  10. distributed under the License is
  11. * distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  12. KIND,
  13. * either express or implied. See the License for the specific language
  14. governing permissions and
  15. * limitations under the License.
  16. *
  17. */
  18. #include <limits.h>
  19. #include <stdbool.h>
  20. #include <stdio.h>
  21. #include <stdlib.h>
  22. #include <string.h>
  23. #include "ql_api_osi.h"
  24. #include "qcloud_iot_export.h"
  25. #include "utils_getopt.h"
  26. #define MAX_SIZE_OF_TOPIC (128)
  27. #define MAX_SIZE_OF_DATA (128)
  28. #define SUB_DEV_USE_DATA_TEMPLATE_LIGHT
  29. #ifdef SUB_DEV_USE_DATA_TEMPLATE_LIGHT
  30. #define LIGHT_SUB_DEV_PRODUCT_ID "BK7EEF4UIB"
  31. #define LIGHT_SUB_DEV_NAME "dev001"
  32. extern void *sub_dev1_thread(void *ptr, char *product_id, char *device_name);
  33. #endif
  34. static int sg_sub_packet_id = -1;
  35. //static int sg_loop_count = 1;
  36. static GatewayDeviceInfo sg_GWdevInfo;
  37. #ifdef AUTH_MODE_CERT
  38. static char sg_cert_file[PATH_MAX + 1]; // full path of device cert file
  39. static char sg_key_file[PATH_MAX + 1]; // full path of device key file
  40. #endif
  41. void _event_handler(void *client, void *context, MQTTEventMsg *msg)
  42. {
  43. MQTTMessage *mqtt_messge = (MQTTMessage *)msg->msg;
  44. uintptr_t packet_id = (uintptr_t)msg->msg;
  45. switch (msg->event_type) {
  46. case MQTT_EVENT_UNDEF:
  47. Log_i("undefined event occur.");
  48. break;
  49. case MQTT_EVENT_DISCONNECT:
  50. Log_i("MQTT disconnect.");
  51. break;
  52. case MQTT_EVENT_RECONNECT:
  53. Log_i("MQTT reconnect.");
  54. break;
  55. case MQTT_EVENT_PUBLISH_RECVEIVED:
  56. Log_i(
  57. "topic message arrived but without any related handle: topic=%.*s, "
  58. "topic_msg=%.*s",
  59. mqtt_messge->topic_len, mqtt_messge->ptopic, mqtt_messge->payload_len, mqtt_messge->payload);
  60. break;
  61. case MQTT_EVENT_SUBCRIBE_SUCCESS:
  62. Log_i("subscribe success, packet-id=%u", (unsigned int)packet_id);
  63. sg_sub_packet_id = packet_id;
  64. break;
  65. case MQTT_EVENT_SUBCRIBE_TIMEOUT:
  66. Log_i("subscribe wait ack timeout, packet-id=%u", (unsigned int)packet_id);
  67. sg_sub_packet_id = packet_id;
  68. break;
  69. case MQTT_EVENT_SUBCRIBE_NACK:
  70. Log_i("subscribe nack, packet-id=%u", (unsigned int)packet_id);
  71. sg_sub_packet_id = packet_id;
  72. break;
  73. case MQTT_EVENT_UNSUBCRIBE_SUCCESS:
  74. Log_i("unsubscribe success, packet-id=%u", (unsigned int)packet_id);
  75. break;
  76. case MQTT_EVENT_UNSUBCRIBE_TIMEOUT:
  77. Log_i("unsubscribe timeout, packet-id=%u", (unsigned int)packet_id);
  78. break;
  79. case MQTT_EVENT_UNSUBCRIBE_NACK:
  80. Log_i("unsubscribe nack, packet-id=%u", (unsigned int)packet_id);
  81. break;
  82. case MQTT_EVENT_PUBLISH_SUCCESS:
  83. Log_i("publish success, packet-id=%u", (unsigned int)packet_id);
  84. break;
  85. case MQTT_EVENT_PUBLISH_TIMEOUT:
  86. Log_i("publish timeout, packet-id=%u", (unsigned int)packet_id);
  87. break;
  88. case MQTT_EVENT_PUBLISH_NACK:
  89. Log_i("publish nack, packet-id=%u", (unsigned int)packet_id);
  90. break;
  91. default:
  92. Log_i("Should NOT arrive here.");
  93. break;
  94. }
  95. }
  96. static void _message_handler(void *client, MQTTMessage *message, void *user_data)
  97. {
  98. if (message == NULL) {
  99. return;
  100. }
  101. Log_i("Receive Message With topicName:%.*s, payload:%.*s", (int)message->topic_len, message->ptopic,
  102. (int)message->payload_len, (char *)message->payload);
  103. }
  104. static int _setup_connect_init_params(GatewayInitParam *init_params)
  105. {
  106. int rc;
  107. rc = HAL_GetGwDevInfo((void *)&sg_GWdevInfo);
  108. if (QCLOUD_RET_SUCCESS != rc) {
  109. Log_e("Get gateway dev info err,rc:%d", rc);
  110. return rc;
  111. }
  112. init_params->init_param.region = sg_GWdevInfo.gw_info.region;
  113. init_params->init_param.product_id = sg_GWdevInfo.gw_info.product_id;
  114. init_params->init_param.device_name = sg_GWdevInfo.gw_info.device_name;
  115. #ifdef AUTH_MODE_CERT
  116. // char certs_dir[PATH_MAX + 1] = "certs";
  117. // char current_path[PATH_MAX + 1];
  118. // char *cwd = getcwd(current_path, sizeof(current_path));
  119. // if (cwd == NULL) {
  120. // Log_e("getcwd return NULL");
  121. // return QCLOUD_ERR_FAILURE;
  122. // }
  123. sprintf(sg_cert_file, "%s", sg_GWdevInfo.gw_info.dev_cert_file_name);
  124. sprintf(sg_key_file, "%s", sg_GWdevInfo.gw_info.dev_key_file_name);
  125. init_params->init_param.cert_file = sg_cert_file;
  126. init_params->init_param.key_file = sg_key_file;
  127. #else
  128. init_params->init_param.device_secret = sg_GWdevInfo.gw_info.device_secret;
  129. #endif
  130. init_params->init_param.command_timeout = QCLOUD_IOT_MQTT_COMMAND_TIMEOUT;
  131. init_params->init_param.auto_connect_enable = 1;
  132. init_params->init_param.event_handle.h_fp = _event_handler;
  133. init_params->init_param.keep_alive_interval_ms = QCLOUD_IOT_MQTT_KEEP_ALIVE_INTERNAL;
  134. return QCLOUD_RET_SUCCESS;
  135. }
  136. //static int parse_arguments(int argc, char **argv)
  137. //{
  138. // int c;
  139. // while ((c = utils_getopt(argc, argv, "c:l:")) != EOF) switch (c) {
  140. // case 'c':
  141. // if (HAL_SetDevInfoFile(utils_optarg))
  142. // return -1;
  143. // break;
  144. //
  145. // case 'l':
  146. // sg_loop_count = atoi(utils_optarg);
  147. // if (sg_loop_count > 10000)
  148. // sg_loop_count = 10000;
  149. // else if (sg_loop_count < 0)
  150. // sg_loop_count = 1;
  151. // break;
  152. //
  153. // default:
  154. // HAL_Printf(
  155. // "usage: %s [options]\n"
  156. // " [-c <config file for DeviceInfo>] \n"
  157. // " [-l <loop count>] \n",
  158. // argv[0]);
  159. // return -1;
  160. // }
  161. // return 0;
  162. //}
  163. /**
  164. * sub dev thread runner
  165. */
  166. #ifdef SUB_DEV_USE_DATA_TEMPLATE_LIGHT // show subdev with data template.
  167. static void sub_dev_thread(void *user_arg)
  168. {
  169. sub_dev1_thread(user_arg, LIGHT_SUB_DEV_PRODUCT_ID, LIGHT_SUB_DEV_NAME);
  170. }
  171. #endif
  172. /**
  173. * show gateway dynamic bind/unbind sub-devices
  174. */
  175. #ifdef GATEWAY_DYN_BIND_SUBDEV_ENABLED
  176. static int add_new_binded_sub_dev(GatewayDeviceInfo *pGateway, DeviceInfo *pNewSubDev)
  177. {
  178. int ret;
  179. if(pGateway->sub_dev_num < MAX_NUM_SUB_DEV) {
  180. memcpy((char *)&pGateway->sub_dev_info[pGateway->sub_dev_num], (char *)pNewSubDev, sizeof(DeviceInfo));
  181. pGateway->sub_dev_num++;
  182. ret = QCLOUD_RET_SUCCESS; //you can save gateway info to local flash for persistent storage
  183. } else {
  184. ret = QCLOUD_ERR_FAILURE;
  185. }
  186. return ret;
  187. }
  188. static int show_subdev_bind_unbind(void *client, GatewayParam *param)
  189. {
  190. int rc;
  191. //ajust for your bind device info
  192. DeviceInfo subDev;
  193. memset((char *)&subDev, 0, sizeof(DeviceInfo));
  194. strncpy(subDev.product_id, "BIND_PID", MAX_SIZE_OF_PRODUCT_ID);
  195. strncpy(subDev.device_name, "BIND_DEV_NAME", MAX_SIZE_OF_DEVICE_NAME);
  196. #ifdef AUTH_MODE_CERT
  197. strncpy(subDev.dev_cert_file_name, "BIND_CERT_FILE_NAME", MAX_SIZE_OF_DEVICE_CERT_FILE_NAME);
  198. strncpy(subDev.dev_key_file_name, "BIND_KEY_FILE_NAME", MAX_SIZE_OF_DEVICE_SECRET_FILE_NAME);
  199. #else
  200. strncpy(subDev.device_secret, "BIND_DEV_PSK", MAX_SIZE_OF_DEVICE_SECRET);
  201. #endif
  202. Log_d("bind subdev %s/%s", subDev.product_id, subDev.device_name);
  203. //bind sub dev
  204. rc = IOT_Gateway_Subdev_Bind(client, param, &subDev);
  205. if(QCLOUD_ERR_BIND_REPEATED_REQ == rc) {
  206. Log_d("%s/%s has been binded", subDev.product_id, subDev.device_name);
  207. rc = IOT_Gateway_Subdev_Unbind(client, param, &subDev);
  208. if(QCLOUD_RET_SUCCESS != rc) {
  209. Log_e("unbind %s/%s fail,rc:%d", subDev.product_id, subDev.device_name, rc);
  210. } else {
  211. Log_d("unbind %s/%s success", subDev.product_id, subDev.device_name);
  212. rc = IOT_Gateway_Subdev_Bind(client, param, &subDev);
  213. }
  214. }
  215. if(QCLOUD_RET_SUCCESS == rc) {
  216. Log_d("bind %s/%s success", subDev.product_id, subDev.device_name);
  217. add_new_binded_sub_dev(&sg_GWdevInfo, &subDev);
  218. } else {
  219. Log_e("bind %s/%s fail,rc:%d", subDev.product_id, subDev.device_name, rc);
  220. }
  221. return rc;
  222. }
  223. #endif
  224. /*Gateway should enable multithread*/
  225. void gateway_sample(void *arg)
  226. {
  227. int rc = QCLOUD_ERR_FAILURE;
  228. int errCount = 0;
  229. int i;
  230. int size;
  231. void * client = NULL;
  232. GatewayDeviceInfo *gw = &sg_GWdevInfo;
  233. GatewayParam param = DEFAULT_GATEWAY_PARAMS;
  234. DeviceInfo * subDevInfo;
  235. #ifdef SUB_DEV_USE_DATA_TEMPLATE_LIGHT
  236. ThreadParams sub_dev1_thread_params = {0};
  237. #endif
  238. IOT_Log_Set_Level(eLOG_DEBUG);
  239. // parse arguments for device info file and loop test;
  240. // rc = parse_arguments(argc, argv);
  241. // if (rc != QCLOUD_RET_SUCCESS) {
  242. // Log_e("parse arguments error, rc = %d", rc);
  243. // return rc;
  244. // }
  245. GatewayInitParam init_params = DEFAULT_GATEWAY_INIT_PARAMS;
  246. rc = _setup_connect_init_params(&init_params);
  247. if (rc != QCLOUD_RET_SUCCESS) {
  248. Log_e("init params err,rc=%d", rc);
  249. return ;
  250. }
  251. client = IOT_Gateway_Construct(&init_params);
  252. if (client == NULL) {
  253. Log_e("client constructed failed.");
  254. return ;
  255. }
  256. #ifdef MULTITHREAD_ENABLED
  257. rc = IOT_Gateway_Start_Yield_Thread(client);
  258. if (rc != QCLOUD_RET_SUCCESS) {
  259. Log_e("init params err,rc=%d", rc);
  260. goto exit;
  261. }
  262. #endif
  263. // set GateWay device info
  264. param.product_id = gw->gw_info.product_id;
  265. param.device_name = gw->gw_info.device_name;
  266. #ifdef GATEWAY_DYN_BIND_SUBDEV_ENABLED
  267. //show gateway dynamic bind/unbind sub-devices
  268. show_subdev_bind_unbind(client, &param);
  269. #endif
  270. // make sub-device online
  271. for (i = 0; i < gw->sub_dev_num; i++) {
  272. subDevInfo = &gw->sub_dev_info[i];
  273. param.subdev_product_id = subDevInfo->product_id;
  274. param.subdev_device_name = subDevInfo->device_name;
  275. rc = IOT_Gateway_Subdev_Online(client, &param);
  276. if (rc != QCLOUD_RET_SUCCESS) {
  277. Log_e("subDev Pid:%s devName:%s online fail.", subDevInfo->product_id, subDevInfo->device_name);
  278. errCount++;
  279. } else {
  280. Log_d("subDev Pid:%s devName:%s online success.", subDevInfo->product_id, subDevInfo->device_name);
  281. }
  282. }
  283. if (errCount > 0) {
  284. Log_e("%d of %d sub devices online fail", errCount, gw->sub_dev_num);
  285. }
  286. // subscribe sub-device data_template down stream topic for example
  287. char topic_filter[MAX_SIZE_OF_TOPIC + 1];
  288. SubscribeParams sub_param = DEFAULT_SUB_PARAMS;
  289. for (i = 0; i < gw->sub_dev_num; i++) {
  290. subDevInfo = &gw->sub_dev_info[i];
  291. #ifdef SUB_DEV_USE_DATA_TEMPLATE_LIGHT // subdev with data template example.
  292. ql_task_t sub_dev1_task = NULL;
  293. if ((0 == strcmp(subDevInfo->product_id, LIGHT_SUB_DEV_PRODUCT_ID)) &&
  294. (0 == strcmp(subDevInfo->device_name, LIGHT_SUB_DEV_NAME))) {
  295. //sub_dev1_thread_params.thread_func = sub_dev_thread;
  296. //sub_dev1_thread_params.thread_name = "sub_dev1_thread";
  297. //sub_dev1_thread_params.user_arg = client;
  298. //sub_dev1_thread_params.stack_size = 4096;
  299. //sub_dev1_thread_params.priority = 1;
  300. int rc = ql_rtos_task_create(&sub_dev1_task, 10*1024, APP_PRIORITY_NORMAL, "sub_dev1_thread", sub_dev_thread, client, 5);
  301. //int rc = HAL_ThreadCreate(&sub_dev1_thread_params);
  302. if (rc) {
  303. Log_e("create sub_dev1_thread fail: %d", rc);
  304. return ;
  305. }
  306. continue;
  307. }
  308. #endif
  309. memset(topic_filter, 0, MAX_SIZE_OF_TOPIC + 1);
  310. size = HAL_Snprintf(topic_filter, MAX_SIZE_OF_TOPIC, "$thing/down/property/%s/%s", subDevInfo->product_id,
  311. subDevInfo->device_name);
  312. if (size < 0 || size > MAX_SIZE_OF_TOPIC) {
  313. Log_e("buf size < topic length!");
  314. rc = QCLOUD_ERR_FAILURE;
  315. goto exit;
  316. }
  317. sub_param.on_message_handler = _message_handler;
  318. rc = IOT_Gateway_Subscribe(client, topic_filter, &sub_param);
  319. if (rc < 0) {
  320. Log_e("IOT_Gateway_Subscribe fail.");
  321. return ;
  322. }
  323. }
  324. HAL_SleepMs(2000); /*wait subcribe ack*/
  325. // publish to sub-device data_template up stream topic for example
  326. PublishParams pub_param = DEFAULT_PUB_PARAMS;
  327. pub_param.qos = QOS0;
  328. // pub_param.payload =
  329. //"{\"method\":\"report\",\"clientToken\":\"123\",\"params\":{\"data\":\"err
  330. // reply wil received\"}}";
  331. pub_param.payload = "{\"method\":\"report\",\"clientToken\":\"123\",\"params\":{}}";
  332. pub_param.payload_len = strlen(pub_param.payload);
  333. for (i = 0; i < gw->sub_dev_num; i++) {
  334. subDevInfo = &gw->sub_dev_info[i];
  335. #ifdef SUB_DEV_USE_DATA_TEMPLATE_LIGHT
  336. if ((0 == strcmp(subDevInfo->product_id, LIGHT_SUB_DEV_PRODUCT_ID)) &&
  337. (0 == strcmp(subDevInfo->device_name, LIGHT_SUB_DEV_NAME))) {
  338. continue;
  339. }
  340. #endif
  341. memset(topic_filter, 0, MAX_SIZE_OF_TOPIC + 1);
  342. size = HAL_Snprintf(topic_filter, MAX_SIZE_OF_TOPIC, "$thing/up/property/%s/%s", subDevInfo->product_id,
  343. subDevInfo->device_name);
  344. if (size < 0 || size > MAX_SIZE_OF_TOPIC) {
  345. Log_e("buf size < topic length!");
  346. return ;
  347. }
  348. rc = IOT_Gateway_Publish(client, topic_filter, &pub_param);
  349. if (rc < 0) {
  350. Log_e("IOT_Gateway_Publish fail.");
  351. }
  352. }
  353. exit:
  354. #ifdef SUB_DEV_USE_DATA_TEMPLATE_LIGHT
  355. if (0 != sub_dev1_thread_params.thread_id) {
  356. //pthread_join(sub_dev1_thread_params.thread_id, NULL);
  357. }
  358. #endif
  359. // set GateWay device info
  360. param.product_id = gw->gw_info.product_id;
  361. param.device_name = gw->gw_info.device_name;
  362. // make sub-device offline
  363. errCount = 0;
  364. for (i = 0; i < gw->sub_dev_num; i++) {
  365. subDevInfo = &gw->sub_dev_info[i];
  366. param.subdev_product_id = subDevInfo->product_id;
  367. param.subdev_device_name = subDevInfo->device_name;
  368. rc = IOT_Gateway_Subdev_Offline(client, &param);
  369. if (rc != QCLOUD_RET_SUCCESS) {
  370. Log_e("subDev Pid:%s devName:%s offline fail.", subDevInfo->product_id, subDevInfo->device_name);
  371. errCount++;
  372. } else {
  373. Log_d("subDev Pid:%s devName:%s offline success.", subDevInfo->product_id, subDevInfo->device_name);
  374. }
  375. }
  376. if (errCount > 0) {
  377. Log_e("%d of %d sub devices offline fail", errCount, gw->sub_dev_num);
  378. }
  379. #ifdef MULTITHREAD_ENABLED
  380. // stop running thread
  381. IOT_Gateway_Stop_Yield_Thread(client);
  382. rc = IOT_Gateway_Destroy(client);
  383. #endif
  384. }
  385. int gateway_sample_start(void)
  386. {
  387. int err = 0;
  388. int count = 0;
  389. ql_task_t gateway_sample_task = NULL;
  390. /* 主循环进入休眠 */
  391. while (count < 10)
  392. {
  393. count++;
  394. ql_rtos_task_sleep_s(1);
  395. Log_e("ql_qcloud_sdk_gateway_sample_start_init -0x%04X\n", err);
  396. }
  397. err = ql_rtos_task_create(&gateway_sample_task, 10*1024, APP_PRIORITY_NORMAL, "gateway_sample", gateway_sample, NULL, 5);
  398. if (err != QL_OSI_SUCCESS)
  399. {
  400. return -1;
  401. }
  402. return 0;
  403. }