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.

951 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
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. * GPRS functions
  373. */
  374. bool gprsConnect(const char* apn, const char* user, const char* pwd) {
  375. gprsDisconnect();
  376. sendAT(GF("+SAPBR=3,1,\"Contype\",\"GPRS\""));
  377. waitResponse();
  378. sendAT(GF("+SAPBR=3,1,\"APN\",\""), apn, '"');
  379. waitResponse();
  380. if (user && strlen(user) > 0) {
  381. sendAT(GF("+SAPBR=3,1,\"USER\",\""), user, '"');
  382. waitResponse();
  383. }
  384. if (pwd && strlen(pwd) > 0) {
  385. sendAT(GF("+SAPBR=3,1,\"PWD\",\""), pwd, '"');
  386. waitResponse();
  387. }
  388. sendAT(GF("+CGDCONT=1,\"IP\",\""), apn, '"');
  389. waitResponse();
  390. sendAT(GF("+CGACT=1,1"));
  391. waitResponse(60000L);
  392. // Open a GPRS context
  393. sendAT(GF("+SAPBR=1,1"));
  394. waitResponse(85000L);
  395. // Query the GPRS context
  396. sendAT(GF("+SAPBR=2,1"));
  397. if (waitResponse(30000L) != 1)
  398. return false;
  399. sendAT(GF("+CGATT=1"));
  400. if (waitResponse(60000L) != 1)
  401. return false;
  402. // TODO: wait AT+CGATT?
  403. sendAT(GF("+CIPMUX=1"));
  404. if (waitResponse() != 1) {
  405. return false;
  406. }
  407. sendAT(GF("+CIPQSEND=1"));
  408. if (waitResponse() != 1) {
  409. return false;
  410. }
  411. sendAT(GF("+CIPRXGET=1"));
  412. if (waitResponse() != 1) {
  413. return false;
  414. }
  415. sendAT(GF("+CSTT=\""), apn, GF("\",\""), user, GF("\",\""), pwd, GF("\""));
  416. if (waitResponse(60000L) != 1) {
  417. return false;
  418. }
  419. sendAT(GF("+CIICR"));
  420. if (waitResponse(60000L) != 1) {
  421. return false;
  422. }
  423. sendAT(GF("+CIFSR;E0"));
  424. if (waitResponse(10000L) != 1) {
  425. return false;
  426. }
  427. sendAT(GF("+CDNSCFG=\"8.8.8.8\",\"8.8.4.4\""));
  428. if (waitResponse() != 1) {
  429. return false;
  430. }
  431. return true;
  432. }
  433. bool gprsDisconnect() {
  434. sendAT(GF("+CIPSHUT"));
  435. if (waitResponse(60000L) != 1)
  436. return false;
  437. sendAT(GF("+CGATT=0"));
  438. if (waitResponse(60000L) != 1)
  439. return false;
  440. return true;
  441. }
  442. bool isGprsConnected() {
  443. sendAT(GF("+CGATT?"));
  444. if (waitResponse(GF(GSM_NL "+CGATT:")) != 1) {
  445. return false;
  446. }
  447. int res = stream.readStringUntil('\n').toInt();
  448. waitResponse();
  449. if (res != 1)
  450. return false;
  451. sendAT(GF("+CIFSR;E0")); // Another option is to use AT+CGPADDR=1
  452. if (waitResponse() != 1)
  453. return false;
  454. return true;
  455. }
  456. String getLocalIP() {
  457. sendAT(GF("+CIFSR;E0"));
  458. String res;
  459. if (waitResponse(10000L, res) != 1) {
  460. return "";
  461. }
  462. res.trim();
  463. return res;
  464. }
  465. IPAddress localIP() {
  466. String strIP = getLocalIP();
  467. int Parts[4] = {0,0,0,0};
  468. int Part = 0;
  469. for (uint8_t i=0; i<strIP.length(); i++) {
  470. char c = strIP[i];
  471. if (c == '.') {
  472. Part++;
  473. continue;
  474. }
  475. Parts[Part] *= 10;
  476. Parts[Part] += c - '0';
  477. }
  478. IPAddress res(Parts[0], Parts[1], Parts[2], Parts[3]);
  479. return res;
  480. }
  481. /*
  482. * Phone Call functions
  483. */
  484. bool setGsmBusy(bool busy = true) {
  485. sendAT(GF("+GSMBUSY="), busy ? 1 : 0);
  486. return waitResponse() == 1;
  487. }
  488. bool callAnswer() {
  489. sendAT(GF("A"));
  490. return waitResponse() == 1;
  491. }
  492. // Returns true on pick-up, false on error/busy
  493. bool callNumber(const String& number) {
  494. sendAT(GF("D"), number, ";");
  495. int status = waitResponse(60000L, GF("OK"), GF("BUSY"), GF("NO ANSWER"), GF("NO CARRIER"));
  496. switch (status) {
  497. case 1: return true;
  498. case 2:
  499. case 3: return false;
  500. default: return false;
  501. }
  502. }
  503. //bool callRedial() {
  504. // sendAT(GF("DL"));
  505. // return waitResponse() == 1;
  506. //}
  507. bool callHangup() {
  508. sendAT(GF("H"));
  509. return waitResponse() == 1;
  510. }
  511. /*
  512. * Messaging functions
  513. */
  514. String sendUSSD(const String& code) {
  515. sendAT(GF("+CMGF=1"));
  516. waitResponse();
  517. sendAT(GF("+CSCS=\"HEX\""));
  518. waitResponse();
  519. sendAT(GF("+CUSD=1,\""), code, GF("\""));
  520. if (waitResponse() != 1) {
  521. return "";
  522. }
  523. if (waitResponse(10000L, GF(GSM_NL "+CUSD:")) != 1) {
  524. return "";
  525. }
  526. stream.readStringUntil('"');
  527. String hex = stream.readStringUntil('"');
  528. stream.readStringUntil(',');
  529. int dcs = stream.readStringUntil('\n').toInt();
  530. if (dcs == 15) {
  531. return decodeHex8bit(hex);
  532. } else if (dcs == 72) {
  533. return decodeHex16bit(hex);
  534. } else {
  535. return hex;
  536. }
  537. }
  538. bool sendSMS(const String& number, const String& text) {
  539. sendAT(GF("+CMGF=1"));
  540. waitResponse();
  541. sendAT(GF("+CMGS=\""), number, GF("\""));
  542. if (waitResponse(GF(">")) != 1) {
  543. return false;
  544. }
  545. stream.print(text);
  546. stream.write((char)0x1A);
  547. stream.flush();
  548. return waitResponse(60000L) == 1;
  549. }
  550. bool sendSMS_UTF16(const String& number, const void* text, size_t len) {
  551. sendAT(GF("+CMGF=1"));
  552. waitResponse();
  553. sendAT(GF("+CSCS=\"HEX\""));
  554. waitResponse();
  555. sendAT(GF("+CSMP=17,167,0,8"));
  556. waitResponse();
  557. sendAT(GF("+CMGS=\""), number, GF("\""));
  558. if (waitResponse(GF(">")) != 1) {
  559. return false;
  560. }
  561. uint16_t* t = (uint16_t*)text;
  562. for (size_t i=0; i<len; i++) {
  563. uint8_t c = t[i] >> 8;
  564. if (c < 0x10) { stream.print('0'); }
  565. stream.print(c, HEX);
  566. c = t[i] & 0xFF;
  567. if (c < 0x10) { stream.print('0'); }
  568. stream.print(c, HEX);
  569. }
  570. stream.write((char)0x1A);
  571. stream.flush();
  572. return waitResponse(60000L) == 1;
  573. }
  574. /*
  575. * Location functions
  576. */
  577. String getGsmLocation() {
  578. sendAT(GF("+CIPGSMLOC=1,1"));
  579. if (waitResponse(10000L, GF(GSM_NL "+CIPGSMLOC:")) != 1) {
  580. return "";
  581. }
  582. String res = stream.readStringUntil('\n');
  583. waitResponse();
  584. res.trim();
  585. return res;
  586. }
  587. /*
  588. * Battery functions
  589. */
  590. // Use: float vBatt = modem.getBattVoltage() / 1000.0;
  591. uint16_t getBattVoltage() {
  592. sendAT(GF("+CBC"));
  593. if (waitResponse(GF(GSM_NL "+CBC:")) != 1) {
  594. return 0;
  595. }
  596. streamSkipUntil(','); // Skip
  597. streamSkipUntil(','); // Skip
  598. uint16_t res = stream.readStringUntil(',').toInt();
  599. waitResponse();
  600. return res;
  601. }
  602. int getBattPercent() {
  603. sendAT(GF("+CBC"));
  604. if (waitResponse(GF(GSM_NL "+CBC:")) != 1) {
  605. return false;
  606. }
  607. stream.readStringUntil(',');
  608. int res = stream.readStringUntil(',').toInt();
  609. waitResponse();
  610. return res;
  611. }
  612. protected:
  613. bool modemConnect(const char* host, uint16_t port, uint8_t mux, bool ssl = false) {
  614. sendAT(GF("+CIPSSL="), ssl);
  615. int rsp = waitResponse();
  616. if (ssl && rsp != 1) {
  617. return false;
  618. }
  619. sendAT(GF("+CIPSTART="), mux, ',', GF("\"TCP"), GF("\",\""), host, GF("\","), port);
  620. rsp = waitResponse(75000L,
  621. GF("CONNECT OK" GSM_NL),
  622. GF("CONNECT FAIL" GSM_NL),
  623. GF("ALREADY CONNECT" GSM_NL));
  624. return (1 == rsp);
  625. }
  626. int modemSend(const void* buff, size_t len, uint8_t mux) {
  627. sendAT(GF("+CIPSEND="), mux, ',', len);
  628. if (waitResponse(GF(">")) != 1) {
  629. return -1;
  630. }
  631. stream.write((uint8_t*)buff, len);
  632. stream.flush();
  633. if (waitResponse(GF(GSM_NL "DATA ACCEPT:")) != 1) {
  634. return -1;
  635. }
  636. streamSkipUntil(','); // Skip mux
  637. return stream.readStringUntil('\n').toInt();
  638. }
  639. size_t modemRead(size_t size, uint8_t mux) {
  640. #ifdef TINY_GSM_USE_HEX
  641. sendAT(GF("+CIPRXGET=3,"), mux, ',', size);
  642. if (waitResponse(GF("+CIPRXGET:")) != 1) {
  643. return 0;
  644. }
  645. #else
  646. sendAT(GF("+CIPRXGET=2,"), mux, ',', size);
  647. if (waitResponse(GF("+CIPRXGET:")) != 1) {
  648. return 0;
  649. }
  650. #endif
  651. streamSkipUntil(','); // Skip mode 2/3
  652. streamSkipUntil(','); // Skip mux
  653. size_t len = stream.readStringUntil(',').toInt();
  654. sockets[mux]->sock_available = stream.readStringUntil('\n').toInt();
  655. for (size_t i=0; i<len; i++) {
  656. #ifdef TINY_GSM_USE_HEX
  657. while (stream.available() < 2) { TINY_GSM_YIELD(); }
  658. char buf[4] = { 0, };
  659. buf[0] = stream.read();
  660. buf[1] = stream.read();
  661. char c = strtol(buf, NULL, 16);
  662. #else
  663. while (!stream.available()) { TINY_GSM_YIELD(); }
  664. char c = stream.read();
  665. #endif
  666. sockets[mux]->rx.put(c);
  667. }
  668. waitResponse();
  669. return len;
  670. }
  671. size_t modemGetAvailable(uint8_t mux) {
  672. sendAT(GF("+CIPRXGET=4,"), mux);
  673. size_t result = 0;
  674. if (waitResponse(GF("+CIPRXGET:")) == 1) {
  675. streamSkipUntil(','); // Skip mode 4
  676. streamSkipUntil(','); // Skip mux
  677. result = stream.readStringUntil('\n').toInt();
  678. waitResponse();
  679. }
  680. if (!result) {
  681. sockets[mux]->sock_connected = modemGetConnected(mux);
  682. }
  683. return result;
  684. }
  685. bool modemGetConnected(uint8_t mux) {
  686. sendAT(GF("+CIPSTATUS="), mux);
  687. int res = waitResponse(GF(",\"CONNECTED\""), GF(",\"CLOSED\""), GF(",\"CLOSING\""), GF(",\"INITIAL\""));
  688. waitResponse();
  689. return 1 == res;
  690. }
  691. static String decodeHex8bit(String &instr) {
  692. String result;
  693. for (unsigned i=0; i<instr.length(); i+=2) {
  694. char buf[4] = { 0, };
  695. buf[0] = instr[i];
  696. buf[1] = instr[i+1];
  697. char b = strtol(buf, NULL, 16);
  698. result += b;
  699. }
  700. return result;
  701. }
  702. static String decodeHex16bit(String &instr) {
  703. String result;
  704. for (unsigned i=0; i<instr.length(); i+=4) {
  705. char buf[4] = { 0, };
  706. buf[0] = instr[i];
  707. buf[1] = instr[i+1];
  708. char b = strtol(buf, NULL, 16);
  709. if (b) { // If high byte is non-zero, we can't handle it ;(
  710. b = '?';
  711. } else {
  712. buf[0] = instr[i+2];
  713. buf[1] = instr[i+3];
  714. b = strtol(buf, NULL, 16);
  715. }
  716. result += b;
  717. }
  718. return result;
  719. }
  720. public:
  721. /* Utilities */
  722. template<typename T>
  723. void streamWrite(T last) {
  724. stream.print(last);
  725. }
  726. template<typename T, typename... Args>
  727. void streamWrite(T head, Args... tail) {
  728. stream.print(head);
  729. streamWrite(tail...);
  730. }
  731. bool streamSkipUntil(char c) { //TODO: timeout
  732. while (true) {
  733. while (!stream.available()) { TINY_GSM_YIELD(); }
  734. if (stream.read() == c)
  735. return true;
  736. }
  737. return false;
  738. }
  739. template<typename... Args>
  740. void sendAT(Args... cmd) {
  741. streamWrite("AT", cmd..., GSM_NL);
  742. stream.flush();
  743. TINY_GSM_YIELD();
  744. //DBG("### AT:", cmd...);
  745. }
  746. // TODO: Optimize this!
  747. uint8_t waitResponse(uint32_t timeout, String& data,
  748. GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  749. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  750. {
  751. /*String r1s(r1); r1s.trim();
  752. String r2s(r2); r2s.trim();
  753. String r3s(r3); r3s.trim();
  754. String r4s(r4); r4s.trim();
  755. String r5s(r5); r5s.trim();
  756. DBG("### ..:", r1s, ",", r2s, ",", r3s, ",", r4s, ",", r5s);*/
  757. data.reserve(64);
  758. int index = 0;
  759. unsigned long startMillis = millis();
  760. do {
  761. TINY_GSM_YIELD();
  762. while (stream.available() > 0) {
  763. int a = stream.read();
  764. if (a <= 0) continue; // Skip 0x00 bytes, just in case
  765. data += (char)a;
  766. if (r1 && data.endsWith(r1)) {
  767. index = 1;
  768. goto finish;
  769. } else if (r2 && data.endsWith(r2)) {
  770. index = 2;
  771. goto finish;
  772. } else if (r3 && data.endsWith(r3)) {
  773. index = 3;
  774. goto finish;
  775. } else if (r4 && data.endsWith(r4)) {
  776. index = 4;
  777. goto finish;
  778. } else if (r5 && data.endsWith(r5)) {
  779. index = 5;
  780. goto finish;
  781. } else if (data.endsWith(GF(GSM_NL "+CIPRXGET:"))) {
  782. String mode = stream.readStringUntil(',');
  783. if (mode.toInt() == 1) {
  784. int mux = stream.readStringUntil('\n').toInt();
  785. if (mux >= 0 && mux < TINY_GSM_MUX_COUNT && sockets[mux]) {
  786. sockets[mux]->got_data = true;
  787. }
  788. data = "";
  789. } else {
  790. data += mode;
  791. }
  792. } else if (data.endsWith(GF("CLOSED" GSM_NL))) {
  793. int nl = data.lastIndexOf(GSM_NL, data.length()-8);
  794. int coma = data.indexOf(',', nl+2);
  795. int mux = data.substring(nl+2, coma).toInt();
  796. if (mux >= 0 && mux < TINY_GSM_MUX_COUNT && sockets[mux]) {
  797. sockets[mux]->sock_connected = false;
  798. }
  799. data = "";
  800. DBG("### Closed: ", mux);
  801. }
  802. }
  803. } while (millis() - startMillis < timeout);
  804. finish:
  805. if (!index) {
  806. data.trim();
  807. if (data.length()) {
  808. DBG("### Unhandled:", data);
  809. }
  810. data = "";
  811. }
  812. return index;
  813. }
  814. uint8_t waitResponse(uint32_t timeout,
  815. GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  816. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  817. {
  818. String data;
  819. return waitResponse(timeout, data, r1, r2, r3, r4, r5);
  820. }
  821. uint8_t waitResponse(GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  822. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  823. {
  824. return waitResponse(1000, r1, r2, r3, r4, r5);
  825. }
  826. protected:
  827. Stream& stream;
  828. GsmClient* sockets[TINY_GSM_MUX_COUNT];
  829. };
  830. #endif