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.

741 lines
17 KiB

8 years ago
8 years ago
7 years ago
7 years ago
  1. /**
  2. * @file TinyGsmClientA6.h
  3. * @author Volodymyr Shymanskyy
  4. * @license LGPL-3.0
  5. * @copyright Copyright (c) 2016 Volodymyr Shymanskyy
  6. * @date Nov 2016
  7. */
  8. #ifndef TinyGsmClientA6_h
  9. #define TinyGsmClientA6_h
  10. //#define TINY_GSM_DEBUG Serial
  11. #if !defined(TINY_GSM_RX_BUFFER)
  12. #define TINY_GSM_RX_BUFFER 256
  13. #endif
  14. #define TINY_GSM_MUX_COUNT 8
  15. #include <TinyGsmCommon.h>
  16. #define GSM_NL "\r\n"
  17. static const char GSM_OK[] TINY_GSM_PROGMEM = "OK" GSM_NL;
  18. static const char GSM_ERROR[] TINY_GSM_PROGMEM = "ERROR" GSM_NL;
  19. enum SimStatus {
  20. SIM_ERROR = 0,
  21. SIM_READY = 1,
  22. SIM_LOCKED = 2,
  23. };
  24. enum RegStatus {
  25. REG_UNREGISTERED = 0,
  26. REG_SEARCHING = 2,
  27. REG_DENIED = 3,
  28. REG_OK_HOME = 1,
  29. REG_OK_ROAMING = 5,
  30. REG_UNKNOWN = 4,
  31. };
  32. class TinyGsm
  33. {
  34. public:
  35. class GsmClient : public Client
  36. {
  37. friend class TinyGsm;
  38. typedef TinyGsmFifo<uint8_t, TINY_GSM_RX_BUFFER> RxFifo;
  39. public:
  40. GsmClient() {}
  41. GsmClient(TinyGsm& modem) {
  42. init(&modem);
  43. }
  44. bool init(TinyGsm* modem) {
  45. this->at = modem;
  46. this->mux = -1;
  47. sock_connected = false;
  48. return true;
  49. }
  50. public:
  51. virtual int connect(const char *host, uint16_t port) {
  52. TINY_GSM_YIELD();
  53. rx.clear();
  54. uint8_t newMux = -1;
  55. sock_connected = at->modemConnect(host, port, &newMux);
  56. if (sock_connected) {
  57. mux = newMux;
  58. at->sockets[mux] = this;
  59. }
  60. return sock_connected;
  61. }
  62. virtual int connect(IPAddress ip, uint16_t port) {
  63. String host; host.reserve(16);
  64. host += ip[0];
  65. host += ".";
  66. host += ip[1];
  67. host += ".";
  68. host += ip[2];
  69. host += ".";
  70. host += ip[3];
  71. return connect(host.c_str(), port);
  72. }
  73. virtual void stop() {
  74. TINY_GSM_YIELD();
  75. at->sendAT(GF("+CIPCLOSE="), mux);
  76. sock_connected = false;
  77. at->waitResponse();
  78. }
  79. virtual size_t write(const uint8_t *buf, size_t size) {
  80. TINY_GSM_YIELD();
  81. //at->maintain();
  82. return at->modemSend(buf, size, mux);
  83. }
  84. virtual size_t write(uint8_t c) {
  85. return write(&c, 1);
  86. }
  87. virtual int available() {
  88. TINY_GSM_YIELD();
  89. if (!rx.size() && sock_connected) {
  90. at->maintain();
  91. }
  92. return rx.size();
  93. }
  94. virtual int read(uint8_t *buf, size_t size) {
  95. TINY_GSM_YIELD();
  96. size_t cnt = 0;
  97. while (cnt < size) {
  98. size_t chunk = TinyGsmMin(size-cnt, rx.size());
  99. if (chunk > 0) {
  100. rx.get(buf, chunk);
  101. buf += chunk;
  102. cnt += chunk;
  103. continue;
  104. }
  105. // TODO: Read directly into user buffer?
  106. if (!rx.size()) {
  107. at->maintain();
  108. //break;
  109. }
  110. }
  111. return cnt;
  112. }
  113. virtual int read() {
  114. uint8_t c;
  115. if (read(&c, 1) == 1) {
  116. return c;
  117. }
  118. return -1;
  119. }
  120. virtual int peek() { return -1; } //TODO
  121. virtual void flush() { at->stream.flush(); }
  122. virtual uint8_t connected() {
  123. if (available()) {
  124. return true;
  125. }
  126. return sock_connected;
  127. }
  128. virtual operator bool() { return connected(); }
  129. /*
  130. * Extended API
  131. */
  132. String remoteIP() TINY_GSM_ATTR_NOT_IMPLEMENTED;
  133. private:
  134. TinyGsm* at;
  135. uint8_t mux;
  136. bool sock_connected;
  137. RxFifo rx;
  138. };
  139. public:
  140. TinyGsm(Stream& stream)
  141. : stream(stream)
  142. {
  143. memset(sockets, 0, sizeof(sockets));
  144. }
  145. /*
  146. * Basic functions
  147. */
  148. bool begin() {
  149. return init();
  150. }
  151. bool init() {
  152. if (!testAT()) {
  153. return false;
  154. }
  155. sendAT(GF("&FZE0")); // Factory + Reset + Echo Off
  156. if (waitResponse() != 1) {
  157. return false;
  158. }
  159. sendAT(GF("+CMEE=0"));
  160. waitResponse();
  161. getSimStatus();
  162. return true;
  163. }
  164. void setBaud(unsigned long baud) {
  165. sendAT(GF("+IPR="), baud);
  166. }
  167. bool testAT(unsigned long timeout = 10000L) {
  168. for (unsigned long start = millis(); millis() - start < timeout; ) {
  169. sendAT(GF(""));
  170. if (waitResponse(200) == 1) {
  171. delay(100);
  172. return true;
  173. }
  174. delay(100);
  175. }
  176. return false;
  177. }
  178. void maintain() {
  179. //while (stream.available()) {
  180. waitResponse(10, NULL, NULL);
  181. //}
  182. }
  183. bool factoryDefault() {
  184. sendAT(GF("&FZE0&W")); // Factory + Reset + Echo Off + Write
  185. waitResponse();
  186. sendAT(GF("&W")); // Write configuration
  187. return waitResponse() == 1;
  188. }
  189. String getModemInfo() {
  190. sendAT(GF("I"));
  191. String res;
  192. if (waitResponse(1000L, res) != 1) {
  193. return "";
  194. }
  195. res.replace(GSM_NL "OK" GSM_NL, "");
  196. res.replace(GSM_NL, " ");
  197. res.trim();
  198. return res;
  199. }
  200. /*
  201. * Power functions
  202. */
  203. bool restart() {
  204. if (!testAT()) {
  205. return false;
  206. }
  207. sendAT(GF("+RST=1"));
  208. delay(3000);
  209. return init();
  210. }
  211. bool poweroff() {
  212. sendAT(GF("+CPOF"));
  213. return waitResponse() == 1;
  214. }
  215. bool radioOff() TINY_GSM_ATTR_NOT_IMPLEMENTED;
  216. bool sleepEnable(bool enable = true) TINY_GSM_ATTR_NOT_IMPLEMENTED;
  217. /*
  218. * SIM card functions
  219. */
  220. bool simUnlock(const char *pin) {
  221. sendAT(GF("+CPIN=\""), pin, GF("\""));
  222. return waitResponse() == 1;
  223. }
  224. String getSimCCID() {
  225. sendAT(GF("+CCID"));
  226. if (waitResponse(GF(GSM_NL "+SCID: SIM Card ID:")) != 1) {
  227. return "";
  228. }
  229. String res = stream.readStringUntil('\n');
  230. waitResponse();
  231. res.trim();
  232. return res;
  233. }
  234. String getIMEI() {
  235. sendAT(GF("+GSN"));
  236. if (waitResponse(GF(GSM_NL)) != 1) {
  237. return "";
  238. }
  239. String res = stream.readStringUntil('\n');
  240. waitResponse();
  241. res.trim();
  242. return res;
  243. }
  244. SimStatus getSimStatus(unsigned long timeout = 10000L) {
  245. for (unsigned long start = millis(); millis() - start < timeout; ) {
  246. sendAT(GF("+CPIN?"));
  247. if (waitResponse(GF(GSM_NL "+CPIN:")) != 1) {
  248. delay(1000);
  249. continue;
  250. }
  251. int status = waitResponse(GF("READY"), GF("SIM PIN"), GF("SIM PUK"));
  252. waitResponse();
  253. switch (status) {
  254. case 2:
  255. case 3: return SIM_LOCKED;
  256. case 1: return SIM_READY;
  257. default: return SIM_ERROR;
  258. }
  259. }
  260. return SIM_ERROR;
  261. }
  262. RegStatus getRegistrationStatus() {
  263. sendAT(GF("+CREG?"));
  264. if (waitResponse(GF(GSM_NL "+CREG:")) != 1) {
  265. return REG_UNKNOWN;
  266. }
  267. streamSkipUntil(','); // Skip format (0)
  268. int status = stream.readStringUntil('\n').toInt();
  269. waitResponse();
  270. return (RegStatus)status;
  271. }
  272. String getOperator() {
  273. sendAT(GF("+COPS=3,0")); // Set format
  274. waitResponse();
  275. sendAT(GF("+COPS?"));
  276. if (waitResponse(GF(GSM_NL "+COPS:")) != 1) {
  277. return "";
  278. }
  279. streamSkipUntil('"'); // Skip mode and format
  280. String res = stream.readStringUntil('"');
  281. waitResponse();
  282. return res;
  283. }
  284. /*
  285. * Generic network functions
  286. */
  287. int getSignalQuality() {
  288. sendAT(GF("+CSQ"));
  289. if (waitResponse(GF(GSM_NL "+CSQ:")) != 1) {
  290. return 99;
  291. }
  292. int res = stream.readStringUntil(',').toInt();
  293. waitResponse();
  294. return res;
  295. }
  296. bool isNetworkConnected() {
  297. RegStatus s = getRegistrationStatus();
  298. return (s == REG_OK_HOME || s == REG_OK_ROAMING);
  299. }
  300. bool waitForNetwork(unsigned long timeout = 60000L) {
  301. for (unsigned long start = millis(); millis() - start < timeout; ) {
  302. if (isNetworkConnected()) {
  303. return true;
  304. }
  305. delay(500);
  306. }
  307. return false;
  308. }
  309. /*
  310. * GPRS functions
  311. */
  312. bool gprsConnect(const char* apn, const char* user, const char* pwd) {
  313. gprsDisconnect();
  314. sendAT(GF("+CGATT=1"));
  315. if (waitResponse(60000L) != 1)
  316. return false;
  317. // TODO: wait AT+CGATT?
  318. sendAT(GF("+CGDCONT=1,\"IP\",\""), apn, '"');
  319. waitResponse();
  320. if (!user) user = "";
  321. if (!pwd) pwd = "";
  322. sendAT(GF("+CSTT=\""), apn, GF("\",\""), user, GF("\",\""), pwd, GF("\""));
  323. if (waitResponse(60000L) != 1) {
  324. return false;
  325. }
  326. sendAT(GF("+CGACT=1,1"));
  327. waitResponse(60000L);
  328. sendAT(GF("+CIPMUX=1"));
  329. if (waitResponse() != 1) {
  330. return false;
  331. }
  332. return true;
  333. }
  334. bool gprsDisconnect() {
  335. sendAT(GF("+CIPSHUT"));
  336. waitResponse(5000L);
  337. for (int i = 0; i<3; i++) {
  338. sendAT(GF("+CGATT=0"));
  339. if (waitResponse(5000L) == 1)
  340. return true;
  341. }
  342. return false;
  343. }
  344. bool isGprsConnected() {
  345. sendAT(GF("+CGATT?"));
  346. if (waitResponse(GF(GSM_NL "+CGATT:")) != 1) {
  347. return false;
  348. }
  349. int res = stream.readStringUntil('\n').toInt();
  350. waitResponse();
  351. return (res == 1);
  352. }
  353. String getLocalIP() {
  354. sendAT(GF("+CIFSR"));
  355. String res;
  356. if (waitResponse(10000L, res) != 1) {
  357. return "";
  358. }
  359. res.replace(GSM_NL "OK" GSM_NL, "");
  360. res.replace(GSM_NL, "");
  361. res.trim();
  362. return res;
  363. }
  364. IPAddress localIP() {
  365. return TinyGsmIpFromString(getLocalIP());
  366. }
  367. /*
  368. * Phone Call functions
  369. */
  370. bool setGsmBusy(bool busy = true) TINY_GSM_ATTR_NOT_AVAILABLE;
  371. bool callAnswer() {
  372. sendAT(GF("A"));
  373. return waitResponse() == 1;
  374. }
  375. // Returns true on pick-up, false on error/busy
  376. bool callNumber(const String& number) {
  377. sendAT(GF("D\""), number, "\";");
  378. if (waitResponse() != 1) {
  379. return false;
  380. }
  381. if (waitResponse(60000L, GF(GSM_NL "+CIEV: \"CALL\",1"), GF(GSM_NL "+CIEV: \"CALL\",0")) != 1) {
  382. return false;
  383. }
  384. int rsp = waitResponse(60000L, GF(GSM_NL "+CIEV: \"SOUNDER\",0"), GF(GSM_NL "+CIEV: \"CALL\",0"));
  385. int rsp2 = waitResponse(300L, GF(GSM_NL "BUSY" GSM_NL), GF(GSM_NL "NO ANSWER" GSM_NL));
  386. return rsp == 1 && rsp2 == 0;
  387. }
  388. //bool callRedial() {
  389. // sendAT(GF("DLST"));
  390. // return waitResponse() == 1;
  391. //}
  392. bool callHangup() {
  393. sendAT(GF("H"));
  394. return waitResponse() == 1;
  395. }
  396. // 0-9,*,#,A,B,C,D
  397. bool dtmfSend(char cmd) {
  398. sendAT(GF("+VTS="), cmd);
  399. return waitResponse() == 1;
  400. }
  401. // Duration in milliseconds
  402. bool dtmfSetDuration(unsigned ms) {
  403. sendAT(GF("+VTD="), ms / 100); // VTD accepts in 1/10 of a second
  404. return waitResponse() == 1;
  405. }
  406. /*
  407. * Audio functions
  408. */
  409. bool audioSetHeadphones() {
  410. sendAT(GF("+SNFS=0"));
  411. return waitResponse() == 1;
  412. }
  413. bool audioSetSpeaker() {
  414. sendAT(GF("+SNFS=1"));
  415. return waitResponse() == 1;
  416. }
  417. bool audioMuteMic(bool mute) {
  418. sendAT(GF("+CMUT="), mute);
  419. return waitResponse() == 1;
  420. }
  421. /*
  422. * Messaging functions
  423. */
  424. String sendUSSD(const String& code) {
  425. sendAT(GF("+CMGF=1"));
  426. waitResponse();
  427. sendAT(GF("+CSCS=\"HEX\""));
  428. waitResponse();
  429. sendAT(GF("+CUSD=1,\""), code, GF("\",15"));
  430. if (waitResponse(10000L) != 1) {
  431. return "";
  432. }
  433. if (waitResponse(GF(GSM_NL "+CUSD:")) != 1) {
  434. return "";
  435. }
  436. stream.readStringUntil('"');
  437. String hex = stream.readStringUntil('"');
  438. stream.readStringUntil(',');
  439. int dcs = stream.readStringUntil('\n').toInt();
  440. if (dcs == 15) {
  441. return TinyGsmDecodeHex7bit(hex);
  442. } else if (dcs == 72) {
  443. return TinyGsmDecodeHex16bit(hex);
  444. } else {
  445. return hex;
  446. }
  447. }
  448. bool sendSMS(const String& number, const String& text) {
  449. sendAT(GF("+CMGF=1"));
  450. waitResponse();
  451. sendAT(GF("+CMGS=\""), number, GF("\""));
  452. if (waitResponse(GF(">")) != 1) {
  453. return false;
  454. }
  455. stream.print(text);
  456. stream.write((char)0x1A);
  457. stream.flush();
  458. return waitResponse(60000L) == 1;
  459. }
  460. /*
  461. * Location functions
  462. */
  463. String getGsmLocation() TINY_GSM_ATTR_NOT_AVAILABLE;
  464. /*
  465. * Battery functions
  466. */
  467. uint16_t getBattVoltage() TINY_GSM_ATTR_NOT_AVAILABLE;
  468. int getBattPercent() {
  469. sendAT(GF("+CBC?"));
  470. if (waitResponse(GF(GSM_NL "+CBC:")) != 1) {
  471. return false;
  472. }
  473. stream.readStringUntil(',');
  474. int res = stream.readStringUntil('\n').toInt();
  475. waitResponse();
  476. return res;
  477. }
  478. protected:
  479. bool modemConnect(const char* host, uint16_t port, uint8_t* mux) {
  480. sendAT(GF("+CIPSTART="), GF("\"TCP"), GF("\",\""), host, GF("\","), port);
  481. if (waitResponse(75000L, GF(GSM_NL "+CIPNUM:")) != 1) {
  482. return false;
  483. }
  484. int newMux = stream.readStringUntil('\n').toInt();
  485. int rsp = waitResponse(75000L,
  486. GF("CONNECT OK" GSM_NL),
  487. GF("CONNECT FAIL" GSM_NL),
  488. GF("ALREADY CONNECT" GSM_NL));
  489. if (waitResponse() != 1) {
  490. return false;
  491. }
  492. *mux = newMux;
  493. return (1 == rsp);
  494. }
  495. int modemSend(const void* buff, size_t len, uint8_t mux) {
  496. sendAT(GF("+CIPSEND="), mux, ',', len);
  497. if (waitResponse(2000L, GF(GSM_NL ">")) != 1) {
  498. return -1;
  499. }
  500. stream.write((uint8_t*)buff, len);
  501. stream.flush();
  502. if (waitResponse(10000L, GFP(GSM_OK), GF(GSM_NL "FAIL")) != 1) {
  503. return -1;
  504. }
  505. return len;
  506. }
  507. bool modemGetConnected(uint8_t mux) {
  508. sendAT(GF("+CIPSTATUS")); //TODO mux?
  509. int res = waitResponse(GF(",\"CONNECTED\""), GF(",\"CLOSED\""), GF(",\"CLOSING\""), GF(",\"INITIAL\""));
  510. waitResponse();
  511. return 1 == res;
  512. }
  513. public:
  514. /* Utilities */
  515. template<typename T>
  516. void streamWrite(T last) {
  517. stream.print(last);
  518. }
  519. template<typename T, typename... Args>
  520. void streamWrite(T head, Args... tail) {
  521. stream.print(head);
  522. streamWrite(tail...);
  523. }
  524. bool streamSkipUntil(char c) { //TODO: timeout
  525. while (true) {
  526. while (!stream.available()) { TINY_GSM_YIELD(); }
  527. if (stream.read() == c)
  528. return true;
  529. }
  530. return false;
  531. }
  532. template<typename... Args>
  533. void sendAT(Args... cmd) {
  534. streamWrite("AT", cmd..., GSM_NL);
  535. stream.flush();
  536. TINY_GSM_YIELD();
  537. //DBG("### AT:", cmd...);
  538. }
  539. // TODO: Optimize this!
  540. uint8_t waitResponse(uint32_t timeout, String& data,
  541. GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  542. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  543. {
  544. /*String r1s(r1); r1s.trim();
  545. String r2s(r2); r2s.trim();
  546. String r3s(r3); r3s.trim();
  547. String r4s(r4); r4s.trim();
  548. String r5s(r5); r5s.trim();
  549. DBG("### ..:", r1s, ",", r2s, ",", r3s, ",", r4s, ",", r5s);*/
  550. data.reserve(64);
  551. int index = 0;
  552. unsigned long startMillis = millis();
  553. do {
  554. TINY_GSM_YIELD();
  555. while (stream.available() > 0) {
  556. int a = stream.read();
  557. if (a <= 0) continue; // Skip 0x00 bytes, just in case
  558. data += (char)a;
  559. if (r1 && data.endsWith(r1)) {
  560. index = 1;
  561. goto finish;
  562. } else if (r2 && data.endsWith(r2)) {
  563. index = 2;
  564. goto finish;
  565. } else if (r3 && data.endsWith(r3)) {
  566. index = 3;
  567. goto finish;
  568. } else if (r4 && data.endsWith(r4)) {
  569. index = 4;
  570. goto finish;
  571. } else if (r5 && data.endsWith(r5)) {
  572. index = 5;
  573. goto finish;
  574. } else if (data.endsWith(GF("+CIPRCV:"))) {
  575. int mux = stream.readStringUntil(',').toInt();
  576. int len = stream.readStringUntil(',').toInt();
  577. int len_orig = len;
  578. if (len > sockets[mux]->rx.free()) {
  579. DBG("### Buffer overflow: ", len, "->", sockets[mux]->rx.free());
  580. } else {
  581. DBG("### Got: ", len, "->", sockets[mux]->rx.free());
  582. }
  583. while (len--) {
  584. while (!stream.available()) { TINY_GSM_YIELD(); }
  585. sockets[mux]->rx.put(stream.read());
  586. }
  587. if (len_orig > sockets[mux]->available()) { // TODO
  588. DBG(GSM_NL, "### Fewer characters received than expected: ", sockets[mux]->available(), " vs ", len_orig);
  589. }
  590. data = "";
  591. } else if (data.endsWith(GF("+TCPCLOSED:"))) {
  592. int mux = stream.readStringUntil('\n').toInt();
  593. if (mux >= 0 && mux < TINY_GSM_MUX_COUNT) {
  594. sockets[mux]->sock_connected = false;
  595. }
  596. data = "";
  597. DBG("### Closed: ", mux);
  598. }
  599. }
  600. } while (millis() - startMillis < timeout);
  601. finish:
  602. if (!index) {
  603. data.trim();
  604. if (data.length()) {
  605. DBG("### Unhandled:", data);
  606. }
  607. data = "";
  608. }
  609. return index;
  610. }
  611. uint8_t waitResponse(uint32_t timeout,
  612. GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  613. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  614. {
  615. String data;
  616. return waitResponse(timeout, data, r1, r2, r3, r4, r5);
  617. }
  618. uint8_t waitResponse(GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  619. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  620. {
  621. return waitResponse(1000, r1, r2, r3, r4, r5);
  622. }
  623. protected:
  624. Stream& stream;
  625. GsmClient* sockets[TINY_GSM_MUX_COUNT];
  626. };
  627. #endif