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.

981 lines
22 KiB

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