gateway_sample.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  1. /*
  2. * Tencent is pleased to support the open source community by making IoT Hub available.
  3. * Copyright (C) 2016 Tencent. All rights reserved.
  4. * Licensed under the MIT License (the "License"); you may not use this file except in
  5. * compliance with the License. You may obtain a copy of the License at
  6. * http://opensource.org/licenses/MIT
  7. * Unless required by applicable law or agreed to in writing, software distributed under the License is
  8. * distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
  9. * either express or implied. See the License for the specific language governing permissions and
  10. * limitations under the License.
  11. *
  12. */
  13. #include <stdio.h>
  14. #include <stdlib.h>
  15. #include <stdbool.h>
  16. #include <string.h>
  17. #include <limits.h>
  18. #include "utils_getopt.h"
  19. #include "qcloud_iot_export.h"
  20. #include "rtthread.h"
  21. #define GATEWAY_THREAD_STACK_SIZE 6144
  22. #define YEILD_THREAD_STACK_SIZE 4096
  23. #define SUBDEV1_THREAD_STACK_SIZE 6144
  24. static int running_state = 0;
  25. #define MAX_SIZE_OF_TOPIC (128)
  26. #define MAX_SIZE_OF_DATA (128)
  27. #define SUB_DEV_USE_DATA_TEMPLATE_LIGHT
  28. #ifdef SUB_DEV_USE_DATA_TEMPLATE_LIGHT
  29. #define LIGHT_SUB_DEV_PRODUCT_ID "BK7EEF4UIB"
  30. #define LIGHT_SUB_DEV_NAME "dev01"
  31. extern void* sub_dev1_thread(void *user_arg, char *product_id, char *device_name);
  32. #endif
  33. static int sg_sub_packet_id = -1;
  34. static GatewayDeviceInfo sg_GWdevInfo;
  35. #ifdef AUTH_MODE_CERT
  36. static char sg_cert_file[PATH_MAX + 1]; // full path of device cert file
  37. static char sg_key_file[PATH_MAX + 1]; // full path of device key file
  38. #endif
  39. int get_gateway_running_state(void)
  40. {
  41. return running_state;
  42. }
  43. void _event_handler(void *client, void *context, MQTTEventMsg *msg)
  44. {
  45. MQTTMessage* mqtt_messge = (MQTTMessage*)msg->msg;
  46. uintptr_t packet_id = (uintptr_t)msg->msg;
  47. switch (msg->event_type) {
  48. case MQTT_EVENT_UNDEF:
  49. Log_i("undefined event occur.");
  50. break;
  51. case MQTT_EVENT_DISCONNECT:
  52. Log_i("MQTT disconnect.");
  53. break;
  54. case MQTT_EVENT_RECONNECT:
  55. Log_i("MQTT reconnect.");
  56. break;
  57. case MQTT_EVENT_PUBLISH_RECVEIVED:
  58. Log_i("topic message arrived but without any related handle: topic=%.*s, topic_msg=%.*s",
  59. mqtt_messge->topic_len,
  60. mqtt_messge->ptopic,
  61. mqtt_messge->payload_len,
  62. mqtt_messge->payload);
  63. break;
  64. case MQTT_EVENT_SUBCRIBE_SUCCESS:
  65. Log_i("subscribe success, packet-id=%u", (unsigned int)packet_id);
  66. sg_sub_packet_id = packet_id;
  67. break;
  68. case MQTT_EVENT_SUBCRIBE_TIMEOUT:
  69. Log_i("subscribe wait ack timeout, packet-id=%u", (unsigned int)packet_id);
  70. sg_sub_packet_id = packet_id;
  71. break;
  72. case MQTT_EVENT_SUBCRIBE_NACK:
  73. Log_i("subscribe nack, packet-id=%u", (unsigned int)packet_id);
  74. sg_sub_packet_id = packet_id;
  75. break;
  76. case MQTT_EVENT_UNSUBCRIBE_SUCCESS:
  77. Log_i("unsubscribe success, packet-id=%u", (unsigned int)packet_id);
  78. break;
  79. case MQTT_EVENT_UNSUBCRIBE_TIMEOUT:
  80. Log_i("unsubscribe timeout, packet-id=%u", (unsigned int)packet_id);
  81. break;
  82. case MQTT_EVENT_UNSUBCRIBE_NACK:
  83. Log_i("unsubscribe nack, packet-id=%u", (unsigned int)packet_id);
  84. break;
  85. case MQTT_EVENT_PUBLISH_SUCCESS:
  86. Log_i("publish success, packet-id=%u", (unsigned int)packet_id);
  87. break;
  88. case MQTT_EVENT_PUBLISH_TIMEOUT:
  89. Log_i("publish timeout, packet-id=%u", (unsigned int)packet_id);
  90. break;
  91. case MQTT_EVENT_PUBLISH_NACK:
  92. Log_i("publish nack, packet-id=%u", (unsigned int)packet_id);
  93. break;
  94. default:
  95. Log_i("Should NOT arrive here.");
  96. break;
  97. }
  98. }
  99. static void _message_handler(void *client, MQTTMessage *message, void *user_data)
  100. {
  101. if (message == NULL) {
  102. return;
  103. }
  104. Log_i("Receive Message With topicName:%.*s, payload:%.*s",
  105. (int) message->topic_len, message->ptopic, (int) message->payload_len, (char *) message->payload);
  106. }
  107. static int _setup_connect_init_params(GatewayInitParam* init_params)
  108. {
  109. int rc;
  110. rc = HAL_GetGwDevInfo((void *)&sg_GWdevInfo);
  111. if (QCLOUD_RET_SUCCESS != rc) {
  112. Log_e("Get gateway dev info err,rc:%d", rc);
  113. return rc;
  114. }
  115. init_params->init_param.product_id = sg_GWdevInfo.gw_info.product_id;
  116. init_params->init_param.device_name = sg_GWdevInfo.gw_info.device_name;
  117. #ifdef AUTH_MODE_CERT
  118. char certs_dir[PATH_MAX + 1] = "certs";
  119. char current_path[PATH_MAX + 1];
  120. char *cwd = getcwd(current_path, sizeof(current_path));
  121. if (cwd == NULL) {
  122. Log_e("getcwd return NULL");
  123. return QCLOUD_ERR_FAILURE;
  124. }
  125. sprintf(sg_cert_file, "%s/%s/%s", current_path, certs_dir, sg_GWdevInfo.gw_info.dev_cert_file_name);
  126. sprintf(sg_key_file, "%s/%s/%s", current_path, certs_dir, sg_GWdevInfo.gw_info.dev_key_file_name);
  127. init_params->init_param.cert_file = sg_cert_file;
  128. init_params->init_param.key_file = sg_key_file;
  129. #else
  130. init_params->init_param.device_secret = sg_GWdevInfo.gw_info.device_secret;
  131. #endif
  132. init_params->init_param.command_timeout = QCLOUD_IOT_MQTT_COMMAND_TIMEOUT;
  133. init_params->init_param.auto_connect_enable = 1;
  134. init_params->init_param.event_handle.h_fp = _event_handler;
  135. init_params->init_param.keep_alive_interval_ms = QCLOUD_IOT_MQTT_KEEP_ALIVE_INTERNAL;
  136. return QCLOUD_RET_SUCCESS;
  137. }
  138. /**
  139. * sub dev thread runner
  140. */
  141. #ifdef SUB_DEV_USE_DATA_TEMPLATE_LIGHT //show subdev with data template.
  142. static void sub_dev_thread(void *user_arg)
  143. {
  144. sub_dev1_thread(user_arg, LIGHT_SUB_DEV_PRODUCT_ID, LIGHT_SUB_DEV_NAME);
  145. }
  146. #endif
  147. /*Gateway should enable multithread*/
  148. int gateway_thread(void)
  149. {
  150. int rc = QCLOUD_ERR_FAILURE;
  151. int errCount = 0;
  152. int i;
  153. int size;
  154. void* client = NULL;
  155. GatewayDeviceInfo *gw = &sg_GWdevInfo;
  156. GatewayParam param = DEFAULT_GATEWAY_PARAMS;
  157. DeviceInfo *subDevInfo;
  158. #ifdef SUB_DEV_USE_DATA_TEMPLATE_LIGHT
  159. ThreadParams sub_dev1_thread_params = {0};
  160. #endif
  161. IOT_Log_Set_Level(eLOG_DEBUG);
  162. GatewayInitParam init_params = DEFAULT_GATEWAY_INIT_PARAMS;
  163. rc = _setup_connect_init_params(&init_params);
  164. if (rc != QCLOUD_RET_SUCCESS) {
  165. Log_e("init params err,rc=%d", rc);
  166. return rc;
  167. }
  168. client = IOT_Gateway_Construct(&init_params);
  169. if (client == NULL) {
  170. Log_e("client constructed failed.");
  171. return QCLOUD_ERR_FAILURE;
  172. }
  173. #ifdef MULTITHREAD_ENABLED
  174. rc = IOT_Gateway_Start_Yield_Thread(client);
  175. if (rc != QCLOUD_RET_SUCCESS) {
  176. Log_e("init params err,rc=%d", rc);
  177. goto exit;
  178. }
  179. #endif
  180. //set GateWay device info
  181. param.product_id = gw->gw_info.product_id;
  182. param.device_name = gw->gw_info.device_name;
  183. // make sub-device online
  184. for (i = 0; i < gw->sub_dev_num; i++) {
  185. subDevInfo = &gw->sub_dev_info[i];
  186. param.subdev_product_id = subDevInfo->product_id;
  187. param.subdev_device_name = subDevInfo->device_name;
  188. rc = IOT_Gateway_Subdev_Online(client, &param);
  189. if (rc != QCLOUD_RET_SUCCESS) {
  190. Log_e("subDev Pid:%s devName:%s online fail.", subDevInfo->product_id, subDevInfo->device_name);
  191. errCount++;
  192. } else {
  193. Log_d("subDev Pid:%s devName:%s online success.", subDevInfo->product_id, subDevInfo->device_name);
  194. }
  195. }
  196. if (errCount > 0) {
  197. Log_e("%d of %d sub devices online fail", errCount, gw->sub_dev_num);
  198. }
  199. //subscribe sub-device data_template down stream topic for example
  200. char topic_filter[MAX_SIZE_OF_TOPIC + 1];
  201. SubscribeParams sub_param = DEFAULT_SUB_PARAMS;
  202. for (i = 0; i < gw->sub_dev_num; i++) {
  203. subDevInfo = &gw->sub_dev_info[i];
  204. #ifdef SUB_DEV_USE_DATA_TEMPLATE_LIGHT // subdev with data template example.
  205. if ((0 == strcmp(subDevInfo->product_id, LIGHT_SUB_DEV_PRODUCT_ID)) &&
  206. (0 == strcmp(subDevInfo->device_name, LIGHT_SUB_DEV_NAME))) {
  207. sub_dev1_thread_params.thread_func = sub_dev_thread;
  208. sub_dev1_thread_params.thread_name = "sub_dev1_thread";
  209. sub_dev1_thread_params.user_arg = client;
  210. sub_dev1_thread_params.stack_size = 4096;
  211. sub_dev1_thread_params.priority = RT_THREAD_PRIORITY_MAX / 2 - 1;
  212. int rc = HAL_ThreadCreate(&sub_dev1_thread_params);
  213. if (rc) {
  214. Log_e("create sub_dev1_thread fail: %d", rc);
  215. return QCLOUD_ERR_FAILURE;
  216. } else {
  217. Log_e("create sub_dev light thread success");
  218. running_state = 1;
  219. }
  220. continue;
  221. }
  222. #endif
  223. memset(topic_filter, 0, MAX_SIZE_OF_TOPIC + 1);
  224. size = HAL_Snprintf(topic_filter, MAX_SIZE_OF_TOPIC, "$thing/down/property/%s/%s", subDevInfo->product_id, subDevInfo->device_name);
  225. if (size < 0 || size > MAX_SIZE_OF_TOPIC) {
  226. Log_e("buf size < topic length!");
  227. rc = QCLOUD_ERR_FAILURE;
  228. goto exit;
  229. }
  230. sub_param.on_message_handler = _message_handler;
  231. rc = IOT_Gateway_Subscribe(client, topic_filter, &sub_param);
  232. if (rc < 0) {
  233. Log_e("IOT_Gateway_Subscribe fail.");
  234. return rc;
  235. }
  236. }
  237. HAL_SleepMs(2000); /*wait subcribe ack*/
  238. // publish to sub-device data_template up stream topic for example
  239. PublishParams pub_param = DEFAULT_PUB_PARAMS;
  240. pub_param.qos = QOS0;
  241. pub_param.payload = "{\"method\":\"report\",\"clientToken\":\"123\",\"params\":{}}";
  242. pub_param.payload_len = strlen(pub_param.payload);
  243. for (i = 0; i < gw->sub_dev_num; i++) {
  244. subDevInfo = &gw->sub_dev_info[i];
  245. #ifdef SUB_DEV_USE_DATA_TEMPLATE_LIGHT
  246. if ((0 == strcmp(subDevInfo->product_id, LIGHT_SUB_DEV_PRODUCT_ID))
  247. && (0 == strcmp(subDevInfo->device_name, LIGHT_SUB_DEV_NAME))) {
  248. continue;
  249. }
  250. #endif
  251. memset(topic_filter, 0, MAX_SIZE_OF_TOPIC + 1);
  252. size = HAL_Snprintf(topic_filter, MAX_SIZE_OF_TOPIC, "$thing/up/property/%s/%s", subDevInfo->product_id, subDevInfo->device_name);
  253. if (size < 0 || size > MAX_SIZE_OF_TOPIC) {
  254. Log_e("buf size < topic length!");
  255. return QCLOUD_ERR_FAILURE;
  256. }
  257. rc = IOT_Gateway_Publish(client, topic_filter, &pub_param);
  258. if (rc < 0) {
  259. Log_e("IOT_Gateway_Publish fail.");
  260. }
  261. }
  262. exit:
  263. #ifdef SUB_DEV_USE_DATA_TEMPLATE_LIGHT
  264. if(NULL != sub_dev1_thread_params.thread_id) {
  265. while(running_state) {};
  266. }
  267. #endif
  268. running_state = 0;
  269. //set GateWay device info
  270. param.product_id = gw->gw_info.product_id;
  271. param.device_name = gw->gw_info.device_name;
  272. // make sub-device offline
  273. errCount = 0;
  274. for (i = 0; i < gw->sub_dev_num; i++) {
  275. subDevInfo = &gw->sub_dev_info[i];
  276. param.subdev_product_id = subDevInfo->product_id;
  277. param.subdev_device_name = subDevInfo->device_name;
  278. rc = IOT_Gateway_Subdev_Offline(client, &param);
  279. if (rc != QCLOUD_RET_SUCCESS) {
  280. Log_e("subDev Pid:%s devName:%s offline fail.", subDevInfo->product_id, subDevInfo->device_name);
  281. errCount++;
  282. } else {
  283. Log_d("subDev Pid:%s devName:%s offline success.", subDevInfo->product_id, subDevInfo->device_name);
  284. }
  285. }
  286. if (errCount > 0) {
  287. Log_e("%d of %d sub devices offline fail", errCount, gw->sub_dev_num);
  288. }
  289. IOT_Gateway_Stop_Yield_Thread(client);
  290. rc = IOT_Gateway_Destroy(client);
  291. return rc;
  292. }
  293. static int tc_gateway_example(int argc, char **argv)
  294. {
  295. rt_thread_t tid;
  296. int stack_size = GATEWAY_THREAD_STACK_SIZE;
  297. //init log level
  298. IOT_Log_Set_Level(eLOG_DEBUG);
  299. if (2 == argc) {
  300. if (!strcmp("start", argv[1])) {
  301. if (1 == running_state) {
  302. Log_d("tc_gateway_example is already running\n");
  303. return 0;
  304. }
  305. } else if (!strcmp("stop", argv[1])) {
  306. if (0 == running_state) {
  307. Log_d("tc_gateway_example is already stopped\n");
  308. return 0;
  309. }
  310. running_state = 0;
  311. return 0;
  312. } else {
  313. Log_d("Usage: tc_gateway_example start/stop");
  314. return 0;
  315. }
  316. } else {
  317. Log_e("Para err, usage: tc_gateway_example start/stop");
  318. return 0;
  319. }
  320. tid = rt_thread_create("gateway", (void (*)(void *))gateway_thread,
  321. NULL, stack_size, RT_THREAD_PRIORITY_MAX / 2 - 1, 10);
  322. if (tid != RT_NULL) {
  323. rt_thread_startup(tid);
  324. }
  325. return 0;
  326. }
  327. #ifdef RT_USING_FINSH
  328. #include <finsh.h>
  329. FINSH_FUNCTION_EXPORT(tc_gateway_example, startup gateway example);
  330. #endif
  331. #ifdef FINSH_USING_MSH
  332. MSH_CMD_EXPORT(tc_gateway_example, startup gateway example);
  333. #endif