at_socket_sim76xx.c 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225
  1. /*
  2. * File : at_socket_sim76xx.c
  3. * This file is part of RT-Thread RTOS
  4. * COPYRIGHT (C) 2006 - 2018, RT-Thread Development Team
  5. *
  6. * This program is free software; you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation; either version 2 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License along
  17. * with this program; if not, write to the Free Software Foundation, Inc.,
  18. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  19. *
  20. * Change Logs:
  21. * Date Author Notes
  22. * 2018-12-22 thomasonegd first version
  23. * 2019-03-06 thomasonegd fix udp connection.
  24. * 2019-03-08 thomasonegd add power_on & power_off api
  25. */
  26. #include <stdio.h>
  27. #include <string.h>
  28. #include <rtthread.h>
  29. #include <sys/socket.h>
  30. #include <at.h>
  31. #include <at_socket.h>
  32. #if !defined(RT_USING_NETDEV)
  33. #error "This RT-Thread version is older, please check and updata laster RT-Thread!"
  34. #else
  35. #include <arpa/inet.h>
  36. #include <netdev.h>
  37. #endif /* RT_USING_NETDEV */
  38. #if !defined(AT_SW_VERSION_NUM) || AT_SW_VERSION_NUM < 0x10200
  39. #error "This AT Client version is older, please check and update latest AT Client!"
  40. #endif
  41. #define LOG_TAG "at.sim76xx"
  42. #include <at_log.h>
  43. #ifdef AT_DEVICE_SIM76XX
  44. #define SIM76XX_NETDEV_NAME "sim76xx"
  45. #define SIM76XX_MODULE_SEND_MAX_SIZE 1500
  46. #define SIM76XX_WAIT_CONNECT_TIME 5000
  47. #define SIM76XX_THREAD_STACK_SIZE 1024
  48. #define SIM76XX_THREAD_PRIORITY (RT_THREAD_PRIORITY_MAX/2)
  49. #define SIM76XX_MAX_CONNECTIONS 10
  50. /* set real event by current socket and current state */
  51. #define SET_EVENT(socket, event) (((socket + 1) << 16) | (event))
  52. /* AT socket event type */
  53. #define SIM76XX_EVENT_CONN_OK (1L << 0)
  54. #define SIM76XX_EVENT_SEND_OK (1L << 1)
  55. #define SIM76XX_EVENT_RECV_OK (1L << 2)
  56. #define SIM76XX_EVNET_CLOSE_OK (1L << 3)
  57. #define SIM76XX_EVENT_CONN_FAIL (1L << 4)
  58. #define SIM76XX_EVENT_SEND_FAIL (1L << 5)
  59. uint8_t at_socket_init = 0;
  60. static int cur_socket;
  61. static int cur_send_bfsz;
  62. static rt_event_t at_socket_event;
  63. static rt_mutex_t at_event_lock;
  64. static at_evt_cb_t at_evt_cb_set[] = {
  65. [AT_SOCKET_EVT_RECV] = NULL,
  66. [AT_SOCKET_EVT_CLOSED] = NULL,
  67. };
  68. static char udp_ipstr[SIM76XX_MAX_CONNECTIONS][16];
  69. static int udp_port[SIM76XX_MAX_CONNECTIONS];
  70. static void at_tcp_ip_errcode_parse(int result)//Unsolicited TCP/IP command<err> codes
  71. {
  72. switch(result)
  73. {
  74. case 0 : LOG_D("%d : operation succeeded ", result); break;
  75. case 1 : LOG_E("%d : UNetwork failure", result); break;
  76. case 2 : LOG_E("%d : Network not opened", result); break;
  77. case 3 : LOG_E("%d : Wrong parameter", result); break;
  78. case 4 : LOG_E("%d : Operation not supported", result); break;
  79. case 5 : LOG_E("%d : Failed to create socket", result); break;
  80. case 6 : LOG_E("%d : Failed to bind socket", result); break;
  81. case 7 : LOG_E("%d : TCP server is already listening", result); break;
  82. case 8 : LOG_E("%d : Busy", result); break;
  83. case 9 : LOG_E("%d : Sockets opened", result); break;
  84. case 10 : LOG_E("%d : Timeout ", result); break;
  85. case 11 : LOG_E("%d : DNS parse failed for AT+CIPOPEN", result); break;
  86. case 255 : LOG_E("%d : Unknown error", result); break;
  87. }
  88. }
  89. static int at_socket_event_send(uint32_t event)
  90. {
  91. return (int) rt_event_send(at_socket_event, event);
  92. }
  93. static int at_socket_event_recv(uint32_t event, uint32_t timeout, rt_uint8_t option)
  94. {
  95. int result = 0;
  96. rt_uint32_t recved;
  97. result = rt_event_recv(at_socket_event, event, option | RT_EVENT_FLAG_CLEAR, timeout, &recved);
  98. if (result != RT_EOK)
  99. {
  100. return -RT_ETIMEOUT;
  101. }
  102. return recved;
  103. }
  104. /**
  105. * close socket by AT commands.
  106. *
  107. * @param current socket
  108. *
  109. * @return 0: close socket success
  110. * -1: send AT commands error
  111. * -2: wait socket event timeout
  112. * -5: no memory
  113. */
  114. static int sim76xx_socket_close(int socket)
  115. {
  116. at_response_t resp = RT_NULL;
  117. int result = RT_EOK;
  118. int activated;
  119. uint8_t lnk_stat[10];
  120. resp = at_create_resp(128, 0, rt_tick_from_millisecond(500));
  121. if (!resp)
  122. {
  123. LOG_E("No memory for response structure!");
  124. return -RT_ENOMEM;
  125. }
  126. rt_mutex_take(at_event_lock, RT_WAITING_FOREVER);
  127. rt_thread_delay(rt_tick_from_millisecond(100));
  128. // check socket link_state
  129. if (at_exec_cmd(resp,"AT+CIPCLOSE?") < 0)
  130. {
  131. result = -RT_ERROR;
  132. goto __exit;
  133. }
  134. if(at_resp_parse_line_args_by_kw(resp,"+CIPCLOSE:", "+CIPCLOSE: %d,%d,%d,%d,%d,%d,%d,%d,%d,%d",&lnk_stat[0],&lnk_stat[1],&lnk_stat[1]
  135. ,&lnk_stat[2],&lnk_stat[3],&lnk_stat[4],&lnk_stat[5],&lnk_stat[6],&lnk_stat[7],&lnk_stat[8],&lnk_stat[9]) < 0)
  136. {
  137. result = -RT_ERROR;
  138. goto __exit;
  139. }
  140. if (lnk_stat[socket])
  141. {
  142. // close tcp or udp socket if connected
  143. if (at_exec_cmd(resp, "AT+CIPCLOSE=%d", socket) < 0)
  144. {
  145. result = -RT_ERROR;
  146. goto __exit;
  147. }
  148. }
  149. // check the network open or not
  150. if (at_exec_cmd(resp,"AT+NETOPEN?") < 0)
  151. {
  152. result = -RT_ERROR;
  153. goto __exit;
  154. }
  155. if(at_resp_parse_line_args_by_kw(resp, "+NETOPEN:", "+NETOPEN: %d", &activated) < 0)
  156. {
  157. result = -RT_ERROR;
  158. goto __exit;
  159. }
  160. if (activated)
  161. {
  162. // if already open,then close it.
  163. if (at_exec_cmd(resp,"AT+NETCLOSE") < 0)
  164. {
  165. result = -RT_ERROR;
  166. goto __exit;
  167. }
  168. }
  169. __exit:
  170. rt_mutex_release(at_event_lock);
  171. if (resp)
  172. {
  173. at_delete_resp(resp);
  174. }
  175. return result;
  176. }
  177. /**
  178. * open packet network
  179. */
  180. static int sim76xx_network_socket_open(void)
  181. {
  182. int result = RT_EOK;
  183. at_response_t resp = RT_NULL;
  184. int activated;
  185. resp = at_create_resp(128, 0, rt_tick_from_millisecond(5000));
  186. if (!resp)
  187. {
  188. LOG_E("No memory for response structure!");
  189. return -RT_ENOMEM;
  190. }
  191. rt_mutex_take(at_event_lock, RT_WAITING_FOREVER);
  192. // check the network open or not
  193. if (at_exec_cmd(resp,"AT+NETOPEN?") < 0)
  194. {
  195. result = -RT_ERROR;
  196. goto __exit;
  197. }
  198. if(at_resp_parse_line_args_by_kw(resp, "+NETOPEN:", "+NETOPEN: %d", &activated) < 0)
  199. {
  200. result = -RT_ERROR;
  201. goto __exit;
  202. }
  203. if (activated)
  204. {//network socket is already opened
  205. goto __exit;
  206. }else
  207. {
  208. // if not opened the open it.
  209. if (at_exec_cmd(resp,"AT+NETOPEN") < 0)
  210. {
  211. result = -RT_ERROR;
  212. goto __exit;
  213. }
  214. }
  215. __exit:
  216. rt_mutex_release(at_event_lock);
  217. if (resp)
  218. {
  219. at_delete_resp(resp);
  220. }
  221. return result;
  222. }
  223. /**
  224. * create TCP/UDP client or server connect by AT commands.
  225. *
  226. * @param socket current socket
  227. * @param ip server or client IP address
  228. * @param port server or client port
  229. * @param type connect socket type(tcp, udp)
  230. * @param is_client connection is client
  231. *
  232. * @return 0: connect success
  233. * -1: connect failed, send commands error or type error
  234. * -2: wait socket event timeout
  235. * -5: no memory
  236. */
  237. static int sim76xx_socket_connect(int socket, char *ip, int32_t port, enum at_socket_type type, rt_bool_t is_client)
  238. {
  239. at_response_t resp = RT_NULL;
  240. int result = RT_EOK,event_result = 0;
  241. rt_bool_t retryed = RT_FALSE;
  242. RT_ASSERT(ip);
  243. RT_ASSERT(port >= 0);
  244. resp = at_create_resp(128, 0, rt_tick_from_millisecond(5000));
  245. if (!resp)
  246. {
  247. LOG_E("No memory for response structure!");
  248. return -RT_ENOMEM;
  249. }
  250. rt_mutex_take(at_event_lock, RT_WAITING_FOREVER);
  251. __retry:
  252. if (is_client)
  253. {
  254. //open network socket first(AT+NETOPEN)
  255. sim76xx_network_socket_open();
  256. switch (type)
  257. {
  258. case AT_SOCKET_TCP:
  259. /* send AT commands to connect TCP server */
  260. if (at_exec_cmd(resp, "AT+CIPOPEN=%d,\"TCP\",\"%s\",%d", socket, ip, port) < 0)
  261. {
  262. result = -RT_ERROR;
  263. }
  264. break;
  265. case AT_SOCKET_UDP:
  266. if (at_exec_cmd(resp, "AT+CIPOPEN=%d,\"UDP\",,,%d", socket, port) < 0)
  267. {
  268. result = -RT_ERROR;
  269. }
  270. strcpy(udp_ipstr[socket],ip);
  271. udp_port[socket] = port;
  272. break;
  273. default:
  274. LOG_E("Not supported connect type : %d.", type);
  275. result = -RT_ERROR;
  276. goto __exit;
  277. }
  278. }
  279. /* waiting result event from AT URC, the device default connection timeout is 75 seconds, but it set to 10 seconds is convenient to use.*/
  280. if (at_socket_event_recv(SET_EVENT(socket, 0), rt_tick_from_millisecond(10 * 1000), RT_EVENT_FLAG_OR) < 0)
  281. {
  282. LOG_E("socket (%d) connect failed, wait connect result timeout.", socket);
  283. result = -RT_ETIMEOUT;
  284. goto __exit;
  285. }
  286. /* waiting OK or failed result */
  287. if ((event_result = at_socket_event_recv(SIM76XX_EVENT_CONN_OK | SIM76XX_EVENT_CONN_FAIL, rt_tick_from_millisecond(1 * 1000),
  288. RT_EVENT_FLAG_OR)) < 0)
  289. {
  290. LOG_E("socket (%d) connect failed, wait connect OK|FAIL timeout.", socket);
  291. result = -RT_ETIMEOUT;
  292. goto __exit;
  293. }
  294. /* check result */
  295. if (event_result & SIM76XX_EVENT_CONN_FAIL)
  296. {
  297. if (!retryed)
  298. {
  299. LOG_E("socket (%d) connect failed, maybe the socket was not be closed at the last time and now will retry.", socket);
  300. if (sim76xx_socket_close(socket) < 0)
  301. {
  302. goto __exit;
  303. }
  304. retryed = RT_TRUE;
  305. goto __retry;
  306. }
  307. LOG_E("socket (%d) connect failed, failed to establish a connection.", socket);
  308. result = -RT_ERROR;
  309. goto __exit;
  310. }
  311. if (result != RT_EOK && !retryed)
  312. {
  313. LOG_D("socket (%d) connect failed, maybe the socket was not be closed at the last time and now will retry.", socket);
  314. if (sim76xx_socket_close(socket) < 0)
  315. {
  316. goto __exit;
  317. }
  318. retryed = RT_TRUE;
  319. result = RT_EOK;
  320. goto __retry;
  321. }
  322. __exit:
  323. rt_mutex_release(at_event_lock);
  324. if (resp)
  325. {
  326. at_delete_resp(resp);
  327. }
  328. return result;
  329. }
  330. /**
  331. * send data to server or client by AT commands.
  332. *
  333. * @param socket current socket
  334. * @param buff send buffer
  335. * @param bfsz send buffer size
  336. * @param type connect socket type(tcp, udp)
  337. *
  338. * @return >=0: the size of send success
  339. * -1: send AT commands error or send data error
  340. * -2: waited socket event timeout
  341. * -5: no memory
  342. */
  343. static int sim76xx_socket_send(int socket, const char *buff, size_t bfsz, enum at_socket_type type)
  344. {
  345. int result = RT_EOK;
  346. int event_result = 0;
  347. at_response_t resp = RT_NULL;
  348. size_t cur_pkt_size = 0, sent_size = 0;
  349. RT_ASSERT(buff);
  350. RT_ASSERT(bfsz > 0);
  351. resp = at_create_resp(128, 2, rt_tick_from_millisecond(5000));
  352. if (!resp)
  353. {
  354. LOG_E("No memory for response structure!");
  355. return -RT_ENOMEM;
  356. }
  357. rt_mutex_take(at_event_lock, RT_WAITING_FOREVER);
  358. /* set current socket for send URC event */
  359. cur_socket = socket;
  360. /* set AT client end sign to deal with '>' sign.*/
  361. at_set_end_sign('>');
  362. while (sent_size < bfsz)
  363. {
  364. if (bfsz - sent_size < SIM76XX_MODULE_SEND_MAX_SIZE)
  365. {
  366. cur_pkt_size = bfsz - sent_size;
  367. }
  368. else
  369. {
  370. cur_pkt_size = SIM76XX_MODULE_SEND_MAX_SIZE;
  371. }
  372. switch(type)
  373. {
  374. case AT_SOCKET_TCP:
  375. /* send the "AT+CIPSEND" commands to AT server than receive the '>' response on the first line. */
  376. if (at_exec_cmd(resp, "AT+CIPSEND=%d,%d", socket, cur_pkt_size) < 0)
  377. {
  378. result = -RT_ERROR;
  379. goto __exit;
  380. }
  381. break;
  382. case AT_SOCKET_UDP:
  383. /* send the "AT+CIPSEND" commands to AT server than receive the '>' response on the first line. */
  384. if (at_exec_cmd(resp, "AT+CIPSEND=%d,%d,\"%s\",%d", socket, cur_pkt_size,udp_ipstr[socket],udp_port[socket]) < 0)
  385. {
  386. result = -RT_ERROR;
  387. goto __exit;
  388. }
  389. break;
  390. }
  391. /* send the real data to server or client */
  392. result = (int) at_client_send(buff + sent_size, cur_pkt_size);
  393. if (result == 0)
  394. {
  395. result = -RT_ERROR;
  396. goto __exit;
  397. }
  398. /* waiting result event from AT URC */
  399. if (at_socket_event_recv(SET_EVENT(socket, 0), rt_tick_from_millisecond(5 * 1000), RT_EVENT_FLAG_OR) < 0)
  400. {
  401. LOG_E("socket (%d) send failed, wait connect result timeout.", socket);
  402. result = -RT_ETIMEOUT;
  403. goto __exit;
  404. }
  405. /* waiting OK or failed result */
  406. if ((event_result = at_socket_event_recv(SIM76XX_EVENT_SEND_OK | SIM76XX_EVENT_SEND_FAIL, rt_tick_from_millisecond(5 * 1000),
  407. RT_EVENT_FLAG_OR)) < 0)
  408. {
  409. LOG_E("socket (%d) send failed, wait connect OK|FAIL timeout.", socket);
  410. result = -RT_ETIMEOUT;
  411. goto __exit;
  412. }
  413. /* check result */
  414. if (event_result & SIM76XX_EVENT_SEND_FAIL)
  415. {
  416. LOG_E("socket (%d) send failed, return failed.", socket);
  417. result = -RT_ERROR;
  418. goto __exit;
  419. }
  420. if (type == AT_SOCKET_TCP)
  421. {
  422. cur_pkt_size = cur_send_bfsz;
  423. }
  424. sent_size += cur_pkt_size;
  425. }
  426. __exit:
  427. /* reset the end sign for data */
  428. at_set_end_sign(0);
  429. rt_mutex_release(at_event_lock);
  430. if (resp)
  431. {
  432. at_delete_resp(resp);
  433. }
  434. return result;
  435. }
  436. /**
  437. * domain resolve by AT commands.
  438. *
  439. * @param name domain name
  440. * @param ip parsed IP address, it's length must be 16
  441. *
  442. * @return 0: domain resolve success
  443. * -2: wait socket event timeout
  444. * -5: no memory
  445. */
  446. static int sim76xx_domain_resolve(const char *name, char ip[16])
  447. {
  448. #define RESOLVE_RETRY 5
  449. int i, result = RT_EOK;
  450. char domain[32] = { 0 };
  451. char domain_ip[16] = {0};
  452. at_response_t resp = RT_NULL;
  453. RT_ASSERT(name);
  454. RT_ASSERT(ip);
  455. resp = at_create_resp(128, 0, rt_tick_from_millisecond(5000));
  456. if (!resp)
  457. {
  458. LOG_E("No memory for response structure!");
  459. return -RT_ENOMEM;
  460. }
  461. rt_mutex_take(at_event_lock, RT_WAITING_FOREVER);
  462. for(i = 0; i < RESOLVE_RETRY; i++)
  463. {
  464. if (at_exec_cmd(resp, "AT+CDNSGIP=\"%s\"", name) < 0)
  465. {
  466. rt_thread_delay(rt_tick_from_millisecond(200));
  467. /* resolve failed, maybe receive an URC CRLF */
  468. continue;
  469. }
  470. /* parse the third line of response data, get the IP address */
  471. /* +CDNSGIP: 1,"www.baidu.com","14.215.177.39" */
  472. if(at_resp_parse_line_args_by_kw(resp, "+CDNSGIP:", "+CDNSGIP: 1,%[^,],\"%[^\"]", domain,domain_ip) < 0)
  473. {
  474. rt_thread_delay(rt_tick_from_millisecond(200));
  475. /* resolve failed, maybe receive an URC CRLF */
  476. continue;
  477. }
  478. if (strlen(domain_ip) < 8)
  479. {
  480. rt_thread_delay(rt_tick_from_millisecond(200));
  481. /* resolve failed, maybe receive an URC CRLF */
  482. continue;
  483. }
  484. else
  485. {
  486. strncpy(ip, domain_ip, 15);
  487. ip[15] = '\0';
  488. break;
  489. }
  490. }
  491. rt_mutex_release(at_event_lock);
  492. if (i == RESOLVE_RETRY)
  493. {
  494. result = -RT_ERROR;
  495. }
  496. if (resp)
  497. {
  498. at_delete_resp(resp);
  499. }
  500. return result;
  501. }
  502. /**
  503. * set AT socket event notice callback
  504. *
  505. * @param event notice event
  506. * @param cb notice callback
  507. */
  508. static void sim76xx_socket_set_event_cb(at_socket_evt_t event, at_evt_cb_t cb)
  509. {
  510. if (event < (sizeof(at_evt_cb_set) / sizeof(at_evt_cb_set[1])))
  511. {
  512. at_evt_cb_set[event] = cb;
  513. }
  514. }
  515. static void urc_send_func(const char *data, rt_size_t size)
  516. {
  517. int socket = 0;
  518. int rqst_size;
  519. int cnf_size;
  520. RT_ASSERT(data && size);
  521. sscanf(data,"+CIPSEND: %d,%d,%d",&socket,&rqst_size,&cnf_size);
  522. cur_send_bfsz = cnf_size;
  523. at_socket_event_send(SET_EVENT(socket, SIM76XX_EVENT_SEND_OK));
  524. }
  525. static void urc_ping_func(const char *data, rt_size_t size)
  526. {
  527. static int icmp_seq = 0;
  528. int i, j = 0;
  529. int result, recv_len, time, ttl;
  530. int sent, rcvd, lost, min, max, avg;
  531. char dst_ip[16] = { 0 };
  532. RT_ASSERT(data);
  533. for (i=0;i<size;i++)
  534. {
  535. if(*(data+i) == '.')
  536. j++;
  537. }
  538. if (j != 0)
  539. {
  540. sscanf(data, "+CPING: %d,%[^,],%d,%d,%d", &result, dst_ip, &recv_len, &time, &ttl);
  541. if (result == 1)
  542. LOG_I("%d bytes from %s icmp_seq=%d ttl=%d time=%d ms", recv_len, dst_ip, icmp_seq++, ttl, time);
  543. }
  544. else
  545. {
  546. sscanf(data, "+CPING: %d,%d,%d,%d,%d,%d,%d", &result, &sent, &rcvd, &lost, &min, &max, &avg);
  547. if (result == 3)
  548. LOG_I("%d sent %d received %d lost, min=%dms max=%dms average=%dms", sent, rcvd, lost, min, max, avg);
  549. if (result == 2)
  550. LOG_I("ping requst timeout");
  551. }
  552. }
  553. static void urc_connect_func(const char *data, rt_size_t size)
  554. {
  555. int socket = 0;
  556. int result = 0;
  557. RT_ASSERT(data && size);
  558. sscanf(data, "+CIPOPEN: %d,%d", &socket , &result);
  559. if (result == 0)
  560. {
  561. at_socket_event_send(SET_EVENT(socket, SIM76XX_EVENT_CONN_OK));
  562. }
  563. else
  564. {
  565. at_tcp_ip_errcode_parse(result);
  566. at_socket_event_send(SET_EVENT(socket, SIM76XX_EVENT_CONN_FAIL));
  567. }
  568. }
  569. static void urc_close_func(const char *data, rt_size_t size)
  570. {
  571. int socket = 0;
  572. int reason = 0;
  573. RT_ASSERT(data && size);
  574. sscanf(data, "+IPCLOSE %d,%d", &socket, &reason);
  575. switch(reason)
  576. {
  577. case 0:
  578. LOG_E("socket is closed by local,active");
  579. break;
  580. case 1:
  581. LOG_E("socket is closed by remote,passive");
  582. break;
  583. case 2:
  584. LOG_E("socket is closed for sending timeout");
  585. break;
  586. }
  587. /* notice the socket is disconnect by remote */
  588. if (at_evt_cb_set[AT_SOCKET_EVT_CLOSED])
  589. {
  590. at_evt_cb_set[AT_SOCKET_EVT_CLOSED](socket, AT_SOCKET_EVT_CLOSED, RT_NULL, 0);
  591. }
  592. }
  593. static void urc_recv_func(const char *data, rt_size_t size)
  594. {
  595. rt_size_t bfsz = 0, temp_size = 0;
  596. rt_int32_t timeout;
  597. char *recv_buf = RT_NULL, temp[8];
  598. RT_ASSERT(data && size);
  599. /* get the current socket and receive buffer size by receive data */
  600. sscanf(data, "+IPD%d:",(int *) &bfsz);
  601. /* get receive timeout by receive buffer length */
  602. timeout = bfsz * 10;
  603. if (bfsz == 0)
  604. return;
  605. recv_buf = rt_calloc(1, bfsz);
  606. if (!recv_buf)
  607. {
  608. LOG_E("no memory for URC receive buffer (%d)!", bfsz);
  609. /* read and clean the coming data */
  610. while (temp_size < bfsz)
  611. {
  612. if (bfsz - temp_size > sizeof(temp))
  613. {
  614. at_client_recv(temp, sizeof(temp), timeout);
  615. }
  616. else
  617. {
  618. at_client_recv(temp, bfsz - temp_size, timeout);
  619. }
  620. temp_size += sizeof(temp);
  621. }
  622. return;
  623. }
  624. /* sync receive data */
  625. if (at_client_recv(recv_buf, bfsz, timeout) != bfsz)
  626. {
  627. LOG_E("receive size(%d) data failed!", bfsz);
  628. rt_free(recv_buf);
  629. return;
  630. }
  631. /* notice the receive buffer and buffer size */
  632. if (at_evt_cb_set[AT_SOCKET_EVT_RECV])
  633. {
  634. at_evt_cb_set[AT_SOCKET_EVT_RECV](cur_socket, AT_SOCKET_EVT_RECV, recv_buf, bfsz);
  635. }
  636. }
  637. static struct at_urc urc_table[] = {
  638. {"+CIPSEND:", "\r\n", urc_send_func},
  639. {"+CIPOPEN:", "\r\n", urc_connect_func},
  640. {"+CPING:", "\r\n", urc_ping_func},
  641. {"+IPCLOSE", "\r\n", urc_close_func},
  642. {"+IPD", "\r\n", urc_recv_func},
  643. };
  644. #define AT_SEND_CMD(resp, cmd) \
  645. do \
  646. { \
  647. if (at_exec_cmd(at_resp_set_info(resp, 256, 0, rt_tick_from_millisecond(5000)), cmd) < 0) \
  648. { \
  649. LOG_E("RT AT send commands(%s) error!", cmd); \
  650. result = -RT_ERROR; \
  651. goto __exit; \
  652. } \
  653. } while(0); \
  654. /**
  655. * power up sim76xx modem
  656. */
  657. static void sim76xx_power_on(void)
  658. {
  659. rt_pin_write(AT_DEVICE_POWER_PIN, PIN_HIGH);
  660. rt_thread_delay(rt_tick_from_millisecond(300));
  661. rt_pin_write(AT_DEVICE_POWER_PIN, PIN_LOW);
  662. while (rt_pin_read(AT_DEVICE_STATUS_PIN) == PIN_LOW)
  663. {
  664. rt_thread_delay(rt_tick_from_millisecond(10));
  665. }
  666. }
  667. static void sim76xx_power_off(void)
  668. {
  669. rt_pin_write(AT_DEVICE_POWER_PIN, PIN_HIGH);
  670. rt_thread_delay(rt_tick_from_millisecond(3000));
  671. rt_pin_write(AT_DEVICE_POWER_PIN, PIN_LOW);
  672. while (rt_pin_read(AT_DEVICE_STATUS_PIN) == PIN_HIGH)
  673. {
  674. rt_thread_delay(rt_tick_from_millisecond(10));
  675. }
  676. rt_pin_write(AT_DEVICE_POWER_PIN, PIN_LOW);
  677. }
  678. static void sim76xx_init_thread_entry(void *parameter)
  679. {
  680. #define CSQ_RETRY 20
  681. #define CREG_RETRY 10
  682. #define CGREG_RETRY 20
  683. #define CGATT_RETRY 10
  684. #define CCLK_RETRY 10
  685. at_response_t resp = RT_NULL;
  686. rt_err_t result = RT_EOK;
  687. rt_size_t i, qi_arg[3];
  688. char parsed_data[20];
  689. resp = at_create_resp(128, 0, rt_tick_from_millisecond(300));
  690. if (!resp)
  691. {
  692. LOG_E("No memory for response structure!");
  693. result = -RT_ENOMEM;
  694. goto __exit;
  695. }
  696. /* power-up sim76xx */
  697. sim76xx_power_on();
  698. LOG_D("Start initializing the SIM76XXE module");
  699. /* wait SIM76XX startup finish, Send AT every 5s, if receive OK, SYNC success*/
  700. if (at_client_wait_connect(SIM76XX_WAIT_CONNECT_TIME))
  701. {
  702. result = -RT_ETIMEOUT;
  703. goto __exit;
  704. }
  705. /* disable echo */
  706. AT_SEND_CMD(resp, "ATE0");
  707. /* get module version */
  708. AT_SEND_CMD(resp, "ATI");
  709. /* show module version */
  710. for (i = 0; i < (int) resp->line_counts - 1; i++)
  711. {
  712. LOG_D("%s", at_resp_get_line(resp, i + 1));
  713. }
  714. /* check SIM card */
  715. AT_SEND_CMD(resp, "AT+CPIN?");
  716. if (!at_resp_get_line_by_kw(resp, "READY"))
  717. {
  718. LOG_E("SIM card detection failed");
  719. result = -RT_ERROR;
  720. goto __exit;
  721. }
  722. /* waiting for dirty data to be digested */
  723. rt_thread_delay(rt_tick_from_millisecond(10));
  724. /* check signal strength */
  725. for (i = 0; i < CSQ_RETRY; i++)
  726. {
  727. AT_SEND_CMD(resp, "AT+CSQ");
  728. at_resp_parse_line_args_by_kw(resp, "+CSQ:", "+CSQ: %d,%d", &qi_arg[0], &qi_arg[1]);
  729. if (qi_arg[0] != 99)
  730. {
  731. LOG_D("Signal strength: %d Channel bit error rate: %d", qi_arg[0], qi_arg[1]);
  732. break;
  733. }
  734. rt_thread_delay(rt_tick_from_millisecond(1000));
  735. }
  736. if (i == CSQ_RETRY)
  737. {
  738. LOG_E("Signal strength check failed (%s)", parsed_data);
  739. result = -RT_ERROR;
  740. goto __exit;
  741. }
  742. //do not show the prompt when receiving data
  743. AT_SEND_CMD(resp, "AT+CIPSRIP=0");
  744. /* check the GSM network is registered */
  745. for (i = 0; i < CREG_RETRY; i++)
  746. {
  747. AT_SEND_CMD(resp,"AT+CREG?");
  748. at_resp_parse_line_args_by_kw(resp, "+CREG:", "+CREG: %s", &parsed_data);
  749. if (!strncmp(parsed_data, "0,1", sizeof(parsed_data)) || !strncmp(parsed_data, "0,5", sizeof(parsed_data)))
  750. {
  751. LOG_D("GSM network is registered (%s)", parsed_data);
  752. break;
  753. }
  754. rt_thread_delay(rt_tick_from_millisecond(1000));
  755. }
  756. if (i == CREG_RETRY)
  757. {
  758. LOG_E("The GSM network is register failed (%s)", parsed_data);
  759. result = -RT_ERROR;
  760. goto __exit;
  761. }
  762. /* check the GPRS network is registered */
  763. for (i = 0; i < CGREG_RETRY; i++)
  764. {
  765. AT_SEND_CMD(resp,"AT+CGREG?");
  766. at_resp_parse_line_args_by_kw(resp, "+CGREG:", "+CGREG: %s", &parsed_data);
  767. if (!strncmp(parsed_data, "0,1", sizeof(parsed_data)) || !strncmp(parsed_data, "0,5", sizeof(parsed_data)))
  768. {
  769. LOG_D("GPRS network is registered (%s)", parsed_data);
  770. break;
  771. }
  772. rt_thread_delay(rt_tick_from_millisecond(1000));
  773. }
  774. if (i == CGREG_RETRY)
  775. {
  776. LOG_E("The GPRS network is register failed (%s)", parsed_data);
  777. result = -RT_ERROR;
  778. goto __exit;
  779. }
  780. /* check packet domain attach or detach */
  781. for (i = 0;i < CGATT_RETRY; i++)
  782. {
  783. AT_SEND_CMD(resp,"AT+CGATT?")
  784. at_resp_parse_line_args_by_kw(resp,"+CGATT:","+CGATT: %s",&parsed_data);
  785. if (!strncmp(parsed_data,"1",1))
  786. {
  787. LOG_I("Packet domain attach");
  788. break;
  789. }
  790. rt_thread_delay(rt_tick_from_millisecond(1000));
  791. }
  792. if (i == CGATT_RETRY)
  793. {
  794. LOG_E("The GPRS network attach failed");
  795. result = -RT_ERROR;
  796. goto __exit;
  797. }
  798. /* get real time */
  799. int year,month,day,hour,min,sec;
  800. for (i = 0;i < CCLK_RETRY;i++)
  801. {
  802. if (at_exec_cmd(at_resp_set_info(resp, 256, 0, rt_tick_from_millisecond(5000)), "AT+CCLK?") < 0)
  803. {
  804. rt_thread_delay(rt_tick_from_millisecond(500));
  805. continue;
  806. }
  807. //+CCLK: "18/12/22,18:33:12+32"
  808. if (at_resp_parse_line_args_by_kw(resp,"+CCLK:","+CCLK: \"%d/%d/%d,%d:%d:%d",&year,&month,&day,&hour,&min,&sec) < 0)
  809. {
  810. rt_thread_delay(rt_tick_from_millisecond(500));
  811. continue;
  812. }
  813. set_date(year + 2000,month,day);
  814. set_time(hour,min,sec);
  815. break;
  816. }
  817. if (i == CCLK_RETRY)
  818. {
  819. LOG_E("The GPRS network attach failed");
  820. result = -RT_ERROR;
  821. goto __exit;
  822. }
  823. /* set active PDP context's profile number */
  824. AT_SEND_CMD(resp, "AT+CSOCKSETPN=1");
  825. __exit:
  826. if (resp)
  827. {
  828. at_delete_resp(resp);
  829. }
  830. if (!result)
  831. {
  832. LOG_I("AT network initialize success!");
  833. at_socket_init = 1;
  834. }
  835. else
  836. {
  837. LOG_E("AT network initialize failed (%d)!", result);
  838. }
  839. }
  840. int sim76xx_net_init(void)
  841. {
  842. #ifdef PKG_AT_INIT_BY_THREAD
  843. rt_thread_t tid;
  844. tid = rt_thread_create("sim76xx_net_init", sim76xx_init_thread_entry, RT_NULL,SIM76XX_THREAD_STACK_SIZE, SIM76XX_THREAD_PRIORITY, 20);
  845. if (tid)
  846. {
  847. rt_thread_startup(tid);
  848. }
  849. else
  850. {
  851. LOG_E("Create AT initialization thread fail!");
  852. }
  853. #else
  854. sim76xx_init_thread_entry(RT_NULL);
  855. #endif
  856. return RT_EOK;
  857. }
  858. int sim76xx_ping(int argc, char **argv)
  859. {
  860. at_response_t resp = RT_NULL;
  861. if (argc != 2)
  862. {
  863. rt_kprintf("Please input: at_ping <host address>\n");
  864. return -RT_ERROR;
  865. }
  866. resp = at_create_resp(64, 0, rt_tick_from_millisecond(5000));
  867. if (!resp)
  868. {
  869. rt_kprintf("No memory for response structure!\n");
  870. return -RT_ENOMEM;
  871. }
  872. if (at_exec_cmd(resp, "AT+CPING=\"%s\",1,4,64,1000,10000,255", argv[1]) < 0)
  873. {
  874. if (resp)
  875. {
  876. at_delete_resp(resp);
  877. }
  878. rt_kprintf("AT send ping commands error!\n");
  879. return -RT_ERROR;
  880. }
  881. if (resp)
  882. {
  883. at_delete_resp(resp);
  884. }
  885. return RT_EOK;
  886. }
  887. int sim76xx_connect(int argc, char **argv)
  888. {
  889. int32_t port;
  890. if (argc != 3)
  891. {
  892. rt_kprintf("Please input: at_connect <host address>\n");
  893. return -RT_ERROR;
  894. }
  895. sscanf(argv[2],"%d",&port);
  896. sim76xx_socket_connect(0, argv[1], port, AT_SOCKET_TCP, 1);
  897. return RT_EOK;
  898. }
  899. int sim76xx_close(int argc, char **argv)
  900. {
  901. if (sim76xx_socket_close(0) < 0)
  902. {
  903. rt_kprintf("sim76xx_socket_close fail\n");
  904. }
  905. else
  906. {
  907. rt_kprintf("sim76xx_socket_closeed\n");
  908. }
  909. return RT_EOK;
  910. }
  911. int sim76xx_send(int argc, char **argv)
  912. {
  913. const char *buff = "1234567890\n";
  914. if (sim76xx_socket_send(0, buff, 11, AT_SOCKET_TCP) < 0)
  915. {
  916. rt_kprintf("sim76xx_socket_send fail\n");
  917. }
  918. return RT_EOK;
  919. }
  920. int sim76xx_domain(int argc, char **argv)
  921. {
  922. char ip[16];
  923. if (sim76xx_domain_resolve("www.baidu.com", ip) < 0)
  924. {
  925. rt_kprintf("sim76xx_socket_send fail\n");
  926. }
  927. else
  928. {
  929. rt_kprintf("baidu.com : %s\n", ip);
  930. }
  931. return RT_EOK;
  932. }
  933. int sim76xx_ifconfig(void)
  934. {
  935. at_response_t resp = RT_NULL;
  936. char resp_arg[AT_CMD_MAX_LEN] = { 0 };
  937. rt_err_t result = RT_EOK;
  938. resp = at_create_resp(128, 2, rt_tick_from_millisecond(300));
  939. if (!resp)
  940. {
  941. rt_kprintf("No memory for response structure!\n");
  942. return -RT_ENOMEM;
  943. }
  944. /* Show PDP address */
  945. AT_SEND_CMD(resp, "AT+CGPADDR");
  946. at_resp_parse_line_args_by_kw(resp, "+CGPADDR:", "+CGPADDR: %s", &resp_arg);
  947. rt_kprintf("IP adress : %s\n", resp_arg);
  948. __exit:
  949. if (resp)
  950. {
  951. at_delete_resp(resp);
  952. }
  953. return result;
  954. }
  955. #ifdef FINSH_USING_MSH
  956. #include <finsh.h>
  957. MSH_CMD_EXPORT_ALIAS(sim76xx_net_init, at_net_init, initialize AT network);
  958. MSH_CMD_EXPORT_ALIAS(sim76xx_ping, at_ping, AT ping network host);
  959. MSH_CMD_EXPORT_ALIAS(sim76xx_ifconfig, at_ifconfig, list the information of network interfaces);
  960. MSH_CMD_EXPORT_ALIAS(sim76xx_connect, at_connect, AT connect network host);
  961. MSH_CMD_EXPORT_ALIAS(sim76xx_close, at_close, AT close a socket);
  962. MSH_CMD_EXPORT_ALIAS(sim76xx_send, at_send, AT send a pack);
  963. MSH_CMD_EXPORT_ALIAS(sim76xx_domain, at_domain, AT domain resolve);
  964. #endif
  965. static const struct at_device_ops sim76xx_socket_ops = {
  966. sim76xx_socket_connect,
  967. sim76xx_socket_close,
  968. sim76xx_socket_send,
  969. sim76xx_domain_resolve,
  970. sim76xx_socket_set_event_cb,
  971. };
  972. static int sim76xx_netdev_add(const char *netdev_name)
  973. {
  974. #define ETHERNET_MTU 1500
  975. #define HWADDR_LEN 8
  976. struct netdev *netdev = RT_NULL;
  977. int result = 0;
  978. RT_ASSERT(netdev_name);
  979. netdev = (struct netdev *) rt_calloc(1, sizeof(struct netdev));
  980. if (netdev == RT_NULL)
  981. {
  982. return RT_NULL;
  983. }
  984. netdev->mtu = ETHERNET_MTU;
  985. netdev->hwaddr_len = HWADDR_LEN;
  986. netdev->ops = RT_NULL;
  987. #ifdef SAL_USING_AT
  988. extern int sal_at_netdev_set_pf_info(struct netdev *netdev);
  989. /* set the network interface socket/netdb operations */
  990. sal_at_netdev_set_pf_info(netdev);
  991. #endif
  992. result = netdev_register(netdev, netdev_name, RT_NULL);
  993. /*TODO: improve netdev adaptation */
  994. netdev_low_level_set_status(netdev, RT_TRUE);
  995. netdev_low_level_set_link_status(netdev, RT_TRUE);
  996. netdev_low_level_set_dhcp_status(netdev, RT_TRUE);
  997. netdev->flags |= NETDEV_FLAG_INTERNET_UP;
  998. return result;
  999. }
  1000. static int at_socket_device_init(void)
  1001. {
  1002. /* create current AT socket event */
  1003. at_socket_event = rt_event_create("at_se", RT_IPC_FLAG_FIFO);
  1004. if (at_socket_event == RT_NULL)
  1005. {
  1006. LOG_E("RT AT client port initialize failed! at_sock_event create failed!");
  1007. return -RT_ENOMEM;
  1008. }
  1009. /* create current AT socket event lock */
  1010. at_event_lock = rt_mutex_create("at_se", RT_IPC_FLAG_FIFO);
  1011. if (at_event_lock == RT_NULL)
  1012. {
  1013. LOG_E("RT AT client port initialize failed! at_sock_lock create failed!");
  1014. rt_event_delete(at_socket_event);
  1015. return -RT_ENOMEM;
  1016. }
  1017. /* initialize AT client */
  1018. at_client_init(AT_DEVICE_NAME, AT_DEVICE_RECV_BUFF_LEN);
  1019. /* register URC data execution function */
  1020. at_set_urc_table(urc_table, sizeof(urc_table) / sizeof(urc_table[0]));
  1021. /* add network interface device to netdev list */
  1022. if (sim76xx_netdev_add(SIM76XX_NETDEV_NAME) < 0)
  1023. {
  1024. LOG_E("SIM76xx network interface device(%d) add failed.", SIM76XX_NETDEV_NAME);
  1025. return -RT_ENOMEM;
  1026. }
  1027. /* initialize sim76xx pin config */
  1028. rt_pin_mode(AT_DEVICE_POWER_PIN, PIN_MODE_OUTPUT);
  1029. rt_pin_mode(AT_DEVICE_STATUS_PIN, PIN_MODE_INPUT);
  1030. /* initialize sim76xx network */
  1031. sim76xx_net_init();
  1032. /* set sim76xx AT Socket options */
  1033. at_socket_device_register(&sim76xx_socket_ops);
  1034. return RT_EOK;
  1035. }
  1036. INIT_APP_EXPORT(at_socket_device_init);
  1037. #endif /* AT_DEVICE_SIM76XX */