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.

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