You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

962 lines
22 KiB

8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
7 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
7 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
7 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
7 years ago
8 years ago
8 years ago
7 years ago
8 years ago
7 years ago
8 years ago
8 years ago
8 years ago
8 years ago
7 years ago
8 years ago
8 years ago
7 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
7 years ago
  1. /**
  2. * @file TinyGsmClientSIM800.h
  3. * @author Volodymyr Shymanskyy
  4. * @license LGPL-3.0
  5. * @copyright Copyright (c) 2016 Volodymyr Shymanskyy
  6. * @date Nov 2016
  7. */
  8. #ifndef TinyGsmClientSIM800_h
  9. #define TinyGsmClientSIM800_h
  10. // #define TINY_GSM_DEBUG Serial
  11. // #define TINY_GSM_USE_HEX
  12. #if !defined(TINY_GSM_RX_BUFFER)
  13. #define TINY_GSM_RX_BUFFER 64
  14. #endif
  15. #define TINY_GSM_MUX_COUNT 5
  16. #include <TinyGsmCommon.h>
  17. #define GSM_NL "\r\n"
  18. static const char GSM_OK[] TINY_GSM_PROGMEM = "OK" GSM_NL;
  19. static const char GSM_ERROR[] TINY_GSM_PROGMEM = "ERROR" GSM_NL;
  20. enum SimStatus {
  21. SIM_ERROR = 0,
  22. SIM_READY = 1,
  23. SIM_LOCKED = 2,
  24. };
  25. enum RegStatus {
  26. REG_UNREGISTERED = 0,
  27. REG_SEARCHING = 2,
  28. REG_DENIED = 3,
  29. REG_OK_HOME = 1,
  30. REG_OK_ROAMING = 5,
  31. REG_UNKNOWN = 4,
  32. };
  33. class TinyGsmSim800
  34. {
  35. public:
  36. class GsmClient : public Client
  37. {
  38. friend class TinyGsmSim800;
  39. typedef TinyGsmFifo<uint8_t, TINY_GSM_RX_BUFFER> RxFifo;
  40. public:
  41. GsmClient() {}
  42. GsmClient(TinyGsmSim800& modem, uint8_t mux = 1) {
  43. init(&modem, mux);
  44. }
  45. bool init(TinyGsmSim800* modem, uint8_t mux = 1) {
  46. this->at = modem;
  47. this->mux = mux;
  48. sock_available = 0;
  49. prev_check = 0;
  50. sock_connected = false;
  51. got_data = false;
  52. at->sockets[mux] = this;
  53. return true;
  54. }
  55. public:
  56. virtual int connect(const char *host, uint16_t port) {
  57. TINY_GSM_YIELD();
  58. rx.clear();
  59. sock_connected = at->modemConnect(host, port, mux);
  60. return sock_connected;
  61. }
  62. virtual int connect(IPAddress ip, uint16_t port) {
  63. String host; host.reserve(16);
  64. host += ip[0];
  65. host += ".";
  66. host += ip[1];
  67. host += ".";
  68. host += ip[2];
  69. host += ".";
  70. host += ip[3];
  71. return connect(host.c_str(), port);
  72. }
  73. virtual void stop() {
  74. TINY_GSM_YIELD();
  75. at->sendAT(GF("+CIPCLOSE="), mux);
  76. sock_connected = false;
  77. at->waitResponse();
  78. }
  79. virtual size_t write(const uint8_t *buf, size_t size) {
  80. TINY_GSM_YIELD();
  81. at->maintain();
  82. return at->modemSend(buf, size, mux);
  83. }
  84. virtual size_t write(uint8_t c) {
  85. return write(&c, 1);
  86. }
  87. virtual int available() {
  88. TINY_GSM_YIELD();
  89. if (!rx.size() && sock_connected) {
  90. // Workaround: sometimes SIM800 forgets to notify about data arrival.
  91. // TODO: Currently we ping the module periodically,
  92. // but maybe there's a better indicator that we need to poll
  93. if (millis() - prev_check > 500) {
  94. got_data = true;
  95. prev_check = millis();
  96. }
  97. at->maintain();
  98. }
  99. return rx.size() + sock_available;
  100. }
  101. virtual int read(uint8_t *buf, size_t size) {
  102. TINY_GSM_YIELD();
  103. at->maintain();
  104. size_t cnt = 0;
  105. while (cnt < size) {
  106. size_t chunk = TinyGsmMin(size-cnt, rx.size());
  107. if (chunk > 0) {
  108. rx.get(buf, chunk);
  109. buf += chunk;
  110. cnt += chunk;
  111. continue;
  112. }
  113. // TODO: Read directly into user buffer?
  114. at->maintain();
  115. if (sock_available > 0) {
  116. at->modemRead(rx.free(), mux);
  117. } else {
  118. break;
  119. }
  120. }
  121. return cnt;
  122. }
  123. virtual int read() {
  124. uint8_t c;
  125. if (read(&c, 1) == 1) {
  126. return c;
  127. }
  128. return -1;
  129. }
  130. virtual int peek() { return -1; } //TODO
  131. virtual void flush() { at->stream.flush(); }
  132. virtual uint8_t connected() {
  133. if (available()) {
  134. return true;
  135. }
  136. return sock_connected;
  137. }
  138. virtual operator bool() { return connected(); }
  139. /*
  140. * Extended API
  141. */
  142. String remoteIP() TINY_GSM_ATTR_NOT_IMPLEMENTED;
  143. private:
  144. TinyGsmSim800* at;
  145. uint8_t mux;
  146. uint16_t sock_available;
  147. uint32_t prev_check;
  148. bool sock_connected;
  149. bool got_data;
  150. RxFifo rx;
  151. };
  152. class GsmClientSecure : public GsmClient
  153. {
  154. public:
  155. GsmClientSecure() {}
  156. GsmClientSecure(TinyGsmSim800& modem, uint8_t mux = 1)
  157. : GsmClient(modem, mux)
  158. {}
  159. public:
  160. virtual int connect(const char *host, uint16_t port) {
  161. TINY_GSM_YIELD();
  162. rx.clear();
  163. sock_connected = at->modemConnect(host, port, mux, true);
  164. return sock_connected;
  165. }
  166. };
  167. public:
  168. TinyGsmSim800(Stream& stream)
  169. : stream(stream)
  170. {
  171. memset(sockets, 0, sizeof(sockets));
  172. }
  173. /*
  174. * Basic functions
  175. */
  176. bool begin() {
  177. return init();
  178. }
  179. bool init() {
  180. if (!autoBaud()) {
  181. return false;
  182. }
  183. sendAT(GF("&FZ")); // Factory + Reset
  184. waitResponse();
  185. sendAT(GF("E0")); // Echo Off
  186. if (waitResponse() != 1) {
  187. return false;
  188. }
  189. getSimStatus();
  190. return true;
  191. }
  192. bool autoBaud(unsigned long timeout = 10000L) {
  193. //streamWrite(GF("AAAAA" GSM_NL)); // TODO: extra A's to help detect the baud rate
  194. for (unsigned long start = millis(); millis() - start < timeout; ) {
  195. sendAT(GF(""));
  196. if (waitResponse(200) == 1) {
  197. delay(100);
  198. return true;
  199. }
  200. delay(100);
  201. }
  202. return false;
  203. }
  204. void maintain() {
  205. for (int mux = 0; mux < TINY_GSM_MUX_COUNT; mux++) {
  206. GsmClient* sock = sockets[mux];
  207. if (sock && sock->got_data) {
  208. sock->got_data = false;
  209. sock->sock_available = modemGetAvailable(mux);
  210. }
  211. }
  212. while (stream.available()) {
  213. waitResponse(10, NULL, NULL);
  214. }
  215. }
  216. bool factoryDefault() {
  217. sendAT(GF("&FZE0&W")); // Factory + Reset + Echo Off + Write
  218. waitResponse();
  219. sendAT(GF("+IPR=0")); // Auto-baud
  220. waitResponse();
  221. sendAT(GF("+IFC=0,0")); // No Flow Control
  222. waitResponse();
  223. sendAT(GF("+ICF=3,3")); // 8 data 0 parity 1 stop
  224. waitResponse();
  225. sendAT(GF("+CSCLK=0")); // Disable Slow Clock
  226. waitResponse();
  227. sendAT(GF("&W")); // Write configuration
  228. return waitResponse() == 1;
  229. }
  230. String getModemInfo() {
  231. sendAT(GF("I"));
  232. String res;
  233. if (waitResponse(1000L, res) != 1) {
  234. return "";
  235. }
  236. res.replace(GSM_NL "OK" GSM_NL, "");
  237. res.replace(GSM_NL, " ");
  238. res.trim();
  239. return res;
  240. }
  241. bool hasSSL() {
  242. sendAT(GF("+CIPSSL=?"));
  243. if (waitResponse(GF(GSM_NL "+CIPSSL:")) != 1) {
  244. return false;
  245. }
  246. return waitResponse() == 1;
  247. }
  248. /*
  249. * Power functions
  250. */
  251. bool restart() {
  252. if (!autoBaud()) {
  253. return false;
  254. }
  255. sendAT(GF("+CFUN=0"));
  256. if (waitResponse(10000L) != 1) {
  257. return false;
  258. }
  259. sendAT(GF("+CFUN=1,1"));
  260. if (waitResponse(10000L) != 1) {
  261. return false;
  262. }
  263. delay(3000);
  264. return init();
  265. }
  266. bool poweroff() {
  267. sendAT(GF("+CPOWD=1"));
  268. return waitResponse(GF("NORMAL POWER DOWN")) == 1;
  269. }
  270. bool radioOff() {
  271. if (!autoBaud()) {
  272. return false;
  273. }
  274. sendAT(GF("+CFUN=0"));
  275. if (waitResponse(10000L) != 1) {
  276. return false;
  277. }
  278. delay(3000);
  279. return true;
  280. }
  281. /*
  282. * SIM card functions
  283. */
  284. bool simUnlock(const char *pin) {
  285. sendAT(GF("+CPIN=\""), pin, GF("\""));
  286. return waitResponse() == 1;
  287. }
  288. String getSimCCID() {
  289. sendAT(GF("+ICCID"));
  290. if (waitResponse(GF(GSM_NL "+ICCID:")) != 1) {
  291. return "";
  292. }
  293. String res = stream.readStringUntil('\n');
  294. waitResponse();
  295. res.trim();
  296. return res;
  297. }
  298. String getIMEI() {
  299. sendAT(GF("+GSN"));
  300. if (waitResponse(GF(GSM_NL)) != 1) {
  301. return "";
  302. }
  303. String res = stream.readStringUntil('\n');
  304. waitResponse();
  305. res.trim();
  306. return res;
  307. }
  308. SimStatus getSimStatus(unsigned long timeout = 10000L) {
  309. for (unsigned long start = millis(); millis() - start < timeout; ) {
  310. sendAT(GF("+CPIN?"));
  311. if (waitResponse(GF(GSM_NL "+CPIN:")) != 1) {
  312. delay(1000);
  313. continue;
  314. }
  315. int status = waitResponse(GF("READY"), GF("SIM PIN"), GF("SIM PUK"), GF("NOT INSERTED"));
  316. waitResponse();
  317. switch (status) {
  318. case 2:
  319. case 3: return SIM_LOCKED;
  320. case 1: return SIM_READY;
  321. default: return SIM_ERROR;
  322. }
  323. }
  324. return SIM_ERROR;
  325. }
  326. RegStatus getRegistrationStatus() {
  327. sendAT(GF("+CREG?"));
  328. if (waitResponse(GF(GSM_NL "+CREG:")) != 1) {
  329. return REG_UNKNOWN;
  330. }
  331. streamSkipUntil(','); // Skip format (0)
  332. int status = stream.readStringUntil('\n').toInt();
  333. waitResponse();
  334. return (RegStatus)status;
  335. }
  336. String getOperator() {
  337. sendAT(GF("+COPS?"));
  338. if (waitResponse(GF(GSM_NL "+COPS:")) != 1) {
  339. return "";
  340. }
  341. streamSkipUntil('"'); // Skip mode and format
  342. String res = stream.readStringUntil('"');
  343. waitResponse();
  344. return res;
  345. }
  346. /*
  347. * Generic network functions
  348. */
  349. int getSignalQuality() {
  350. sendAT(GF("+CSQ"));
  351. if (waitResponse(GF(GSM_NL "+CSQ:")) != 1) {
  352. return 99;
  353. }
  354. int res = stream.readStringUntil(',').toInt();
  355. waitResponse();
  356. return res;
  357. }
  358. bool isNetworkConnected() {
  359. RegStatus s = getRegistrationStatus();
  360. return (s == REG_OK_HOME || s == REG_OK_ROAMING);
  361. }
  362. bool waitForNetwork(unsigned long timeout = 60000L) {
  363. for (unsigned long start = millis(); millis() - start < timeout; ) {
  364. if (isNetworkConnected()) {
  365. return true;
  366. }
  367. delay(500);
  368. }
  369. return false;
  370. }
  371. /*
  372. * WiFi functions
  373. */
  374. bool networkConnect(const char* ssid, const char* pwd) {
  375. return false;
  376. }
  377. bool networkDisconnect() {
  378. return false;
  379. }
  380. /*
  381. * GPRS functions
  382. */
  383. bool gprsConnect(const char* apn, const char* user, const char* pwd) {
  384. gprsDisconnect();
  385. sendAT(GF("+SAPBR=3,1,\"Contype\",\"GPRS\""));
  386. waitResponse();
  387. sendAT(GF("+SAPBR=3,1,\"APN\",\""), apn, '"');
  388. waitResponse();
  389. if (user) {
  390. sendAT(GF("+SAPBR=3,1,\"USER\",\""), user, '"');
  391. waitResponse();
  392. }
  393. if (pwd) {
  394. sendAT(GF("+SAPBR=3,1,\"PWD\",\""), pwd, '"');
  395. waitResponse();
  396. }
  397. sendAT(GF("+CGDCONT=1,\"IP\",\""), apn, '"');
  398. waitResponse();
  399. sendAT(GF("+CGACT=1,1"));
  400. waitResponse(60000L);
  401. // Open a GPRS context
  402. sendAT(GF("+SAPBR=1,1"));
  403. waitResponse(85000L);
  404. // Query the GPRS context
  405. sendAT(GF("+SAPBR=2,1"));
  406. if (waitResponse(30000L) != 1)
  407. return false;
  408. sendAT(GF("+CGATT=1"));
  409. if (waitResponse(60000L) != 1)
  410. return false;
  411. // TODO: wait AT+CGATT?
  412. sendAT(GF("+CIPMUX=1"));
  413. if (waitResponse() != 1) {
  414. return false;
  415. }
  416. sendAT(GF("+CIPQSEND=1"));
  417. if (waitResponse() != 1) {
  418. return false;
  419. }
  420. sendAT(GF("+CIPRXGET=1"));
  421. if (waitResponse() != 1) {
  422. return false;
  423. }
  424. sendAT(GF("+CSTT=\""), apn, GF("\",\""), user, GF("\",\""), pwd, GF("\""));
  425. if (waitResponse(60000L) != 1) {
  426. return false;
  427. }
  428. sendAT(GF("+CIICR"));
  429. if (waitResponse(60000L) != 1) {
  430. return false;
  431. }
  432. sendAT(GF("+CIFSR;E0"));
  433. if (waitResponse(10000L) != 1) {
  434. return false;
  435. }
  436. sendAT(GF("+CDNSCFG=\"8.8.8.8\",\"8.8.4.4\""));
  437. if (waitResponse() != 1) {
  438. return false;
  439. }
  440. return true;
  441. }
  442. bool gprsDisconnect() {
  443. sendAT(GF("+CIPSHUT"));
  444. if (waitResponse(60000L) != 1)
  445. return false;
  446. sendAT(GF("+CGATT=0"));
  447. if (waitResponse(60000L) != 1)
  448. return false;
  449. return true;
  450. }
  451. bool isGprsConnected() {
  452. sendAT(GF("+CGATT?"));
  453. if (waitResponse(GF(GSM_NL "+CGATT:")) != 1) {
  454. return false;
  455. }
  456. int res = stream.readStringUntil('\n').toInt();
  457. waitResponse();
  458. if (res != 1)
  459. return false;
  460. sendAT(GF("+CIFSR;E0")); // Another option is to use AT+CGPADDR=1
  461. if (waitResponse() != 1)
  462. return false;
  463. return true;
  464. }
  465. String getLocalIP() {
  466. sendAT(GF("+CIFSR;E0"));
  467. String res;
  468. if (waitResponse(10000L, res) != 1) {
  469. return "";
  470. }
  471. res.trim();
  472. return res;
  473. }
  474. IPAddress localIP() {
  475. String strIP = getLocalIP();
  476. int Parts[4] = {0,0,0,0};
  477. int Part = 0;
  478. for (uint8_t i=0; i<strIP.length(); i++) {
  479. char c = strIP[i];
  480. if (c == '.') {
  481. Part++;
  482. continue;
  483. }
  484. Parts[Part] *= 10;
  485. Parts[Part] += c - '0';
  486. }
  487. IPAddress res(Parts[0], Parts[1], Parts[2], Parts[3]);
  488. return res;
  489. }
  490. /*
  491. * Phone Call functions
  492. */
  493. bool setGsmBusy(bool busy = true) {
  494. sendAT(GF("+GSMBUSY="), busy ? 1 : 0);
  495. return waitResponse() == 1;
  496. }
  497. bool callAnswer() {
  498. sendAT(GF("A"));
  499. return waitResponse() == 1;
  500. }
  501. // Returns true on pick-up, false on error/busy
  502. bool callNumber(const String& number) {
  503. sendAT(GF("D"), number, ";");
  504. int status = waitResponse(60000L, GF("OK"), GF("BUSY"), GF("NO ANSWER"), GF("NO CARRIER"));
  505. switch (status) {
  506. case 1: return true;
  507. case 2:
  508. case 3: return false;
  509. default: return false;
  510. }
  511. }
  512. //bool callRedial() {
  513. // sendAT(GF("DL"));
  514. // return waitResponse() == 1;
  515. //}
  516. bool callHangup() {
  517. sendAT(GF("H"));
  518. return waitResponse() == 1;
  519. }
  520. /*
  521. * Messaging functions
  522. */
  523. String sendUSSD(const String& code) {
  524. sendAT(GF("+CMGF=1"));
  525. waitResponse();
  526. sendAT(GF("+CSCS=\"HEX\""));
  527. waitResponse();
  528. sendAT(GF("+CUSD=1,\""), code, GF("\""));
  529. if (waitResponse() != 1) {
  530. return "";
  531. }
  532. if (waitResponse(10000L, GF(GSM_NL "+CUSD:")) != 1) {
  533. return "";
  534. }
  535. stream.readStringUntil('"');
  536. String hex = stream.readStringUntil('"');
  537. stream.readStringUntil(',');
  538. int dcs = stream.readStringUntil('\n').toInt();
  539. if (dcs == 15) {
  540. return decodeHex8bit(hex);
  541. } else if (dcs == 72) {
  542. return decodeHex16bit(hex);
  543. } else {
  544. return hex;
  545. }
  546. }
  547. bool sendSMS(const String& number, const String& text) {
  548. sendAT(GF("+CMGF=1"));
  549. waitResponse();
  550. sendAT(GF("+CMGS=\""), number, GF("\""));
  551. if (waitResponse(GF(">")) != 1) {
  552. return false;
  553. }
  554. stream.print(text);
  555. stream.write((char)0x1A);
  556. stream.flush();
  557. return waitResponse(60000L) == 1;
  558. }
  559. bool sendSMS_UTF16(const String& number, const void* text, size_t len) {
  560. sendAT(GF("+CMGF=1"));
  561. waitResponse();
  562. sendAT(GF("+CSCS=\"HEX\""));
  563. waitResponse();
  564. sendAT(GF("+CSMP=17,167,0,8"));
  565. waitResponse();
  566. sendAT(GF("+CMGS=\""), number, GF("\""));
  567. if (waitResponse(GF(">")) != 1) {
  568. return false;
  569. }
  570. uint16_t* t = (uint16_t*)text;
  571. for (size_t i=0; i<len; i++) {
  572. uint8_t c = t[i] >> 8;
  573. if (c < 0x10) { stream.print('0'); }
  574. stream.print(c, HEX);
  575. c = t[i] & 0xFF;
  576. if (c < 0x10) { stream.print('0'); }
  577. stream.print(c, HEX);
  578. }
  579. stream.write((char)0x1A);
  580. stream.flush();
  581. return waitResponse(60000L) == 1;
  582. }
  583. /*
  584. * Location functions
  585. */
  586. String getGsmLocation() {
  587. sendAT(GF("+CIPGSMLOC=1,1"));
  588. if (waitResponse(10000L, GF(GSM_NL "+CIPGSMLOC:")) != 1) {
  589. return "";
  590. }
  591. String res = stream.readStringUntil('\n');
  592. waitResponse();
  593. res.trim();
  594. return res;
  595. }
  596. /*
  597. * Battery functions
  598. */
  599. // Use: float vBatt = modem.getBattVoltage() / 1000.0;
  600. uint16_t getBattVoltage() {
  601. sendAT(GF("+CBC"));
  602. if (waitResponse(GF(GSM_NL "+CBC:")) != 1) {
  603. return 0;
  604. }
  605. streamSkipUntil(','); // Skip
  606. streamSkipUntil(','); // Skip
  607. uint16_t res = stream.readStringUntil(',').toInt();
  608. waitResponse();
  609. return res;
  610. }
  611. int getBattPercent() {
  612. sendAT(GF("+CBC"));
  613. if (waitResponse(GF(GSM_NL "+CBC:")) != 1) {
  614. return false;
  615. }
  616. stream.readStringUntil(',');
  617. int res = stream.readStringUntil(',').toInt();
  618. waitResponse();
  619. return res;
  620. }
  621. protected:
  622. bool modemConnect(const char* host, uint16_t port, uint8_t mux, bool ssl = false) {
  623. sendAT(GF("+CIPSSL="), ssl);
  624. int rsp = waitResponse();
  625. if (ssl && rsp != 1) {
  626. return false;
  627. }
  628. sendAT(GF("+CIPSTART="), mux, ',', GF("\"TCP"), GF("\",\""), host, GF("\","), port);
  629. rsp = waitResponse(75000L,
  630. GF("CONNECT OK" GSM_NL),
  631. GF("CONNECT FAIL" GSM_NL),
  632. GF("ALREADY CONNECT" GSM_NL));
  633. return (1 == rsp);
  634. }
  635. int modemSend(const void* buff, size_t len, uint8_t mux) {
  636. sendAT(GF("+CIPSEND="), mux, ',', len);
  637. if (waitResponse(GF(">")) != 1) {
  638. return -1;
  639. }
  640. stream.write((uint8_t*)buff, len);
  641. stream.flush();
  642. if (waitResponse(GF(GSM_NL "DATA ACCEPT:")) != 1) {
  643. return -1;
  644. }
  645. streamSkipUntil(','); // Skip mux
  646. return stream.readStringUntil('\n').toInt();
  647. }
  648. size_t modemRead(size_t size, uint8_t mux) {
  649. #ifdef TINY_GSM_USE_HEX
  650. sendAT(GF("+CIPRXGET=3,"), mux, ',', size);
  651. if (waitResponse(GF("+CIPRXGET:")) != 1) {
  652. return 0;
  653. }
  654. #else
  655. sendAT(GF("+CIPRXGET=2,"), mux, ',', size);
  656. if (waitResponse(GF("+CIPRXGET:")) != 1) {
  657. return 0;
  658. }
  659. #endif
  660. streamSkipUntil(','); // Skip mode 2/3
  661. streamSkipUntil(','); // Skip mux
  662. size_t len = stream.readStringUntil(',').toInt();
  663. sockets[mux]->sock_available = stream.readStringUntil('\n').toInt();
  664. for (size_t i=0; i<len; i++) {
  665. #ifdef TINY_GSM_USE_HEX
  666. while (stream.available() < 2) { TINY_GSM_YIELD(); }
  667. char buf[4] = { 0, };
  668. buf[0] = stream.read();
  669. buf[1] = stream.read();
  670. char c = strtol(buf, NULL, 16);
  671. #else
  672. while (!stream.available()) { TINY_GSM_YIELD(); }
  673. char c = stream.read();
  674. #endif
  675. sockets[mux]->rx.put(c);
  676. }
  677. waitResponse();
  678. return len;
  679. }
  680. size_t modemGetAvailable(uint8_t mux) {
  681. sendAT(GF("+CIPRXGET=4,"), mux);
  682. size_t result = 0;
  683. if (waitResponse(GF("+CIPRXGET:")) == 1) {
  684. streamSkipUntil(','); // Skip mode 4
  685. streamSkipUntil(','); // Skip mux
  686. result = stream.readStringUntil('\n').toInt();
  687. waitResponse();
  688. }
  689. if (!result) {
  690. sockets[mux]->sock_connected = modemGetConnected(mux);
  691. }
  692. return result;
  693. }
  694. bool modemGetConnected(uint8_t mux) {
  695. sendAT(GF("+CIPSTATUS="), mux);
  696. int res = waitResponse(GF(",\"CONNECTED\""), GF(",\"CLOSED\""), GF(",\"CLOSING\""), GF(",\"INITIAL\""));
  697. waitResponse();
  698. return 1 == res;
  699. }
  700. static String decodeHex8bit(String &instr) {
  701. String result;
  702. for (unsigned i=0; i<instr.length(); i+=2) {
  703. char buf[4] = { 0, };
  704. buf[0] = instr[i];
  705. buf[1] = instr[i+1];
  706. char b = strtol(buf, NULL, 16);
  707. result += b;
  708. }
  709. return result;
  710. }
  711. static String decodeHex16bit(String &instr) {
  712. String result;
  713. for (unsigned i=0; i<instr.length(); i+=4) {
  714. char buf[4] = { 0, };
  715. buf[0] = instr[i];
  716. buf[1] = instr[i+1];
  717. char b = strtol(buf, NULL, 16);
  718. if (b) { // If high byte is non-zero, we can't handle it ;(
  719. b = '?';
  720. } else {
  721. buf[0] = instr[i+2];
  722. buf[1] = instr[i+3];
  723. b = strtol(buf, NULL, 16);
  724. }
  725. result += b;
  726. }
  727. return result;
  728. }
  729. public:
  730. /* Utilities */
  731. template<typename T>
  732. void streamWrite(T last) {
  733. stream.print(last);
  734. }
  735. template<typename T, typename... Args>
  736. void streamWrite(T head, Args... tail) {
  737. stream.print(head);
  738. streamWrite(tail...);
  739. }
  740. bool streamSkipUntil(char c) { //TODO: timeout
  741. while (true) {
  742. while (!stream.available()) { TINY_GSM_YIELD(); }
  743. if (stream.read() == c)
  744. return true;
  745. }
  746. return false;
  747. }
  748. template<typename... Args>
  749. void sendAT(Args... cmd) {
  750. streamWrite("AT", cmd..., GSM_NL);
  751. stream.flush();
  752. TINY_GSM_YIELD();
  753. DBG("### AT:", cmd...);
  754. }
  755. // TODO: Optimize this!
  756. uint8_t waitResponse(uint32_t timeout, String& data,
  757. GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  758. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  759. {
  760. /*String r1s(r1); r1s.trim();
  761. String r2s(r2); r2s.trim();
  762. String r3s(r3); r3s.trim();
  763. String r4s(r4); r4s.trim();
  764. String r5s(r5); r5s.trim();
  765. DBG("### ..:", r1s, ",", r2s, ",", r3s, ",", r4s, ",", r5s);*/
  766. data.reserve(64);
  767. int index = 0;
  768. unsigned long startMillis = millis();
  769. do {
  770. TINY_GSM_YIELD();
  771. while (stream.available() > 0) {
  772. int a = stream.read();
  773. if (a <= 0) continue; // Skip 0x00 bytes, just in case
  774. data += (char)a;
  775. if (r1 && data.endsWith(r1)) {
  776. index = 1;
  777. goto finish;
  778. } else if (r2 && data.endsWith(r2)) {
  779. index = 2;
  780. goto finish;
  781. } else if (r3 && data.endsWith(r3)) {
  782. index = 3;
  783. goto finish;
  784. } else if (r4 && data.endsWith(r4)) {
  785. index = 4;
  786. goto finish;
  787. } else if (r5 && data.endsWith(r5)) {
  788. index = 5;
  789. goto finish;
  790. } else if (data.endsWith(GF(GSM_NL "+CIPRXGET:"))) {
  791. String mode = stream.readStringUntil(',');
  792. if (mode.toInt() == 1) {
  793. int mux = stream.readStringUntil('\n').toInt();
  794. if (mux >= 0 && mux < TINY_GSM_MUX_COUNT) {
  795. sockets[mux]->got_data = true;
  796. }
  797. data = "";
  798. } else {
  799. data += mode;
  800. }
  801. } else if (data.endsWith(GF("CLOSED" GSM_NL))) {
  802. int nl = data.lastIndexOf(GSM_NL, data.length()-8);
  803. int coma = data.indexOf(',', nl+2);
  804. int mux = data.substring(nl+2, coma).toInt();
  805. if (mux >= 0 && mux < TINY_GSM_MUX_COUNT) {
  806. sockets[mux]->sock_connected = false;
  807. }
  808. data = "";
  809. DBG("### Closed: ", mux);
  810. }
  811. }
  812. } while (millis() - startMillis < timeout);
  813. finish:
  814. if (!index) {
  815. data.trim();
  816. if (data.length()) {
  817. DBG("### Unhandled:", data);
  818. }
  819. data = "";
  820. }
  821. return index;
  822. }
  823. uint8_t waitResponse(uint32_t timeout,
  824. GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  825. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  826. {
  827. String data;
  828. return waitResponse(timeout, data, r1, r2, r3, r4, r5);
  829. }
  830. uint8_t waitResponse(GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  831. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  832. {
  833. return waitResponse(1000, r1, r2, r3, r4, r5);
  834. }
  835. protected:
  836. Stream& stream;
  837. GsmClient* sockets[TINY_GSM_MUX_COUNT];
  838. };
  839. #endif