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.

964 lines
22 KiB

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