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.

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