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.

852 lines
22 KiB

5 years ago
5 years ago
  1. /**
  2. * @file TinyGsmClientSIM7600.h
  3. * @author Volodymyr Shymanskyy
  4. * @license LGPL-3.0
  5. * @copyright Copyright (c) 2016 Volodymyr Shymanskyy
  6. * @date Nov 2016
  7. */
  8. #ifndef TinyGsmClientSIM7600_h
  9. #define TinyGsmClientSIM7600_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 10
  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 TinyGsmSim7600: public TinyGsmUTFSMS<TinyGsmSim7600>
  39. {
  40. public:
  41. class GsmClient : public Client
  42. {
  43. friend class TinyGsmSim7600;
  44. typedef TinyGsmFifo<uint8_t, TINY_GSM_RX_BUFFER> RxFifo;
  45. public:
  46. GsmClient() {}
  47. GsmClient(TinyGsmSim7600& modem, uint8_t mux = 0) {
  48. init(&modem, mux);
  49. }
  50. virtual ~GsmClient(){}
  51. bool init(TinyGsmSim7600* modem, uint8_t mux = 0) {
  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. TinyGsmSim7600* 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. public:
  95. TinyGsmSim7600(Stream& stream)
  96. : stream(stream)
  97. {
  98. memset(sockets, 0, sizeof(sockets));
  99. }
  100. /*
  101. * Basic functions
  102. */
  103. bool begin(const char* pin = NULL) {
  104. return init(pin);
  105. }
  106. bool init(const char* pin = NULL) {
  107. DBG(GF("### TinyGSM Version:"), TINYGSM_VERSION);
  108. if (!testAT()) {
  109. return false;
  110. }
  111. sendAT(GF("E0")); // Echo Off
  112. if (waitResponse() != 1) {
  113. return false;
  114. }
  115. DBG(GF("### Modem:"), getModemName());
  116. int ret = getSimStatus();
  117. // if the sim isn't ready and a pin has been provided, try to unlock the sim
  118. if (ret != SIM_READY && pin != NULL && strlen(pin) > 0) {
  119. simUnlock(pin);
  120. return (getSimStatus() == SIM_READY);
  121. }
  122. // if the sim is ready, or it's locked but no pin has been provided, return
  123. // true
  124. else {
  125. return (ret == SIM_READY || ret == SIM_LOCKED);
  126. }
  127. }
  128. String getModemName() {
  129. String name = "SIMCom SIM7600";
  130. sendAT(GF("+CGMM"));
  131. String res2;
  132. if (waitResponse(1000L, res2) != 1) {
  133. return name;
  134. }
  135. res2.replace(GSM_NL "OK" GSM_NL, "");
  136. res2.replace("_", " ");
  137. res2.trim();
  138. name = res2;
  139. DBG("### Modem:", name);
  140. return name;
  141. }
  142. TINY_GSM_MODEM_SET_BAUD_IPR()
  143. TINY_GSM_MODEM_TEST_AT()
  144. TINY_GSM_MODEM_MAINTAIN_CHECK_SOCKS()
  145. bool factoryDefault() { // these commands aren't supported
  146. return false;
  147. }
  148. TINY_GSM_MODEM_GET_INFO_ATI()
  149. bool hasSSL() {
  150. return false; // TODO: Module supports SSL, but not yet implemented
  151. }
  152. bool hasWifi() {
  153. return false;
  154. }
  155. bool hasGPRS() {
  156. return true;
  157. }
  158. /*
  159. * Power functions
  160. */
  161. bool restart() {
  162. if (!testAT()) {
  163. return false;
  164. }
  165. sendAT(GF("+CRESET"));
  166. if (waitResponse(10000L) != 1) {
  167. return false;
  168. }
  169. delay(5000L); // TODO: Test this delay!
  170. return init();
  171. }
  172. bool poweroff() {
  173. sendAT(GF("+CPOF"));
  174. return waitResponse() == 1;
  175. }
  176. bool radioOff() {
  177. sendAT(GF("+CFUN=4"));
  178. if (waitResponse(10000L) != 1) {
  179. return false;
  180. }
  181. delay(3000);
  182. return true;
  183. }
  184. bool sleepEnable(bool enable = true) {
  185. sendAT(GF("+CSCLK="), enable);
  186. return waitResponse() == 1;
  187. }
  188. /*
  189. * SIM card functions
  190. */
  191. TINY_GSM_MODEM_SIM_UNLOCK_CPIN()
  192. // Gets the CCID of a sim card via AT+CCID
  193. String getSimCCID() {
  194. sendAT(GF("+CICCID"));
  195. if (waitResponse(GF(GSM_NL "+ICCID:")) != 1) {
  196. return "";
  197. }
  198. String res = stream.readStringUntil('\n');
  199. waitResponse();
  200. res.trim();
  201. return res;
  202. }
  203. TINY_GSM_MODEM_GET_IMEI_GSN()
  204. SimStatus getSimStatus(unsigned long timeout_ms = 10000L) {
  205. for (unsigned long start = millis(); millis() - start < timeout_ms; ) {
  206. sendAT(GF("+CPIN?"));
  207. if (waitResponse(GF(GSM_NL "+CPIN:")) != 1) {
  208. delay(1000);
  209. continue;
  210. }
  211. int status = waitResponse(GF("READY"), GF("SIM PIN"), GF("SIM PUK"));
  212. waitResponse();
  213. switch (status) {
  214. case 2:
  215. case 3: return SIM_LOCKED;
  216. case 1: return SIM_READY;
  217. default: return SIM_ERROR;
  218. }
  219. }
  220. return SIM_ERROR;
  221. }
  222. TINY_GSM_MODEM_GET_REGISTRATION_XREG(CGREG)
  223. TINY_GSM_MODEM_GET_OPERATOR_COPS()
  224. /*
  225. * Generic network functions
  226. */
  227. TINY_GSM_MODEM_GET_CSQ()
  228. bool isNetworkConnected() {
  229. RegStatus s = getRegistrationStatus();
  230. return (s == REG_OK_HOME || s == REG_OK_ROAMING);
  231. }
  232. String getNetworkModes() {
  233. sendAT(GF("+CNMP=?"));
  234. if (waitResponse(GF(GSM_NL "+CNMP:")) != 1) {
  235. return "";
  236. }
  237. String res = stream.readStringUntil('\n');
  238. waitResponse();
  239. return res;
  240. }
  241. TINY_GSM_MODEM_WAIT_FOR_NETWORK()
  242. String setNetworkMode(uint8_t mode) {
  243. sendAT(GF("+CNMP="), mode);
  244. if (waitResponse(GF(GSM_NL "+CNMP:")) != 1) {
  245. return "OK";
  246. }
  247. String res = stream.readStringUntil('\n');
  248. waitResponse();
  249. return res;
  250. }
  251. /*
  252. * GPRS functions
  253. */
  254. bool gprsConnect(const char* apn, const char* user = NULL, const char* pwd = NULL) {
  255. gprsDisconnect(); // Make sure we're not connected first
  256. // Define the PDP context
  257. // The CGDCONT commands set up the "external" PDP context
  258. // Set the external authentication
  259. if (user && strlen(user) > 0) {
  260. sendAT(GF("+CGAUTH=1,0,\""), user, GF("\",\""), pwd, '"');
  261. waitResponse();
  262. }
  263. // Define external PDP context 1
  264. sendAT(GF("+CGDCONT=1,\"IP\",\""), apn, '"',",\"0.0.0.0\",0,0");
  265. waitResponse();
  266. // Configure TCP parameters
  267. // Select TCP/IP application mode (command mode)
  268. sendAT(GF("+CIPMODE=0"));
  269. waitResponse();
  270. // Set Sending Mode - send without waiting for peer TCP ACK
  271. sendAT(GF("+CIPSENDMODE=0"));
  272. waitResponse();
  273. // Configure socket parameters
  274. //AT+CIPCCFG= [<NmRetry>][,[<DelayTm>][,[<Ack>][,[<errMode>][,]<HeaderType>][,[[<AsyncMode>][,[<TimeoutVal>]]]]]]]]
  275. // NmRetry = number of retransmission to be made for an IP packet = 10 (default)
  276. // DelayTm = number of milliseconds to delay to output data of Receiving = 0 (default)
  277. // Ack = sets whether reporting a string “Send ok” = 0 (don't report)
  278. // errMode = mode of reporting error result code = 0 (numberic values)
  279. // HeaderType = which data header of receiving data in multi-client mode = 1 (“+RECEIVE,<link num>,<data length>”)
  280. // AsyncMode = sets mode of executing commands = 0 (synchronous command executing)
  281. // TimeoutVal = minimum retransmission timeout in milliseconds = 75000
  282. sendAT(GF("+CIPCCFG=10,0,0,0,1,0,75000"));
  283. if (waitResponse() != 1) {
  284. return false;
  285. }
  286. // Configure timeouts for opening and closing sockets
  287. // AT+CIPTIMEOUT=[<netopen_timeout>][, [<cipopen_timeout>][, [<cipsend_timeout>]]]
  288. sendAT(GF("+CIPTIMEOUT="), 75000, ',', 15000, ',', 15000);
  289. waitResponse();
  290. // Start the socket service
  291. // This activates and attaches to the external PDP context that is tied
  292. // to the embedded context for TCP/IP (ie AT+CGACT=1,1 and AT+CGATT=1)
  293. // Response may be an immediate "OK" followed later by "+NETOPEN: 0".
  294. // We to ignore any immediate response and wait for the
  295. // URC to show it's really connected.
  296. sendAT(GF("+NETOPEN"));
  297. if (waitResponse(75000L, GF(GSM_NL "+NETOPEN: 0")) != 1) {
  298. return false;
  299. }
  300. return true;
  301. }
  302. bool gprsDisconnect() {
  303. // Close all sockets and stop the socket service
  304. // Note: On the LTE models, this single command closes all sockets and the service
  305. sendAT(GF("+NETCLOSE"));
  306. if (waitResponse(60000L, GF(GSM_NL "+NETCLOSE: 0")) != 1) {
  307. return false;
  308. }
  309. return true;
  310. }
  311. bool isGprsConnected() {
  312. sendAT(GF("+NETOPEN?"));
  313. // May return +NETOPEN: 1, 0. We just confirm that the first number is 1
  314. if (waitResponse(GF(GSM_NL "+NETOPEN: 1")) != 1) {
  315. return false;
  316. }
  317. waitResponse();
  318. sendAT(GF("+IPADDR")); // Inquire Socket PDP address
  319. // sendAT(GF("+CGPADDR=1")); // Show PDP address
  320. if (waitResponse() != 1) {
  321. return false;
  322. }
  323. return true;
  324. }
  325. /*
  326. * IP Address functions
  327. */
  328. String getLocalIP() {
  329. sendAT(GF("+IPADDR")); // Inquire Socket PDP address
  330. // sendAT(GF("+CGPADDR=1")); // Show PDP address
  331. String res;
  332. if (waitResponse(10000L, res) != 1) {
  333. return "";
  334. }
  335. res.replace(GSM_NL "OK" GSM_NL, "");
  336. res.replace(GSM_NL, "");
  337. res.trim();
  338. return res;
  339. }
  340. IPAddress localIP() {
  341. return TinyGsmIpFromString(getLocalIP());
  342. }
  343. /*
  344. * Phone Call functions
  345. */
  346. bool setGsmBusy() TINY_GSM_ATTR_NOT_IMPLEMENTED;
  347. bool callAnswer() TINY_GSM_ATTR_NOT_IMPLEMENTED;
  348. bool callNumber() TINY_GSM_ATTR_NOT_IMPLEMENTED;
  349. bool callHangup() TINY_GSM_ATTR_NOT_IMPLEMENTED;
  350. bool dtmfSend() TINY_GSM_ATTR_NOT_IMPLEMENTED;
  351. /*
  352. * Messaging functions
  353. */
  354. String sendUSSD(const String& code) {
  355. // Select message format (1=text)
  356. sendAT(GF("+CMGF=1"));
  357. waitResponse();
  358. // Select TE character set
  359. sendAT(GF("+CSCS=\"HEX\""));
  360. waitResponse();
  361. sendAT(GF("+CUSD=1,\""), code, GF("\""));
  362. if (waitResponse() != 1) {
  363. return "";
  364. }
  365. if (waitResponse(10000L, GF(GSM_NL "+CUSD:")) != 1) {
  366. return "";
  367. }
  368. stream.readStringUntil('"');
  369. String hex = stream.readStringUntil('"');
  370. stream.readStringUntil(',');
  371. int dcs = stream.readStringUntil('\n').toInt();
  372. if (dcs == 15) {
  373. return TinyGsmDecodeHex8bit(hex);
  374. } else if (dcs == 72) {
  375. return TinyGsmDecodeHex16bit(hex);
  376. } else {
  377. return hex;
  378. }
  379. }
  380. bool sendSMS(const String& number, const String& text) {
  381. // Get SMS service centre address
  382. sendAT(GF("+AT+CSCA?"));
  383. waitResponse();
  384. // Select message format (1=text)
  385. sendAT(GF("+CMGF=1"));
  386. waitResponse();
  387. //Set GSM 7 bit default alphabet (3GPP TS 23.038)
  388. sendAT(GF("+CSCS=\"GSM\""));
  389. waitResponse();
  390. // Send the message!
  391. sendAT(GF("+CMGS=\""), number, GF("\""));
  392. if (waitResponse(GF(">")) != 1) {
  393. return false;
  394. }
  395. stream.print(text);
  396. stream.write((char)0x1A);
  397. stream.flush();
  398. return waitResponse(60000L) == 1;
  399. }
  400. /*
  401. * Location functions
  402. */
  403. String getGsmLocation() TINY_GSM_ATTR_NOT_IMPLEMENTED;
  404. /*
  405. * GPS location functions
  406. */
  407. // enable GPS
  408. bool enableGPS() {
  409. sendAT(GF("+CGPS=1"));
  410. if (waitResponse() != 1) {
  411. return false;
  412. }
  413. return true;
  414. }
  415. bool disableGPS() {
  416. sendAT(GF("+CGPS=0"));
  417. if (waitResponse() != 1) {
  418. return false;
  419. }
  420. return true;
  421. }
  422. // get the RAW GPS output
  423. String getGPSraw() {
  424. sendAT(GF("+CGNSSINFO=32"));
  425. if (waitResponse(GF(GSM_NL "+CGNSSINFO:")) != 1) {
  426. return "";
  427. }
  428. String res = stream.readStringUntil('\n');
  429. waitResponse();
  430. res.trim();
  431. return res;
  432. }
  433. // get GPS informations
  434. bool getGPS(float *lat, float *lon, float *speed=0, int *alt=0) {
  435. //String buffer = "";
  436. bool fix = false;
  437. sendAT(GF("+CGNSSINFO"));
  438. if (waitResponse(GF(GSM_NL "+CGNSSINFO:")) != 1) {
  439. return false;
  440. }
  441. //stream.readStringUntil(','); // mode
  442. if ( stream.readStringUntil(',').toInt() == 1 ) fix = true;
  443. stream.readStringUntil(','); //gps
  444. stream.readStringUntil(','); // glonass
  445. stream.readStringUntil(','); // beidu
  446. *lat = stream.readStringUntil(',').toFloat(); //lat
  447. stream.readStringUntil(','); // N/S
  448. *lon = stream.readStringUntil(',').toFloat(); //lon
  449. stream.readStringUntil(','); // E/W
  450. stream.readStringUntil(','); // date
  451. stream.readStringUntil(','); // UTC time
  452. if (alt != NULL) *alt = stream.readStringUntil(',').toFloat(); //alt
  453. if (speed != NULL) *speed = stream.readStringUntil(',').toFloat(); //speed
  454. stream.readStringUntil(','); //course
  455. stream.readStringUntil(','); //time
  456. stream.readStringUntil(',');//PDOP
  457. stream.readStringUntil(',');//HDOP
  458. stream.readStringUntil(',');//VDOP
  459. stream.readStringUntil('\n');
  460. waitResponse();
  461. return fix;
  462. }
  463. /*
  464. * Time functions
  465. */
  466. /*
  467. * Battery & temperature functions
  468. */
  469. // Use: float vBatt = modem.getBattVoltage() / 1000.0;
  470. uint16_t getBattVoltage() {
  471. sendAT(GF("+CBC"));
  472. if (waitResponse(GF(GSM_NL "+CBC:")) != 1) {
  473. return 0;
  474. }
  475. // get voltage in VOLTS
  476. float voltage = stream.readStringUntil('\n').toFloat();
  477. // Wait for final OK
  478. waitResponse();
  479. // Return millivolts
  480. uint16_t res = voltage*1000;
  481. return res;
  482. }
  483. int8_t getBattPercent() TINY_GSM_ATTR_NOT_AVAILABLE;
  484. uint8_t getBattChargeState() TINY_GSM_ATTR_NOT_AVAILABLE;
  485. bool getBattStats(uint8_t& chargeState, int8_t& percent,
  486. uint16_t& milliVolts) {
  487. chargeState = 0;
  488. percent = 0;
  489. milliVolts = getBattVoltage();
  490. return true;
  491. }
  492. // get temperature in degree celsius
  493. uint16_t getTemperature() {
  494. sendAT(GF("+CPMUTEMP"));
  495. if (waitResponse(GF(GSM_NL "+CPMUTEMP:")) != 1) {
  496. return 0;
  497. }
  498. // return temperature in C
  499. uint16_t res = stream.readStringUntil('\n').toInt();
  500. // Wait for final OK
  501. waitResponse();
  502. return res;
  503. }
  504. /*
  505. * Client related functions
  506. */
  507. protected:
  508. bool modemConnect(const char* host, uint16_t port, uint8_t mux,
  509. bool ssl = false, int timeout_s = 15) {
  510. if (ssl) {
  511. DBG("SSL not yet supported on this module!");
  512. }
  513. // Make sure we'll be getting data manually on this connection
  514. sendAT(GF("+CIPRXGET=1"));
  515. if (waitResponse() != 1) {
  516. return false;
  517. }
  518. // Establish a connection in multi-socket mode
  519. uint32_t timeout_ms = ((uint32_t)timeout_s) * 1000;
  520. sendAT(GF("+CIPOPEN="), mux, ',', GF("\"TCP"), GF("\",\""), host, GF("\","),
  521. port);
  522. // The reply is +CIPOPEN: ## of socket created
  523. if (waitResponse(timeout_ms, GF(GSM_NL "+CIPOPEN:")) != 1) {
  524. return false;
  525. }
  526. return true;
  527. }
  528. int16_t modemSend(const void* buff, size_t len, uint8_t mux) {
  529. sendAT(GF("+CIPSEND="), mux, ',', (uint16_t)len);
  530. if (waitResponse(GF(">")) != 1) {
  531. return 0;
  532. }
  533. stream.write((uint8_t*)buff, len);
  534. stream.flush();
  535. if (waitResponse(GF(GSM_NL "+CIPSEND:")) != 1) {
  536. return 0;
  537. }
  538. streamSkipUntil(','); // Skip mux
  539. streamSkipUntil(','); // Skip requested bytes to send
  540. // TODO: make sure requested and confirmed bytes match
  541. return stream.readStringUntil('\n').toInt();
  542. }
  543. size_t modemRead(size_t size, uint8_t mux) {
  544. #ifdef TINY_GSM_USE_HEX
  545. sendAT(GF("+CIPRXGET=3,"), mux, ',', (uint16_t)size);
  546. if (waitResponse(GF("+CIPRXGET:")) != 1) {
  547. return 0;
  548. }
  549. #else
  550. sendAT(GF("+CIPRXGET=2,"), mux, ',', (uint16_t)size);
  551. if (waitResponse(GF("+CIPRXGET:")) != 1) {
  552. return 0;
  553. }
  554. #endif
  555. streamSkipUntil(','); // Skip Rx mode 2/normal or 3/HEX
  556. streamSkipUntil(','); // Skip mux/cid (connecion id)
  557. int len_requested = stream.readStringUntil(',').toInt();
  558. // ^^ Requested number of data bytes (1-1460 bytes)to be read
  559. int len_confirmed = stream.readStringUntil('\n').toInt();
  560. // ^^ The data length which not read in the buffer
  561. for (int i=0; i<len_requested; i++) {
  562. uint32_t startMillis = millis();
  563. #ifdef TINY_GSM_USE_HEX
  564. while (stream.available() < 2 && (millis() - startMillis < sockets[mux]->_timeout)) { TINY_GSM_YIELD(); }
  565. char buf[4] = { 0, };
  566. buf[0] = stream.read();
  567. buf[1] = stream.read();
  568. char c = strtol(buf, NULL, 16);
  569. #else
  570. while (!stream.available() && (millis() - startMillis < sockets[mux]->_timeout)) { TINY_GSM_YIELD(); }
  571. char c = stream.read();
  572. #endif
  573. sockets[mux]->rx.put(c);
  574. }
  575. DBG("### READ:", len_requested, "from", mux);
  576. // sockets[mux]->sock_available = modemGetAvailable(mux);
  577. sockets[mux]->sock_available = len_confirmed;
  578. waitResponse();
  579. return len_requested;
  580. }
  581. size_t modemGetAvailable(uint8_t mux) {
  582. sendAT(GF("+CIPRXGET=4,"), mux);
  583. size_t result = 0;
  584. if (waitResponse(GF("+CIPRXGET:")) == 1) {
  585. streamSkipUntil(','); // Skip mode 4
  586. streamSkipUntil(','); // Skip mux
  587. result = stream.readStringUntil('\n').toInt();
  588. waitResponse();
  589. }
  590. DBG("### Available:", result, "on", mux);
  591. if (!result) {
  592. sockets[mux]->sock_connected = modemGetConnected(mux);
  593. }
  594. return result;
  595. }
  596. bool modemGetConnected(uint8_t mux) {
  597. // Read the status of all sockets at once
  598. sendAT(GF("+CIPCLOSE?"));
  599. if (waitResponse(GF("+CIPCLOSE:")) != 1) {
  600. // return false; // TODO: Why does this not read correctly?
  601. }
  602. for (int muxNo = 0; muxNo <= TINY_GSM_MUX_COUNT; muxNo++) {
  603. // +CIPCLOSE:<link0_state>,<link1_state>,...,<link9_state>
  604. sockets[muxNo]->sock_connected = stream.parseInt();
  605. }
  606. waitResponse(); // Should be an OK at the end
  607. return sockets[mux]->sock_connected;
  608. }
  609. public:
  610. /*
  611. Utilities
  612. */
  613. TINY_GSM_MODEM_STREAM_UTILITIES()
  614. // TODO: Optimize this!
  615. uint8_t waitResponse(uint32_t timeout_ms, String& data,
  616. GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  617. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  618. {
  619. /*String r1s(r1); r1s.trim();
  620. String r2s(r2); r2s.trim();
  621. String r3s(r3); r3s.trim();
  622. String r4s(r4); r4s.trim();
  623. String r5s(r5); r5s.trim();
  624. DBG("### ..:", r1s, ",", r2s, ",", r3s, ",", r4s, ",", r5s);*/
  625. data.reserve(64);
  626. int index = 0;
  627. unsigned long startMillis = millis();
  628. do {
  629. TINY_GSM_YIELD();
  630. while (stream.available() > 0) {
  631. TINY_GSM_YIELD();
  632. int a = stream.read();
  633. if (a <= 0) continue; // Skip 0x00 bytes, just in case
  634. data += (char)a;
  635. if (r1 && data.endsWith(r1)) {
  636. index = 1;
  637. goto finish;
  638. } else if (r2 && data.endsWith(r2)) {
  639. index = 2;
  640. goto finish;
  641. } else if (r3 && data.endsWith(r3)) {
  642. index = 3;
  643. goto finish;
  644. } else if (r4 && data.endsWith(r4)) {
  645. index = 4;
  646. goto finish;
  647. } else if (r5 && data.endsWith(r5)) {
  648. index = 5;
  649. goto finish;
  650. } else if (data.endsWith(GF(GSM_NL "+CIPRXGET:"))) {
  651. String mode = stream.readStringUntil(',');
  652. if (mode.toInt() == 1) {
  653. int mux = stream.readStringUntil('\n').toInt();
  654. if (mux >= 0 && mux < TINY_GSM_MUX_COUNT && sockets[mux]) {
  655. sockets[mux]->got_data = true;
  656. }
  657. data = "";
  658. DBG("### Got Data:", mux);
  659. } else {
  660. data += mode;
  661. }
  662. } else if (data.endsWith(GF(GSM_NL "+RECEIVE:"))) {
  663. int mux = stream.readStringUntil(',').toInt();
  664. int len = stream.readStringUntil('\n').toInt();
  665. if (mux >= 0 && mux < TINY_GSM_MUX_COUNT && sockets[mux]) {
  666. sockets[mux]->got_data = true;
  667. sockets[mux]->sock_available = len;
  668. }
  669. data = "";
  670. DBG("### Got Data:", len, "on", mux);
  671. } else if (data.endsWith(GF("+IPCLOSE:"))) {
  672. int mux = stream.readStringUntil(',').toInt();
  673. streamSkipUntil('\n'); // Skip the reason code
  674. if (mux >= 0 && mux < TINY_GSM_MUX_COUNT && sockets[mux]) {
  675. sockets[mux]->sock_connected = false;
  676. }
  677. data = "";
  678. DBG("### Closed: ", mux);
  679. } else if (data.endsWith(GF("+CIPEVENT:"))) {
  680. // Need to close all open sockets and release the network library.
  681. // User will then need to reconnect.
  682. DBG("### Network error!");
  683. if (!isGprsConnected()) {
  684. gprsDisconnect();
  685. }
  686. data = "";
  687. }
  688. }
  689. } while (millis() - startMillis < timeout_ms);
  690. finish:
  691. if (!index) {
  692. data.trim();
  693. if (data.length()) {
  694. DBG("### Unhandled:", data);
  695. }
  696. data = "";
  697. }
  698. //data.replace(GSM_NL, "/");
  699. //DBG('<', index, '>', data);
  700. return index;
  701. }
  702. uint8_t waitResponse(uint32_t timeout_ms,
  703. GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  704. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  705. {
  706. String data;
  707. return waitResponse(timeout_ms, data, r1, r2, r3, r4, r5);
  708. }
  709. uint8_t waitResponse(GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  710. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  711. {
  712. return waitResponse(1000, r1, r2, r3, r4, r5);
  713. }
  714. public:
  715. Stream& stream;
  716. protected:
  717. GsmClient* sockets[TINY_GSM_MUX_COUNT];
  718. };
  719. #endif