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.

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