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.

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