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.

1023 lines
24 KiB

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