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.

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