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.

609 lines
14 KiB

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