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.

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