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.

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