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.

708 lines
16 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.trim();
  360. return res;
  361. }
  362. IPAddress localIP() {
  363. return TinyGsmIpFromString(getLocalIP());
  364. }
  365. /*
  366. * Phone Call functions
  367. */
  368. bool setGsmBusy(bool busy = true) TINY_GSM_ATTR_NOT_AVAILABLE;
  369. bool callAnswer() {
  370. sendAT(GF("A"));
  371. return waitResponse() == 1;
  372. }
  373. // Returns true on pick-up, false on error/busy
  374. bool callNumber(const String& number) {
  375. sendAT(GF("D\""), number, "\";");
  376. if (waitResponse() != 1) {
  377. return false;
  378. }
  379. if (waitResponse(60000L, GF(GSM_NL "+CIEV: \"CALL\",1"), GF(GSM_NL "+CIEV: \"CALL\",0")) != 1) {
  380. return false;
  381. }
  382. int rsp = waitResponse(60000L, GF(GSM_NL "+CIEV: \"SOUNDER\",0"), GF(GSM_NL "+CIEV: \"CALL\",0"));
  383. int rsp2 = waitResponse(300L, GF(GSM_NL "BUSY" GSM_NL), GF(GSM_NL "NO ANSWER" GSM_NL));
  384. return rsp == 1 && rsp2 == 0;
  385. }
  386. //bool callRedial() {
  387. // sendAT(GF("DLST"));
  388. // return waitResponse() == 1;
  389. //}
  390. bool callHangup() {
  391. sendAT(GF("H"));
  392. return waitResponse() == 1;
  393. }
  394. /*
  395. * Messaging functions
  396. */
  397. String sendUSSD(const String& code) {
  398. sendAT(GF("+CMGF=1"));
  399. waitResponse();
  400. sendAT(GF("+CSCS=\"HEX\""));
  401. waitResponse();
  402. sendAT(GF("+CUSD=1,\""), code, GF("\",15"));
  403. if (waitResponse(10000L) != 1) {
  404. return "";
  405. }
  406. if (waitResponse(GF(GSM_NL "+CUSD:")) != 1) {
  407. return "";
  408. }
  409. stream.readStringUntil('"');
  410. String hex = stream.readStringUntil('"');
  411. stream.readStringUntil(',');
  412. int dcs = stream.readStringUntil('\n').toInt();
  413. if (dcs == 15) {
  414. return TinyGsmDecodeHex7bit(hex);
  415. } else if (dcs == 72) {
  416. return TinyGsmDecodeHex16bit(hex);
  417. } else {
  418. return hex;
  419. }
  420. }
  421. bool sendSMS(const String& number, const String& text) {
  422. sendAT(GF("+CMGF=1"));
  423. waitResponse();
  424. sendAT(GF("+CMGS=\""), number, GF("\""));
  425. if (waitResponse(GF(">")) != 1) {
  426. return false;
  427. }
  428. stream.print(text);
  429. stream.write((char)0x1A);
  430. stream.flush();
  431. return waitResponse(60000L) == 1;
  432. }
  433. /*
  434. * Location functions
  435. */
  436. String getGsmLocation() TINY_GSM_ATTR_NOT_AVAILABLE;
  437. /*
  438. * Battery functions
  439. */
  440. uint16_t getBattVoltage() TINY_GSM_ATTR_NOT_AVAILABLE;
  441. int getBattPercent() {
  442. sendAT(GF("+CBC?"));
  443. if (waitResponse(GF(GSM_NL "+CBC:")) != 1) {
  444. return false;
  445. }
  446. stream.readStringUntil(',');
  447. int res = stream.readStringUntil('\n').toInt();
  448. waitResponse();
  449. return res;
  450. }
  451. protected:
  452. bool modemConnect(const char* host, uint16_t port, uint8_t* mux) {
  453. sendAT(GF("+CIPSTART="), GF("\"TCP"), GF("\",\""), host, GF("\","), port);
  454. if (waitResponse(75000L, GF(GSM_NL "+CIPNUM:")) != 1) {
  455. return false;
  456. }
  457. int newMux = stream.readStringUntil('\n').toInt();
  458. int rsp = waitResponse(75000L,
  459. GF("CONNECT OK" GSM_NL),
  460. GF("CONNECT FAIL" GSM_NL),
  461. GF("ALREADY CONNECT" GSM_NL));
  462. if (waitResponse() != 1) {
  463. return false;
  464. }
  465. *mux = newMux;
  466. return (1 == rsp);
  467. }
  468. int modemSend(const void* buff, size_t len, uint8_t mux) {
  469. sendAT(GF("+CIPSEND="), mux, ',', len);
  470. if (waitResponse(2000L, GF(GSM_NL ">")) != 1) {
  471. return -1;
  472. }
  473. stream.write((uint8_t*)buff, len);
  474. stream.flush();
  475. if (waitResponse(10000L, GFP(GSM_OK), GF(GSM_NL "FAIL")) != 1) {
  476. return -1;
  477. }
  478. return len;
  479. }
  480. bool modemGetConnected(uint8_t mux) {
  481. sendAT(GF("+CIPSTATUS")); //TODO mux?
  482. int res = waitResponse(GF(",\"CONNECTED\""), GF(",\"CLOSED\""), GF(",\"CLOSING\""), GF(",\"INITIAL\""));
  483. waitResponse();
  484. return 1 == res;
  485. }
  486. public:
  487. /* Utilities */
  488. template<typename T>
  489. void streamWrite(T last) {
  490. stream.print(last);
  491. }
  492. template<typename T, typename... Args>
  493. void streamWrite(T head, Args... tail) {
  494. stream.print(head);
  495. streamWrite(tail...);
  496. }
  497. bool streamSkipUntil(char c) { //TODO: timeout
  498. while (true) {
  499. while (!stream.available()) { TINY_GSM_YIELD(); }
  500. if (stream.read() == c)
  501. return true;
  502. }
  503. return false;
  504. }
  505. template<typename... Args>
  506. void sendAT(Args... cmd) {
  507. streamWrite("AT", cmd..., GSM_NL);
  508. stream.flush();
  509. TINY_GSM_YIELD();
  510. //DBG("### AT:", cmd...);
  511. }
  512. // TODO: Optimize this!
  513. uint8_t waitResponse(uint32_t timeout, String& data,
  514. GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  515. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  516. {
  517. /*String r1s(r1); r1s.trim();
  518. String r2s(r2); r2s.trim();
  519. String r3s(r3); r3s.trim();
  520. String r4s(r4); r4s.trim();
  521. String r5s(r5); r5s.trim();
  522. DBG("### ..:", r1s, ",", r2s, ",", r3s, ",", r4s, ",", r5s);*/
  523. data.reserve(64);
  524. int index = 0;
  525. unsigned long startMillis = millis();
  526. do {
  527. TINY_GSM_YIELD();
  528. while (stream.available() > 0) {
  529. int a = stream.read();
  530. if (a <= 0) continue; // Skip 0x00 bytes, just in case
  531. data += (char)a;
  532. if (r1 && data.endsWith(r1)) {
  533. index = 1;
  534. goto finish;
  535. } else if (r2 && data.endsWith(r2)) {
  536. index = 2;
  537. goto finish;
  538. } else if (r3 && data.endsWith(r3)) {
  539. index = 3;
  540. goto finish;
  541. } else if (r4 && data.endsWith(r4)) {
  542. index = 4;
  543. goto finish;
  544. } else if (r5 && data.endsWith(r5)) {
  545. index = 5;
  546. goto finish;
  547. } else if (data.endsWith(GF("+CIPRCV:"))) {
  548. int mux = stream.readStringUntil(',').toInt();
  549. int len = stream.readStringUntil(',').toInt();
  550. int len_orig = len;
  551. if (len > sockets[mux]->rx.free()) {
  552. DBG("### Buffer overflow: ", len, "->", sockets[mux]->rx.free());
  553. } else {
  554. DBG("### Got: ", len, "->", sockets[mux]->rx.free());
  555. }
  556. while (len--) {
  557. while (!stream.available()) { TINY_GSM_YIELD(); }
  558. sockets[mux]->rx.put(stream.read());
  559. }
  560. if (len_orig > sockets[mux]->available()) { // TODO
  561. DBG(GSM_NL, "### Fewer characters received than expected: ", sockets[mux]->available(), " vs ", len_orig);
  562. }
  563. data = "";
  564. } else if (data.endsWith(GF("+TCPCLOSED:"))) {
  565. int mux = stream.readStringUntil('\n').toInt();
  566. if (mux >= 0 && mux < TINY_GSM_MUX_COUNT) {
  567. sockets[mux]->sock_connected = false;
  568. }
  569. data = "";
  570. DBG("### Closed: ", mux);
  571. }
  572. }
  573. } while (millis() - startMillis < timeout);
  574. finish:
  575. if (!index) {
  576. data.trim();
  577. if (data.length()) {
  578. DBG("### Unhandled:", data);
  579. }
  580. data = "";
  581. }
  582. return index;
  583. }
  584. uint8_t waitResponse(uint32_t timeout,
  585. GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  586. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  587. {
  588. String data;
  589. return waitResponse(timeout, data, r1, r2, r3, r4, r5);
  590. }
  591. uint8_t waitResponse(GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  592. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  593. {
  594. return waitResponse(1000, r1, r2, r3, r4, r5);
  595. }
  596. protected:
  597. Stream& stream;
  598. GsmClient* sockets[TINY_GSM_MUX_COUNT];
  599. };
  600. #endif