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.

623 lines
14 KiB

8 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. #include <TinyGsmCommon.h>
  15. #define GSM_NL "\r\n"
  16. static const char GSM_OK[] TINY_GSM_PROGMEM = "OK" GSM_NL;
  17. static const char GSM_ERROR[] TINY_GSM_PROGMEM = "ERROR" GSM_NL;
  18. enum SimStatus {
  19. SIM_ERROR = 0,
  20. SIM_READY = 1,
  21. SIM_LOCKED = 2,
  22. };
  23. enum RegStatus {
  24. REG_UNREGISTERED = 0,
  25. REG_SEARCHING = 2,
  26. REG_DENIED = 3,
  27. REG_OK_HOME = 1,
  28. REG_OK_ROAMING = 5,
  29. REG_UNKNOWN = 4,
  30. };
  31. class TinyGsm
  32. {
  33. public:
  34. TinyGsm(Stream& stream)
  35. : stream(stream)
  36. {}
  37. public:
  38. class GsmClient : public Client
  39. {
  40. friend class TinyGsm;
  41. typedef TinyGsmFifo<uint8_t, TINY_GSM_RX_BUFFER> RxFifo;
  42. public:
  43. GsmClient() {}
  44. GsmClient(TinyGsm& modem) {
  45. init(&modem);
  46. }
  47. bool init(TinyGsm* modem) {
  48. this->at = modem;
  49. this->mux = -1;
  50. sock_connected = false;
  51. return true;
  52. }
  53. public:
  54. virtual int connect(const char *host, uint16_t port) {
  55. TINY_GSM_YIELD();
  56. rx.clear();
  57. uint8_t newMux = -1;
  58. sock_connected = at->modemConnect(host, port, &newMux);
  59. if (sock_connected) {
  60. mux = newMux;
  61. at->sockets[mux] = this;
  62. }
  63. return sock_connected;
  64. }
  65. virtual int connect(IPAddress ip, uint16_t port) {
  66. String host; host.reserve(16);
  67. host += ip[0];
  68. host += ".";
  69. host += ip[1];
  70. host += ".";
  71. host += ip[2];
  72. host += ".";
  73. host += ip[3];
  74. return connect(host.c_str(), port);
  75. }
  76. virtual void stop() {
  77. TINY_GSM_YIELD();
  78. at->sendAT(GF("+CIPCLOSE="), mux);
  79. sock_connected = false;
  80. at->waitResponse();
  81. }
  82. virtual size_t write(const uint8_t *buf, size_t size) {
  83. TINY_GSM_YIELD();
  84. //at->maintain();
  85. return at->modemSend(buf, size, mux);
  86. }
  87. virtual size_t write(uint8_t c) {
  88. return write(&c, 1);
  89. }
  90. virtual int available() {
  91. TINY_GSM_YIELD();
  92. if (!rx.size()) {
  93. at->maintain();
  94. }
  95. return rx.size();
  96. }
  97. virtual int read(uint8_t *buf, size_t size) {
  98. TINY_GSM_YIELD();
  99. size_t cnt = 0;
  100. while (cnt < size) {
  101. size_t chunk = TinyGsmMin(size-cnt, rx.size());
  102. if (chunk > 0) {
  103. rx.get(buf, chunk);
  104. buf += chunk;
  105. cnt += chunk;
  106. continue;
  107. }
  108. // TODO: Read directly into user buffer?
  109. if (!rx.size()) {
  110. at->maintain();
  111. //break;
  112. }
  113. }
  114. return cnt;
  115. }
  116. virtual int read() {
  117. uint8_t c;
  118. if (read(&c, 1) == 1) {
  119. return c;
  120. }
  121. return -1;
  122. }
  123. virtual int peek() { return -1; } //TODO
  124. virtual void flush() { at->stream.flush(); }
  125. virtual uint8_t connected() {
  126. if (available()) {
  127. return true;
  128. }
  129. return sock_connected;
  130. }
  131. virtual operator bool() { return connected(); }
  132. private:
  133. TinyGsm* at;
  134. uint8_t mux;
  135. bool sock_connected;
  136. RxFifo rx;
  137. };
  138. public:
  139. /*
  140. * Basic functions
  141. */
  142. bool begin() {
  143. return init();
  144. }
  145. bool init() {
  146. if (!autoBaud()) {
  147. return false;
  148. }
  149. sendAT(GF("&FZE0")); // Factory + Reset + Echo Off
  150. if (waitResponse() != 1) {
  151. return false;
  152. }
  153. sendAT(GF("+CMEE=0"));
  154. waitResponse();
  155. getSimStatus();
  156. return true;
  157. }
  158. bool autoBaud(unsigned long timeout = 10000L) {
  159. for (unsigned long start = millis(); millis() - start < timeout; ) {
  160. sendAT(GF("E0"));
  161. if (waitResponse(200) == 1) {
  162. delay(100);
  163. return true;
  164. }
  165. delay(100);
  166. }
  167. return false;
  168. }
  169. void maintain() {
  170. //while (stream.available()) {
  171. waitResponse(10, NULL, NULL);
  172. //}
  173. }
  174. bool factoryDefault() {
  175. sendAT(GF("&FZE0&W")); // Factory + Reset + Echo Off + Write
  176. waitResponse();
  177. sendAT(GF("&W")); // Write configuration
  178. return waitResponse() == 1;
  179. }
  180. /*
  181. * Power functions
  182. */
  183. bool restart() {
  184. if (!autoBaud()) {
  185. return false;
  186. }
  187. sendAT(GF("+RST=1"));
  188. delay(3000);
  189. return init();
  190. }
  191. /*
  192. * SIM card & Network Operator functions
  193. */
  194. bool simUnlock(const char *pin) {
  195. sendAT(GF("+CPIN=\""), pin, GF("\""));
  196. return waitResponse() == 1;
  197. }
  198. String getSimCCID() {
  199. sendAT(GF("+CCID"));
  200. if (waitResponse(GF(GSM_NL "+ICCID:")) != 1) {
  201. return "";
  202. }
  203. String res = streamReadUntil('\n');
  204. waitResponse();
  205. return res;
  206. }
  207. String getIMEI() {
  208. sendAT(GF("+GSN"));
  209. if (waitResponse(GF(GSM_NL)) != 1) {
  210. return "";
  211. }
  212. String res = streamReadUntil('\n');
  213. waitResponse();
  214. return res;
  215. }
  216. int getSignalQuality() {
  217. sendAT(GF("+CSQ"));
  218. if (waitResponse(GF(GSM_NL "+CSQ:")) != 1) {
  219. return 99;
  220. }
  221. int res = streamReadUntil(',').toInt();
  222. waitResponse();
  223. return res;
  224. }
  225. SimStatus getSimStatus(unsigned long timeout = 10000L) {
  226. for (unsigned long start = millis(); millis() - start < timeout; ) {
  227. sendAT(GF("+CPIN?"));
  228. if (waitResponse(GF(GSM_NL "+CPIN:")) != 1) {
  229. delay(1000);
  230. continue;
  231. }
  232. int status = waitResponse(GF("READY"), GF("SIM PIN"), GF("SIM PUK"));
  233. waitResponse();
  234. switch (status) {
  235. case 2:
  236. case 3: return SIM_LOCKED;
  237. case 1: return SIM_READY;
  238. default: return SIM_ERROR;
  239. }
  240. }
  241. return SIM_ERROR;
  242. }
  243. RegStatus getRegistrationStatus() {
  244. sendAT(GF("+CREG?"));
  245. if (waitResponse(GF(GSM_NL "+CREG:")) != 1) {
  246. return REG_UNKNOWN;
  247. }
  248. streamSkipUntil(','); // Skip format (0)
  249. int status = streamReadUntil('\n').toInt();
  250. waitResponse();
  251. return (RegStatus)status;
  252. }
  253. String getOperator() {
  254. sendAT(GF("+COPS?"));
  255. if (waitResponse(GF(GSM_NL "+COPS:")) != 1) {
  256. return "";
  257. }
  258. streamSkipUntil('"'); // Skip mode and format
  259. String res = streamReadUntil('"');
  260. waitResponse();
  261. return res;
  262. }
  263. bool waitForNetwork(unsigned long timeout = 60000L) {
  264. for (unsigned long start = millis(); millis() - start < timeout; ) {
  265. RegStatus s = getRegistrationStatus();
  266. if (s == REG_OK_HOME || s == REG_OK_ROAMING) {
  267. return true;
  268. }
  269. delay(1000);
  270. }
  271. return false;
  272. }
  273. /*
  274. * WiFi functions
  275. */
  276. bool networkConnect(const char* ssid, const char* pwd) {
  277. return false;
  278. }
  279. bool networkDisconnect() {
  280. return false;
  281. }
  282. /*
  283. * GPRS functions
  284. */
  285. bool gprsConnect(const char* apn, const char* user, const char* pwd) {
  286. gprsDisconnect();
  287. sendAT(GF("+CGDCONT=1,\"IP\",\""), apn, '"');
  288. waitResponse();
  289. sendAT(GF("+CSTT=\""), apn, GF("\",\""), user, GF("\",\""), pwd, GF("\""));
  290. if (waitResponse(60000L) != 1) {
  291. return false;
  292. }
  293. sendAT(GF("+CGACT=1,1"));
  294. waitResponse(60000L);
  295. sendAT(GF("+CGATT=1"));
  296. if (waitResponse(60000L) != 1)
  297. return false;
  298. // TODO: wait AT+CGATT?
  299. sendAT(GF("+CIPMUX=1"));
  300. if (waitResponse() != 1) {
  301. return false;
  302. }
  303. /*sendAT(GF("+CIFSR"));
  304. String data;
  305. if (waitResponse(10000L, data) != 1) {
  306. data.replace(GSM_NL, "");
  307. return false;
  308. }*/
  309. return true;
  310. }
  311. bool gprsDisconnect() {
  312. sendAT(GF("+CIPSHUT"));
  313. return waitResponse(60000L) == 1;
  314. }
  315. /*
  316. * Phone Call functions
  317. */
  318. bool callAnswer() {
  319. sendAT(GF("A"));
  320. return waitResponse() == 1;
  321. }
  322. bool callNumber(const String& number) {
  323. sendAT(GF("D"), number);
  324. return waitResponse() == 1;
  325. }
  326. bool callHangup(const String& number) {
  327. sendAT(GF("H"), number);
  328. return waitResponse() == 1;
  329. }
  330. /*
  331. * Messaging functions
  332. */
  333. void sendUSSD() {
  334. }
  335. void sendSMS() {
  336. }
  337. bool sendSMS(const String& number, const String& text) {
  338. sendAT(GF("+CMGF=1"));
  339. waitResponse();
  340. sendAT(GF("+CMGS=\""), number, GF("\""));
  341. if (waitResponse(GF(">")) != 1) {
  342. return false;
  343. }
  344. stream.print(text);
  345. stream.write((char)0x1A);
  346. return waitResponse(60000L) == 1;
  347. }
  348. /*
  349. * Location functions
  350. */
  351. void getLocation() {
  352. }
  353. /*
  354. * Battery functions
  355. */
  356. /* Public Utilities */
  357. template<typename... Args>
  358. void sendAT(Args... cmd) {
  359. streamWrite("AT", cmd..., GSM_NL);
  360. stream.flush();
  361. TINY_GSM_YIELD();
  362. DBG(GSM_NL, ">>> AT:", cmd...);
  363. }
  364. // TODO: Optimize this!
  365. uint8_t waitResponse(uint32_t timeout, String& data,
  366. GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  367. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  368. {
  369. /*String r1s(r1); r1s.trim();
  370. String r2s(r2); r2s.trim();
  371. String r3s(r3); r3s.trim();
  372. String r4s(r4); r4s.trim();
  373. String r5s(r5); r5s.trim();
  374. DBG("### ..:", r1s, ",", r2s, ",", r3s, ",", r4s, ",", r5s);*/
  375. data.reserve(64);
  376. bool gotData = false;
  377. int mux = -1;
  378. int len = 0;
  379. int index = 0;
  380. unsigned long startMillis = millis();
  381. do {
  382. TINY_GSM_YIELD();
  383. while (stream.available() > 0) {
  384. int a = streamRead();
  385. if (a <= 0) continue; // Skip 0x00 bytes, just in case
  386. data += (char)a;
  387. if (r1 && data.endsWith(r1)) {
  388. index = 1;
  389. goto finish;
  390. } else if (r2 && data.endsWith(r2)) {
  391. index = 2;
  392. goto finish;
  393. } else if (r3 && data.endsWith(r3)) {
  394. index = 3;
  395. goto finish;
  396. } else if (r4 && data.endsWith(r4)) {
  397. index = 4;
  398. goto finish;
  399. } else if (r5 && data.endsWith(r5)) {
  400. index = 5;
  401. goto finish;
  402. } else if (data.endsWith(GF("+CIPRCV:"))) {
  403. mux = stream.readStringUntil(',').toInt();
  404. data += mux;
  405. data += (',');
  406. len = stream.readStringUntil(',').toInt();
  407. data += len;
  408. data += (',');
  409. gotData = true;
  410. index = 6;
  411. goto finish;
  412. } else if (data.endsWith(GF("+TCPCLOSED:"))) {
  413. mux = stream.readStringUntil(',').toInt();
  414. data += mux;
  415. data += (',');
  416. String concl = stream.readStringUntil('\n');
  417. data += concl;
  418. sockets[mux]->sock_connected = false;
  419. index = 7;
  420. goto finish;
  421. }
  422. }
  423. } while (millis() - startMillis < timeout);
  424. finish:
  425. if (!index) {
  426. data.trim();
  427. if (data.length()) {
  428. DBG(GSM_NL, "### Unhandled:", data);
  429. }
  430. }
  431. else {
  432. data.trim();
  433. data.replace(GSM_NL GSM_NL, GSM_NL);
  434. data.replace(GSM_NL, GSM_NL " ");
  435. if (data.length()) {
  436. DBG(GSM_NL, "<<< ", data);
  437. }
  438. }
  439. if (gotData) {
  440. int len_orig = len;
  441. if (len > sockets[mux]->rx.free()) {
  442. DBG(GSM_NL, "### Buffer overflow: ", len, "->", sockets[mux]->rx.free());
  443. } else {
  444. DBG(GSM_NL, "### Got: ", len, "->", sockets[mux]->rx.free());
  445. }
  446. while (len--) {
  447. TINY_GSM_YIELD();
  448. int r = stream.read();
  449. if (r <= 0) continue; // Skip 0x00 bytes, just in case
  450. sockets[mux]->rx.put((char)r);
  451. }
  452. if (len_orig > sockets[mux]->available()) {
  453. DBG(GSM_NL, "### Fewer characters received than expected: ", sockets[mux]->available(), " vs ", len_orig);
  454. }
  455. }
  456. return index;
  457. }
  458. uint8_t waitResponse(uint32_t timeout,
  459. GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  460. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  461. {
  462. String data;
  463. return waitResponse(timeout, data, r1, r2, r3, r4, r5);
  464. }
  465. uint8_t waitResponse(GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  466. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  467. {
  468. return waitResponse(1000, r1, r2, r3, r4, r5);
  469. }
  470. private:
  471. int modemConnect(const char* host, uint16_t port, uint8_t* mux) {
  472. sendAT(GF("+CIPSTART="), GF("\"TCP"), GF("\",\""), host, GF("\","), port);
  473. if (waitResponse(75000L, GF(GSM_NL "+CIPNUM:")) != 1) {
  474. return -1;
  475. }
  476. int newMux = streamReadUntil('\n').toInt();
  477. int rsp = waitResponse(75000L,
  478. GF("CONNECT OK" GSM_NL),
  479. GF("CONNECT FAIL" GSM_NL),
  480. GF("ALREADY CONNECT" GSM_NL));
  481. if (waitResponse() != 1) {
  482. return -1;
  483. }
  484. *mux = newMux;
  485. return (1 == rsp);
  486. }
  487. int modemSend(const void* buff, size_t len, uint8_t mux) {
  488. sendAT(GF("+CIPSEND="), mux, ',', len);
  489. if (waitResponse(10000L, GF(GSM_NL ">")) != 1) {
  490. return -1;
  491. }
  492. stream.write((uint8_t*)buff, len);
  493. stream.flush();
  494. if (waitResponse(10000L, GFP(GSM_OK), GF(GSM_NL "FAIL")) != 1) {
  495. return -1;
  496. }
  497. return len;
  498. }
  499. bool modemGetConnected(uint8_t mux) { //TODO mux?
  500. sendAT(GF("+CIPSTATUS"));
  501. int res = waitResponse(GF(",\"CONNECTED\""), GF(",\"CLOSED\""), GF(",\"CLOSING\""), GF(",\"INITIAL\""));
  502. waitResponse();
  503. return 1 == res;
  504. }
  505. /* Private Utilities */
  506. template<typename T>
  507. void streamWrite(T last) {
  508. stream.print(last);
  509. }
  510. template<typename T, typename... Args>
  511. void streamWrite(T head, Args... tail) {
  512. stream.print(head);
  513. streamWrite(tail...);
  514. }
  515. int streamRead() { return stream.read(); }
  516. String streamReadUntil(char c) {
  517. String return_string = stream.readStringUntil(c);
  518. return_string.trim();
  519. if (String(c) == GSM_NL || String(c) == "\n"){
  520. DBG(return_string, c, " ");
  521. } else DBG(return_string, c);
  522. return return_string;
  523. }
  524. bool streamSkipUntil(char c) {
  525. String skipped = stream.readStringUntil(c);
  526. skipped.trim();
  527. if (skipped.length()) {
  528. if (String(c) == GSM_NL || String(c) == "\n"){
  529. DBG(skipped, c, " ");
  530. } else DBG(skipped, c);
  531. return true;
  532. } else return false;
  533. }
  534. private:
  535. Stream& stream;
  536. GsmClient* sockets[8];
  537. };
  538. typedef TinyGsm::GsmClient TinyGsmClient;
  539. #endif