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.

1085 lines
26 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. * GPS location functions
  617. */
  618. // enable GPS
  619. boolean enableGPS() {
  620. uint16_t state;
  621. sendAT(GF("+CGNSPWR=1"));
  622. if (waitResponse() != 1) {
  623. return false;
  624. }
  625. return true;
  626. }
  627. boolean disableGPS() {
  628. uint16_t state;
  629. sendAT(GF("+CGNSPWR=0"));
  630. if (waitResponse() != 1) {
  631. return false;
  632. }
  633. return true;
  634. }
  635. // get the RAW GPS output
  636. // works only with ans SIM808 V2
  637. String getGPSraw() {
  638. sendAT(GF("+CGNSINF"));
  639. if (waitResponse(GF(GSM_NL "+CGNSINF:")) != 1) {
  640. return "";
  641. }
  642. String res = stream.readStringUntil('\n');
  643. waitResponse();
  644. res.trim();
  645. return res;
  646. }
  647. // get GPS informations
  648. // works only with ans SIM808 V2
  649. boolean getGPS(float *lat, float *lon, float *speed=0, int *alt=0, int *vsat=0, int *usat=0) {
  650. //String buffer = "";
  651. char chr_buffer[12];
  652. boolean fix = false;
  653. sendAT(GF("+CGNSINF"));
  654. if (waitResponse(GF(GSM_NL "+CGNSINF:")) != 1) {
  655. return false;
  656. }
  657. stream.readStringUntil(','); // mode
  658. if ( stream.readStringUntil(',').toInt() == 1 ) fix = true;
  659. stream.readStringUntil(','); //utctime
  660. *lat = stream.readStringUntil(',').toFloat(); //lat
  661. *lon = stream.readStringUntil(',').toFloat(); //lon
  662. if (alt != NULL) *alt = stream.readStringUntil(',').toFloat(); //lon
  663. if (speed != NULL) *speed = stream.readStringUntil(',').toFloat(); //speed
  664. stream.readStringUntil(',');
  665. stream.readStringUntil(',');
  666. stream.readStringUntil(',');
  667. stream.readStringUntil(',');
  668. stream.readStringUntil(',');
  669. stream.readStringUntil(',');
  670. stream.readStringUntil(',');
  671. if (vsat != NULL) *vsat = stream.readStringUntil(',').toInt(); //viewed satelites
  672. if (usat != NULL) *usat = stream.readStringUntil(',').toInt(); //used satelites
  673. stream.readStringUntil('\n');
  674. waitResponse();
  675. return fix;
  676. }
  677. // get GPS time
  678. // works only with SIM808 V2
  679. boolean getGPSTime(int *year, int *month, int *day, int *hour, int *minute, int *second) {
  680. boolean fix = false;
  681. char chr_buffer[12];
  682. sendAT(GF("+CGNSINF"));
  683. if (waitResponse(GF(GSM_NL "+CGNSINF:")) != 1) {
  684. return false;
  685. }
  686. for (int i = 0; i < 3; i++) {
  687. String buffer = stream.readStringUntil(',');
  688. buffer.toCharArray(chr_buffer, sizeof(chr_buffer));
  689. switch (i) {
  690. case 0:
  691. //mode
  692. break;
  693. case 1:
  694. //fixstatus
  695. if ( buffer.toInt() == 1 ) {
  696. fix = buffer.toInt();
  697. }
  698. break;
  699. case 2:
  700. *year = buffer.substring(0,4).toInt();
  701. *month = buffer.substring(4,6).toInt();
  702. *day = buffer.substring(6,8).toInt();
  703. *hour = buffer.substring(8,10).toInt();
  704. *minute = buffer.substring(10,12).toInt();
  705. *second = buffer.substring(12,14).toInt();
  706. break;
  707. default:
  708. // if nothing else matches, do the default
  709. // default is optional
  710. break;
  711. }
  712. }
  713. String res = stream.readStringUntil('\n');
  714. waitResponse();
  715. if (fix) {
  716. return true;
  717. } else {
  718. return false;
  719. }
  720. }
  721. private:
  722. bool modemConnect(const char* host, uint16_t port, uint8_t mux) {
  723. sendAT(GF("+CIPSTART="), mux, ',', GF("\"TCP"), GF("\",\""), host, GF("\","), port);
  724. int rsp = waitResponse(75000L,
  725. GF("CONNECT OK" GSM_NL),
  726. GF("CONNECT FAIL" GSM_NL),
  727. GF("ALREADY CONNECT" GSM_NL));
  728. return (1 == rsp);
  729. }
  730. int modemSend(const void* buff, size_t len, uint8_t mux) {
  731. sendAT(GF("+CIPSEND="), mux, ',', len);
  732. if (waitResponse(GF(">")) != 1) {
  733. return -1;
  734. }
  735. stream.write((uint8_t*)buff, len);
  736. stream.flush();
  737. if (waitResponse(GF(GSM_NL "DATA ACCEPT:")) != 1) {
  738. return -1;
  739. }
  740. streamSkipUntil(','); // Skip mux
  741. return stream.readStringUntil('\n').toInt();
  742. }
  743. size_t modemRead(size_t size, uint8_t mux) {
  744. #ifdef TINY_GSM_USE_HEX
  745. sendAT(GF("+CIPRXGET=3,"), mux, ',', size);
  746. if (waitResponse(GF("+CIPRXGET:")) != 1) {
  747. return 0;
  748. }
  749. #else
  750. sendAT(GF("+CIPRXGET=2,"), mux, ',', size);
  751. if (waitResponse(GF("+CIPRXGET:")) != 1) {
  752. return 0;
  753. }
  754. #endif
  755. streamSkipUntil(','); // Skip mode 2/3
  756. streamSkipUntil(','); // Skip mux
  757. size_t len = stream.readStringUntil(',').toInt();
  758. sockets[mux]->sock_available = stream.readStringUntil('\n').toInt();
  759. for (size_t i=0; i<len; i++) {
  760. #ifdef TINY_GSM_USE_HEX
  761. while (stream.available() < 2) { TINY_GSM_YIELD(); }
  762. char buf[4] = { 0, };
  763. buf[0] = stream.read();
  764. buf[1] = stream.read();
  765. char c = strtol(buf, NULL, 16);
  766. #else
  767. while (!stream.available()) { TINY_GSM_YIELD(); }
  768. char c = stream.read();
  769. #endif
  770. sockets[mux]->rx.put(c);
  771. }
  772. waitResponse();
  773. return len;
  774. }
  775. size_t modemGetAvailable(uint8_t mux) {
  776. sendAT(GF("+CIPRXGET=4,"), mux);
  777. size_t result = 0;
  778. if (waitResponse(GF("+CIPRXGET:")) == 1) {
  779. streamSkipUntil(','); // Skip mode 4
  780. streamSkipUntil(','); // Skip mux
  781. result = stream.readStringUntil('\n').toInt();
  782. waitResponse();
  783. }
  784. if (!result) {
  785. sockets[mux]->sock_connected = modemGetConnected(mux);
  786. }
  787. return result;
  788. }
  789. bool modemGetConnected(uint8_t mux) {
  790. sendAT(GF("+CIPSTATUS="), mux);
  791. int res = waitResponse(GF(",\"CONNECTED\""), GF(",\"CLOSED\""), GF(",\"CLOSING\""), GF(",\"INITIAL\""));
  792. waitResponse();
  793. return 1 == res;
  794. }
  795. static String decodeHex8bit(String &instr) {
  796. String result;
  797. for (unsigned i=0; i<instr.length(); i+=2) {
  798. char buf[4] = { 0, };
  799. buf[0] = instr[i];
  800. buf[1] = instr[i+1];
  801. char b = strtol(buf, NULL, 16);
  802. result += b;
  803. }
  804. return result;
  805. }
  806. static String decodeHex16bit(String &instr) {
  807. String result;
  808. for (unsigned i=0; i<instr.length(); i+=4) {
  809. char buf[4] = { 0, };
  810. buf[0] = instr[i];
  811. buf[1] = instr[i+1];
  812. char b = strtol(buf, NULL, 16);
  813. if (b) { // If high byte is non-zero, we can't handle it ;(
  814. b = '?';
  815. } else {
  816. buf[0] = instr[i+2];
  817. buf[1] = instr[i+3];
  818. b = strtol(buf, NULL, 16);
  819. }
  820. result += b;
  821. }
  822. return result;
  823. }
  824. public:
  825. /* Utilities */
  826. template<typename T>
  827. void streamWrite(T last) {
  828. stream.print(last);
  829. }
  830. template<typename T, typename... Args>
  831. void streamWrite(T head, Args... tail) {
  832. stream.print(head);
  833. streamWrite(tail...);
  834. }
  835. bool streamSkipUntil(char c) { //TODO: timeout
  836. while (true) {
  837. while (!stream.available()) { TINY_GSM_YIELD(); }
  838. if (stream.read() == c)
  839. return true;
  840. }
  841. return false;
  842. }
  843. template<typename... Args>
  844. void sendAT(Args... cmd) {
  845. streamWrite("AT", cmd..., GSM_NL);
  846. stream.flush();
  847. TINY_GSM_YIELD();
  848. //DBG("### AT:", cmd...);
  849. }
  850. // TODO: Optimize this!
  851. uint8_t waitResponse(uint32_t timeout, String& data,
  852. GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  853. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  854. {
  855. /*String r1s(r1); r1s.trim();
  856. String r2s(r2); r2s.trim();
  857. String r3s(r3); r3s.trim();
  858. String r4s(r4); r4s.trim();
  859. String r5s(r5); r5s.trim();
  860. DBG("### ..:", r1s, ",", r2s, ",", r3s, ",", r4s, ",", r5s);*/
  861. data.reserve(64);
  862. int index = 0;
  863. unsigned long startMillis = millis();
  864. do {
  865. TINY_GSM_YIELD();
  866. while (stream.available() > 0) {
  867. int a = stream.read();
  868. if (a <= 0) continue; // Skip 0x00 bytes, just in case
  869. data += (char)a;
  870. if (r1 && data.endsWith(r1)) {
  871. index = 1;
  872. goto finish;
  873. } else if (r2 && data.endsWith(r2)) {
  874. index = 2;
  875. goto finish;
  876. } else if (r3 && data.endsWith(r3)) {
  877. index = 3;
  878. goto finish;
  879. } else if (r4 && data.endsWith(r4)) {
  880. index = 4;
  881. goto finish;
  882. } else if (r5 && data.endsWith(r5)) {
  883. index = 5;
  884. goto finish;
  885. } else if (data.endsWith(GF(GSM_NL "+CIPRXGET:"))) {
  886. String mode = stream.readStringUntil(',');
  887. if (mode.toInt() == 1) {
  888. int mux = stream.readStringUntil('\n').toInt();
  889. if (mux >= 0 && mux < TINY_GSM_MUX_COUNT) {
  890. sockets[mux]->got_data = true;
  891. }
  892. data = "";
  893. } else {
  894. data += mode;
  895. }
  896. } else if (data.endsWith(GF("CLOSED" GSM_NL))) {
  897. int nl = data.lastIndexOf(GSM_NL, data.length()-8);
  898. int coma = data.indexOf(',', nl+2);
  899. int mux = data.substring(nl+2, coma).toInt();
  900. if (mux >= 0 && mux < TINY_GSM_MUX_COUNT) {
  901. sockets[mux]->sock_connected = false;
  902. }
  903. data = "";
  904. DBG("### Closed: ", mux);
  905. }
  906. }
  907. } while (millis() - startMillis < timeout);
  908. finish:
  909. if (!index) {
  910. data.trim();
  911. if (data.length()) {
  912. DBG("### Unhandled:", data);
  913. }
  914. data = "";
  915. }
  916. return index;
  917. }
  918. uint8_t waitResponse(uint32_t timeout,
  919. GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  920. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  921. {
  922. String data;
  923. return waitResponse(timeout, data, r1, r2, r3, r4, r5);
  924. }
  925. uint8_t waitResponse(GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  926. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  927. {
  928. return waitResponse(1000, r1, r2, r3, r4, r5);
  929. }
  930. private:
  931. Stream& stream;
  932. GsmClient* sockets[TINY_GSM_MUX_COUNT];
  933. };
  934. typedef TinyGsm::GsmClient TinyGsmClient;
  935. #endif