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.

743 lines
17 KiB

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