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.

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