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.

619 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 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. SimStatus getSimStatus(unsigned long timeout = 10000L) {
  217. for (unsigned long start = millis(); millis() - start < timeout; ) {
  218. sendAT(GF("+CPIN?"));
  219. if (waitResponse(GF(GSM_NL "+CPIN:")) != 1) {
  220. delay(1000);
  221. continue;
  222. }
  223. int status = waitResponse(GF("READY"), GF("SIM PIN"), GF("SIM PUK"));
  224. waitResponse();
  225. switch (status) {
  226. case 2:
  227. case 3: return SIM_LOCKED;
  228. case 1: return SIM_READY;
  229. default: return SIM_ERROR;
  230. }
  231. }
  232. return SIM_ERROR;
  233. }
  234. RegStatus getRegistrationStatus() {
  235. sendAT(GF("+CREG?"));
  236. if (waitResponse(GF(GSM_NL "+CREG:")) != 1) {
  237. return REG_UNKNOWN;
  238. }
  239. streamSkipUntil(','); // Skip format (0)
  240. int status = streamReadUntil('\n').toInt();
  241. waitResponse();
  242. return (RegStatus)status;
  243. }
  244. String getOperator() {
  245. sendAT(GF("+COPS?"));
  246. if (waitResponse(GF(GSM_NL "+COPS:")) != 1) {
  247. return "";
  248. }
  249. streamSkipUntil('"'); // Skip mode and format
  250. String res = streamReadUntil('"');
  251. waitResponse();
  252. return res;
  253. }
  254. /*
  255. * Generic network functions
  256. */
  257. int getSignalQuality() {
  258. sendAT(GF("+CSQ"));
  259. if (waitResponse(GF(GSM_NL "+CSQ:")) != 1) {
  260. return 99;
  261. }
  262. int res = streamReadUntil(',').toInt();
  263. waitResponse();
  264. return res;
  265. }
  266. bool waitForNetwork(unsigned long timeout = 60000L) {
  267. for (unsigned long start = millis(); millis() - start < timeout; ) {
  268. RegStatus s = getRegistrationStatus();
  269. if (s == REG_OK_HOME || s == REG_OK_ROAMING) {
  270. return true;
  271. }
  272. delay(1000);
  273. }
  274. return false;
  275. }
  276. /*
  277. * WiFi functions
  278. */
  279. bool networkConnect(const char* ssid, const char* pwd) {
  280. return false;
  281. }
  282. bool networkDisconnect() {
  283. return false;
  284. }
  285. /*
  286. * GPRS functions
  287. */
  288. bool gprsConnect(const char* apn, const char* user, const char* pwd) {
  289. gprsDisconnect();
  290. sendAT(GF("+CGDCONT=1,\"IP\",\""), apn, '"');
  291. waitResponse();
  292. sendAT(GF("+CSTT=\""), apn, GF("\",\""), user, GF("\",\""), pwd, GF("\""));
  293. if (waitResponse(60000L) != 1) {
  294. return false;
  295. }
  296. sendAT(GF("+CGACT=1,1"));
  297. waitResponse(60000L);
  298. sendAT(GF("+CGATT=1"));
  299. if (waitResponse(60000L) != 1)
  300. return false;
  301. // TODO: wait AT+CGATT?
  302. sendAT(GF("+CIPMUX=1"));
  303. if (waitResponse() != 1) {
  304. return false;
  305. }
  306. /*sendAT(GF("+CIFSR"));
  307. String data;
  308. if (waitResponse(10000L, data) != 1) {
  309. data.replace(GSM_NL, "");
  310. return false;
  311. }*/
  312. return true;
  313. }
  314. bool gprsDisconnect() {
  315. sendAT(GF("+CIPSHUT"));
  316. return waitResponse(60000L) == 1;
  317. }
  318. /*
  319. * Phone Call functions
  320. */
  321. bool callAnswer() {
  322. sendAT(GF("A"));
  323. return waitResponse() == 1;
  324. }
  325. bool callNumber(const String& number) {
  326. sendAT(GF("D"), number);
  327. return waitResponse() == 1;
  328. }
  329. bool callHangup(const String& number) {
  330. sendAT(GF("H"), number);
  331. return waitResponse() == 1;
  332. }
  333. /*
  334. * Messaging functions
  335. */
  336. bool sendSMS(const String& number, const String& text) {
  337. sendAT(GF("+CMGF=1"));
  338. waitResponse();
  339. sendAT(GF("+CMGS=\""), number, GF("\""));
  340. if (waitResponse(GF(">")) != 1) {
  341. return false;
  342. }
  343. stream.print(text);
  344. stream.write((char)0x1A);
  345. return waitResponse(60000L) == 1;
  346. }
  347. /*
  348. * Location functions
  349. */
  350. /*
  351. * Battery functions
  352. */
  353. private:
  354. int modemConnect(const char* host, uint16_t port, uint8_t* mux) {
  355. sendAT(GF("+CIPSTART="), GF("\"TCP"), GF("\",\""), host, GF("\","), port);
  356. if (waitResponse(75000L, GF(GSM_NL "+CIPNUM:")) != 1) {
  357. return -1;
  358. }
  359. int newMux = streamReadUntil('\n').toInt();
  360. int rsp = waitResponse(75000L,
  361. GF("CONNECT OK" GSM_NL),
  362. GF("CONNECT FAIL" GSM_NL),
  363. GF("ALREADY CONNECT" GSM_NL));
  364. if (waitResponse() != 1) {
  365. return -1;
  366. }
  367. *mux = newMux;
  368. return (1 == rsp);
  369. }
  370. int modemSend(const void* buff, size_t len, uint8_t mux) {
  371. sendAT(GF("+CIPSEND="), mux, ',', len);
  372. if (waitResponse(10000L, GF(GSM_NL ">")) != 1) {
  373. return -1;
  374. }
  375. stream.write((uint8_t*)buff, len);
  376. stream.flush();
  377. if (waitResponse(10000L, GFP(GSM_OK), GF(GSM_NL "FAIL")) != 1) {
  378. return -1;
  379. }
  380. return len;
  381. }
  382. bool modemGetConnected(uint8_t mux) { //TODO mux?
  383. sendAT(GF("+CIPSTATUS"));
  384. int res = waitResponse(GF(",\"CONNECTED\""), GF(",\"CLOSED\""), GF(",\"CLOSING\""), GF(",\"INITIAL\""));
  385. waitResponse();
  386. return 1 == res;
  387. }
  388. /* Private Utilities */
  389. template<typename T>
  390. void streamWrite(T last) {
  391. stream.print(last);
  392. }
  393. template<typename T, typename... Args>
  394. void streamWrite(T head, Args... tail) {
  395. stream.print(head);
  396. streamWrite(tail...);
  397. }
  398. int streamRead() { return stream.read(); }
  399. String streamReadUntil(char c) {
  400. String return_string = stream.readStringUntil(c);
  401. return_string.trim();
  402. if (String(c) == GSM_NL || String(c) == "\n"){
  403. DBG(return_string, c, " ");
  404. } else DBG(return_string, c);
  405. return return_string;
  406. }
  407. bool streamSkipUntil(char c) {
  408. String skipped = stream.readStringUntil(c);
  409. skipped.trim();
  410. if (skipped.length()) {
  411. if (String(c) == GSM_NL || String(c) == "\n"){
  412. DBG(skipped, c, " ");
  413. } else DBG(skipped, c);
  414. return true;
  415. } else return false;
  416. }
  417. template<typename... Args>
  418. void sendAT(Args... cmd) {
  419. streamWrite("AT", cmd..., GSM_NL);
  420. stream.flush();
  421. TINY_GSM_YIELD();
  422. DBG(GSM_NL, ">>> AT:", cmd...);
  423. }
  424. // TODO: Optimize this!
  425. uint8_t waitResponse(uint32_t timeout, String& data,
  426. GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  427. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  428. {
  429. /*String r1s(r1); r1s.trim();
  430. String r2s(r2); r2s.trim();
  431. String r3s(r3); r3s.trim();
  432. String r4s(r4); r4s.trim();
  433. String r5s(r5); r5s.trim();
  434. DBG("### ..:", r1s, ",", r2s, ",", r3s, ",", r4s, ",", r5s);*/
  435. data.reserve(64);
  436. bool gotData = false;
  437. int mux = -1;
  438. int len = 0;
  439. int index = 0;
  440. unsigned long startMillis = millis();
  441. do {
  442. TINY_GSM_YIELD();
  443. while (stream.available() > 0) {
  444. int a = streamRead();
  445. if (a <= 0) continue; // Skip 0x00 bytes, just in case
  446. data += (char)a;
  447. if (r1 && data.endsWith(r1)) {
  448. index = 1;
  449. goto finish;
  450. } else if (r2 && data.endsWith(r2)) {
  451. index = 2;
  452. goto finish;
  453. } else if (r3 && data.endsWith(r3)) {
  454. index = 3;
  455. goto finish;
  456. } else if (r4 && data.endsWith(r4)) {
  457. index = 4;
  458. goto finish;
  459. } else if (r5 && data.endsWith(r5)) {
  460. index = 5;
  461. goto finish;
  462. } else if (data.endsWith(GF("+CIPRCV:"))) {
  463. mux = stream.readStringUntil(',').toInt();
  464. data += mux;
  465. data += (',');
  466. len = stream.readStringUntil(',').toInt();
  467. data += len;
  468. data += (',');
  469. gotData = true;
  470. index = 6;
  471. goto finish;
  472. } else if (data.endsWith(GF("+TCPCLOSED:"))) {
  473. mux = stream.readStringUntil(',').toInt();
  474. data += mux;
  475. data += (',');
  476. String concl = stream.readStringUntil('\n');
  477. data += concl;
  478. sockets[mux]->sock_connected = false;
  479. index = 7;
  480. goto finish;
  481. }
  482. }
  483. } while (millis() - startMillis < timeout);
  484. finish:
  485. if (!index) {
  486. data.trim();
  487. if (data.length()) {
  488. DBG(GSM_NL, "### Unhandled:", data);
  489. }
  490. }
  491. else {
  492. data.trim();
  493. data.replace(GSM_NL GSM_NL, GSM_NL);
  494. data.replace(GSM_NL, GSM_NL " ");
  495. if (data.length()) {
  496. DBG(GSM_NL, "<<< ", data);
  497. }
  498. }
  499. if (gotData) {
  500. int len_orig = len;
  501. if (len > sockets[mux]->rx.free()) {
  502. DBG(GSM_NL, "### Buffer overflow: ", len, "->", sockets[mux]->rx.free());
  503. } else {
  504. DBG(GSM_NL, "### Got: ", len, "->", sockets[mux]->rx.free());
  505. }
  506. while (len--) {
  507. TINY_GSM_YIELD();
  508. int r = stream.read();
  509. if (r <= 0) continue; // Skip 0x00 bytes, just in case
  510. sockets[mux]->rx.put((char)r);
  511. }
  512. if (len_orig > sockets[mux]->available()) {
  513. DBG(GSM_NL, "### Fewer characters received than expected: ", sockets[mux]->available(), " vs ", len_orig);
  514. }
  515. }
  516. return index;
  517. }
  518. uint8_t waitResponse(uint32_t timeout,
  519. GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  520. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  521. {
  522. String data;
  523. return waitResponse(timeout, data, r1, r2, r3, r4, r5);
  524. }
  525. uint8_t waitResponse(GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  526. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  527. {
  528. return waitResponse(1000, r1, r2, r3, r4, r5);
  529. }
  530. private:
  531. Stream& stream;
  532. GsmClient* sockets[8];
  533. };
  534. typedef TinyGsm::GsmClient TinyGsmClient;
  535. #endif