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.

682 lines
16 KiB

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