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.

756 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. sendAT(GF("+CMER=3,0,0,2"));
  162. waitResponse();
  163. getSimStatus();
  164. return true;
  165. }
  166. void setBaud(unsigned long baud) {
  167. sendAT(GF("+IPR="), baud);
  168. }
  169. bool testAT(unsigned long timeout = 10000L) {
  170. for (unsigned long start = millis(); millis() - start < timeout; ) {
  171. sendAT(GF(""));
  172. if (waitResponse(200) == 1) {
  173. delay(100);
  174. return true;
  175. }
  176. delay(100);
  177. }
  178. return false;
  179. }
  180. void maintain() {
  181. //while (stream.available()) {
  182. waitResponse(10, NULL, NULL);
  183. //}
  184. }
  185. bool factoryDefault() {
  186. sendAT(GF("&FZE0&W")); // Factory + Reset + Echo Off + Write
  187. waitResponse();
  188. sendAT(GF("&W")); // Write configuration
  189. return waitResponse() == 1;
  190. }
  191. String getModemInfo() {
  192. sendAT(GF("I"));
  193. String res;
  194. if (waitResponse(1000L, res) != 1) {
  195. return "";
  196. }
  197. res.replace(GSM_NL "OK" GSM_NL, "");
  198. res.replace(GSM_NL, " ");
  199. res.trim();
  200. return res;
  201. }
  202. /*
  203. * Power functions
  204. */
  205. bool restart() {
  206. if (!testAT()) {
  207. return false;
  208. }
  209. sendAT(GF("+RST=1"));
  210. delay(3000);
  211. return init();
  212. }
  213. bool poweroff() {
  214. sendAT(GF("+CPOF"));
  215. return waitResponse() == 1;
  216. }
  217. bool radioOff() TINY_GSM_ATTR_NOT_IMPLEMENTED;
  218. bool sleepEnable(bool enable = true) TINY_GSM_ATTR_NOT_IMPLEMENTED;
  219. /*
  220. * SIM card functions
  221. */
  222. bool simUnlock(const char *pin) {
  223. sendAT(GF("+CPIN=\""), pin, GF("\""));
  224. return waitResponse() == 1;
  225. }
  226. String getSimCCID() {
  227. sendAT(GF("+CCID"));
  228. if (waitResponse(GF(GSM_NL "+SCID: SIM Card ID:")) != 1) {
  229. return "";
  230. }
  231. String res = stream.readStringUntil('\n');
  232. waitResponse();
  233. res.trim();
  234. return res;
  235. }
  236. String getIMEI() {
  237. sendAT(GF("+GSN"));
  238. if (waitResponse(GF(GSM_NL)) != 1) {
  239. return "";
  240. }
  241. String res = stream.readStringUntil('\n');
  242. waitResponse();
  243. res.trim();
  244. return res;
  245. }
  246. SimStatus getSimStatus(unsigned long timeout = 10000L) {
  247. for (unsigned long start = millis(); millis() - start < timeout; ) {
  248. sendAT(GF("+CPIN?"));
  249. if (waitResponse(GF(GSM_NL "+CPIN:")) != 1) {
  250. delay(1000);
  251. continue;
  252. }
  253. int status = waitResponse(GF("READY"), GF("SIM PIN"), GF("SIM PUK"));
  254. waitResponse();
  255. switch (status) {
  256. case 2:
  257. case 3: return SIM_LOCKED;
  258. case 1: return SIM_READY;
  259. default: return SIM_ERROR;
  260. }
  261. }
  262. return SIM_ERROR;
  263. }
  264. RegStatus getRegistrationStatus() {
  265. sendAT(GF("+CREG?"));
  266. if (waitResponse(GF(GSM_NL "+CREG:")) != 1) {
  267. return REG_UNKNOWN;
  268. }
  269. streamSkipUntil(','); // Skip format (0)
  270. int status = stream.readStringUntil('\n').toInt();
  271. waitResponse();
  272. return (RegStatus)status;
  273. }
  274. String getOperator() {
  275. sendAT(GF("+COPS=3,0")); // Set format
  276. waitResponse();
  277. sendAT(GF("+COPS?"));
  278. if (waitResponse(GF(GSM_NL "+COPS:")) != 1) {
  279. return "";
  280. }
  281. streamSkipUntil('"'); // Skip mode and format
  282. String res = stream.readStringUntil('"');
  283. waitResponse();
  284. return res;
  285. }
  286. /*
  287. * Generic network functions
  288. */
  289. int getSignalQuality() {
  290. sendAT(GF("+CSQ"));
  291. if (waitResponse(GF(GSM_NL "+CSQ:")) != 1) {
  292. return 99;
  293. }
  294. int res = stream.readStringUntil(',').toInt();
  295. waitResponse();
  296. return res;
  297. }
  298. bool isNetworkConnected() {
  299. RegStatus s = getRegistrationStatus();
  300. return (s == REG_OK_HOME || s == REG_OK_ROAMING);
  301. }
  302. bool waitForNetwork(unsigned long timeout = 60000L) {
  303. for (unsigned long start = millis(); millis() - start < timeout; ) {
  304. if (isNetworkConnected()) {
  305. return true;
  306. }
  307. delay(500);
  308. }
  309. return false;
  310. }
  311. /*
  312. * GPRS functions
  313. */
  314. bool gprsConnect(const char* apn, const char* user, const char* pwd) {
  315. gprsDisconnect();
  316. sendAT(GF("+CGATT=1"));
  317. if (waitResponse(60000L) != 1)
  318. return false;
  319. // TODO: wait AT+CGATT?
  320. sendAT(GF("+CGDCONT=1,\"IP\",\""), apn, '"');
  321. waitResponse();
  322. if (!user) user = "";
  323. if (!pwd) pwd = "";
  324. sendAT(GF("+CSTT=\""), apn, GF("\",\""), user, GF("\",\""), pwd, GF("\""));
  325. if (waitResponse(60000L) != 1) {
  326. return false;
  327. }
  328. sendAT(GF("+CGACT=1,1"));
  329. waitResponse(60000L);
  330. sendAT(GF("+CIPMUX=1"));
  331. if (waitResponse() != 1) {
  332. return false;
  333. }
  334. return true;
  335. }
  336. bool gprsDisconnect() {
  337. sendAT(GF("+CIPSHUT"));
  338. waitResponse(5000L);
  339. for (int i = 0; i<3; i++) {
  340. sendAT(GF("+CGATT=0"));
  341. if (waitResponse(5000L) == 1)
  342. return true;
  343. }
  344. return false;
  345. }
  346. bool isGprsConnected() {
  347. sendAT(GF("+CGATT?"));
  348. if (waitResponse(GF(GSM_NL "+CGATT:")) != 1) {
  349. return false;
  350. }
  351. int res = stream.readStringUntil('\n').toInt();
  352. waitResponse();
  353. return (res == 1);
  354. }
  355. String getLocalIP() {
  356. sendAT(GF("+CIFSR"));
  357. String res;
  358. if (waitResponse(10000L, res) != 1) {
  359. return "";
  360. }
  361. res.replace(GSM_NL "OK" GSM_NL, "");
  362. res.replace(GSM_NL, "");
  363. res.trim();
  364. return res;
  365. }
  366. IPAddress localIP() {
  367. return TinyGsmIpFromString(getLocalIP());
  368. }
  369. /*
  370. * Phone Call functions
  371. */
  372. bool setGsmBusy(bool busy = true) TINY_GSM_ATTR_NOT_AVAILABLE;
  373. bool callAnswer() {
  374. sendAT(GF("A"));
  375. return waitResponse() == 1;
  376. }
  377. // Returns true on pick-up, false on error/busy
  378. bool callNumber(const String& number) {
  379. if (number == GF("last")) {
  380. sendAT(GF("DLST"));
  381. } else {
  382. sendAT(GF("D\""), number, "\";");
  383. }
  384. if (waitResponse(5000L) != 1) {
  385. return false;
  386. }
  387. if (waitResponse(60000L,
  388. GF(GSM_NL "+CIEV: \"CALL\",1"),
  389. GF(GSM_NL "+CIEV: \"CALL\",0"),
  390. GFP(GSM_ERROR)) != 1)
  391. {
  392. return false;
  393. }
  394. int rsp = waitResponse(60000L,
  395. GF(GSM_NL "+CIEV: \"SOUNDER\",0"),
  396. GF(GSM_NL "+CIEV: \"CALL\",0"));
  397. int rsp2 = waitResponse(300L, GF(GSM_NL "BUSY" GSM_NL), GF(GSM_NL "NO ANSWER" GSM_NL));
  398. return rsp == 1 && rsp2 == 0;
  399. }
  400. bool callHangup() {
  401. sendAT(GF("H"));
  402. return waitResponse() == 1;
  403. }
  404. // 0-9,*,#,A,B,C,D
  405. bool dtmfSend(char cmd, unsigned duration_ms = 100) {
  406. duration_ms = constrain(duration_ms, 100, 1000);
  407. // The duration parameter is not working, so we simulate it using delay..
  408. // TODO: Maybe there's another way...
  409. //sendAT(GF("+VTD="), duration_ms / 100);
  410. //waitResponse();
  411. sendAT(GF("+VTS="), cmd);
  412. if (waitResponse(10000L) == 1) {
  413. delay(duration_ms);
  414. return true;
  415. }
  416. return false;
  417. }
  418. /*
  419. * Audio functions
  420. */
  421. bool audioSetHeadphones() {
  422. sendAT(GF("+SNFS=0"));
  423. return waitResponse() == 1;
  424. }
  425. bool audioSetSpeaker() {
  426. sendAT(GF("+SNFS=1"));
  427. return waitResponse() == 1;
  428. }
  429. bool audioMuteMic(bool mute) {
  430. sendAT(GF("+CMUT="), mute);
  431. return waitResponse() == 1;
  432. }
  433. /*
  434. * Messaging functions
  435. */
  436. String sendUSSD(const String& code) {
  437. sendAT(GF("+CMGF=1"));
  438. waitResponse();
  439. sendAT(GF("+CSCS=\"HEX\""));
  440. waitResponse();
  441. sendAT(GF("+CUSD=1,\""), code, GF("\",15"));
  442. if (waitResponse(10000L) != 1) {
  443. return "";
  444. }
  445. if (waitResponse(GF(GSM_NL "+CUSD:")) != 1) {
  446. return "";
  447. }
  448. stream.readStringUntil('"');
  449. String hex = stream.readStringUntil('"');
  450. stream.readStringUntil(',');
  451. int dcs = stream.readStringUntil('\n').toInt();
  452. if (dcs == 15) {
  453. return TinyGsmDecodeHex7bit(hex);
  454. } else if (dcs == 72) {
  455. return TinyGsmDecodeHex16bit(hex);
  456. } else {
  457. return hex;
  458. }
  459. }
  460. bool sendSMS(const String& number, const String& text) {
  461. sendAT(GF("+CMGF=1"));
  462. waitResponse();
  463. sendAT(GF("+CMGS=\""), number, GF("\""));
  464. if (waitResponse(GF(">")) != 1) {
  465. return false;
  466. }
  467. stream.print(text);
  468. stream.write((char)0x1A);
  469. stream.flush();
  470. return waitResponse(60000L) == 1;
  471. }
  472. /*
  473. * Location functions
  474. */
  475. String getGsmLocation() TINY_GSM_ATTR_NOT_AVAILABLE;
  476. /*
  477. * Battery functions
  478. */
  479. uint16_t getBattVoltage() TINY_GSM_ATTR_NOT_AVAILABLE;
  480. int getBattPercent() {
  481. sendAT(GF("+CBC?"));
  482. if (waitResponse(GF(GSM_NL "+CBC:")) != 1) {
  483. return false;
  484. }
  485. stream.readStringUntil(',');
  486. int res = stream.readStringUntil('\n').toInt();
  487. waitResponse();
  488. return res;
  489. }
  490. protected:
  491. bool modemConnect(const char* host, uint16_t port, uint8_t* mux) {
  492. sendAT(GF("+CIPSTART="), GF("\"TCP"), GF("\",\""), host, GF("\","), port);
  493. if (waitResponse(75000L, GF(GSM_NL "+CIPNUM:")) != 1) {
  494. return false;
  495. }
  496. int newMux = stream.readStringUntil('\n').toInt();
  497. int rsp = waitResponse(75000L,
  498. GF("CONNECT OK" GSM_NL),
  499. GF("CONNECT FAIL" GSM_NL),
  500. GF("ALREADY CONNECT" GSM_NL));
  501. if (waitResponse() != 1) {
  502. return false;
  503. }
  504. *mux = newMux;
  505. return (1 == rsp);
  506. }
  507. int modemSend(const void* buff, size_t len, uint8_t mux) {
  508. sendAT(GF("+CIPSEND="), mux, ',', len);
  509. if (waitResponse(2000L, GF(GSM_NL ">")) != 1) {
  510. return -1;
  511. }
  512. stream.write((uint8_t*)buff, len);
  513. stream.flush();
  514. if (waitResponse(10000L, GFP(GSM_OK), GF(GSM_NL "FAIL")) != 1) {
  515. return -1;
  516. }
  517. return len;
  518. }
  519. bool modemGetConnected(uint8_t mux) {
  520. sendAT(GF("+CIPSTATUS")); //TODO mux?
  521. int res = waitResponse(GF(",\"CONNECTED\""), GF(",\"CLOSED\""), GF(",\"CLOSING\""), GF(",\"INITIAL\""));
  522. waitResponse();
  523. return 1 == res;
  524. }
  525. public:
  526. /* Utilities */
  527. template<typename T>
  528. void streamWrite(T last) {
  529. stream.print(last);
  530. }
  531. template<typename T, typename... Args>
  532. void streamWrite(T head, Args... tail) {
  533. stream.print(head);
  534. streamWrite(tail...);
  535. }
  536. bool streamSkipUntil(char c) { //TODO: timeout
  537. while (true) {
  538. while (!stream.available()) { TINY_GSM_YIELD(); }
  539. if (stream.read() == c)
  540. return true;
  541. }
  542. return false;
  543. }
  544. template<typename... Args>
  545. void sendAT(Args... cmd) {
  546. streamWrite("AT", cmd..., GSM_NL);
  547. stream.flush();
  548. TINY_GSM_YIELD();
  549. //DBG("### AT:", cmd...);
  550. }
  551. // TODO: Optimize this!
  552. uint8_t waitResponse(uint32_t timeout, String& data,
  553. GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  554. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  555. {
  556. /*String r1s(r1); r1s.trim();
  557. String r2s(r2); r2s.trim();
  558. String r3s(r3); r3s.trim();
  559. String r4s(r4); r4s.trim();
  560. String r5s(r5); r5s.trim();
  561. DBG("### ..:", r1s, ",", r2s, ",", r3s, ",", r4s, ",", r5s);*/
  562. data.reserve(64);
  563. int index = 0;
  564. unsigned long startMillis = millis();
  565. do {
  566. TINY_GSM_YIELD();
  567. while (stream.available() > 0) {
  568. int a = stream.read();
  569. if (a <= 0) continue; // Skip 0x00 bytes, just in case
  570. data += (char)a;
  571. if (r1 && data.endsWith(r1)) {
  572. index = 1;
  573. goto finish;
  574. } else if (r2 && data.endsWith(r2)) {
  575. index = 2;
  576. goto finish;
  577. } else if (r3 && data.endsWith(r3)) {
  578. index = 3;
  579. goto finish;
  580. } else if (r4 && data.endsWith(r4)) {
  581. index = 4;
  582. goto finish;
  583. } else if (r5 && data.endsWith(r5)) {
  584. index = 5;
  585. goto finish;
  586. } else if (data.endsWith(GF("+CIPRCV:"))) {
  587. int mux = stream.readStringUntil(',').toInt();
  588. int len = stream.readStringUntil(',').toInt();
  589. int len_orig = len;
  590. if (len > sockets[mux]->rx.free()) {
  591. DBG("### Buffer overflow: ", len, "->", sockets[mux]->rx.free());
  592. } else {
  593. DBG("### Got: ", len, "->", sockets[mux]->rx.free());
  594. }
  595. while (len--) {
  596. while (!stream.available()) { TINY_GSM_YIELD(); }
  597. sockets[mux]->rx.put(stream.read());
  598. }
  599. if (len_orig > sockets[mux]->available()) { // TODO
  600. DBG(GSM_NL, "### Fewer characters received than expected: ", sockets[mux]->available(), " vs ", len_orig);
  601. }
  602. data = "";
  603. } else if (data.endsWith(GF("+TCPCLOSED:"))) {
  604. int mux = stream.readStringUntil('\n').toInt();
  605. if (mux >= 0 && mux < TINY_GSM_MUX_COUNT) {
  606. sockets[mux]->sock_connected = false;
  607. }
  608. data = "";
  609. DBG("### Closed: ", mux);
  610. }
  611. }
  612. } while (millis() - startMillis < timeout);
  613. finish:
  614. if (!index) {
  615. data.trim();
  616. if (data.length()) {
  617. DBG("### Unhandled:", data);
  618. }
  619. data = "";
  620. }
  621. return index;
  622. }
  623. uint8_t waitResponse(uint32_t timeout,
  624. GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  625. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  626. {
  627. String data;
  628. return waitResponse(timeout, data, r1, r2, r3, r4, r5);
  629. }
  630. uint8_t waitResponse(GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  631. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  632. {
  633. return waitResponse(1000, r1, r2, r3, r4, r5);
  634. }
  635. protected:
  636. Stream& stream;
  637. GsmClient* sockets[TINY_GSM_MUX_COUNT];
  638. };
  639. #endif