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.

597 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("+CGDCONT=1,\"IP\",\""), apn, '"');
  292. waitResponse();
  293. sendAT(GF("+CSTT=\""), apn, GF("\",\""), user, GF("\",\""), pwd, GF("\""));
  294. if (waitResponse(60000L) != 1) {
  295. return false;
  296. }
  297. sendAT(GF("+CGACT=1,1"));
  298. waitResponse(60000L);
  299. sendAT(GF("+CGATT=1"));
  300. if (waitResponse(60000L) != 1)
  301. return false;
  302. // TODO: wait AT+CGATT?
  303. sendAT(GF("+CIPMUX=1"));
  304. if (waitResponse() != 1) {
  305. return false;
  306. }
  307. /*
  308. sendAT(GF("+CIFSR"));
  309. String data;
  310. if (waitResponse(10000L, data) != 1) {
  311. data.replace(GSM_NL, "");
  312. return false;
  313. }
  314. */
  315. return true;
  316. }
  317. bool gprsDisconnect() {
  318. sendAT(GF("+CIPSHUT"));
  319. return waitResponse(60000L) == 1;
  320. }
  321. /*
  322. * Phone Call functions
  323. */
  324. bool setGsmBusy(bool busy = true) TINY_GSM_ATTR_NOT_AVAILABLE;
  325. bool callAnswer() {
  326. sendAT(GF("A"));
  327. return waitResponse() == 1;
  328. }
  329. bool callNumber(const String& number) {
  330. sendAT(GF("D"), number);
  331. return waitResponse() == 1;
  332. }
  333. void callRedial() {
  334. sendAT(GF("DLST"));
  335. return waitResponse() == 1;
  336. }
  337. bool callHangup(const String& number) {
  338. sendAT(GF("H"), number);
  339. return waitResponse() == 1;
  340. }
  341. /*
  342. * Messaging functions
  343. */
  344. void sendUSSD() TINY_GSM_ATTR_NOT_IMPLEMENTED;
  345. bool sendSMS(const String& number, const String& text) {
  346. sendAT(GF("+CMGF=1"));
  347. waitResponse();
  348. sendAT(GF("+CMGS=\""), number, GF("\""));
  349. if (waitResponse(GF(">")) != 1) {
  350. return false;
  351. }
  352. stream.print(text);
  353. stream.write((char)0x1A);
  354. stream.flush();
  355. return waitResponse(60000L) == 1;
  356. }
  357. /*
  358. * Location functions
  359. */
  360. String getGsmLocation() TINY_GSM_ATTR_NOT_AVAILABLE;
  361. /*
  362. * Battery functions
  363. */
  364. private:
  365. bool modemConnect(const char* host, uint16_t port, uint8_t* mux) {
  366. sendAT(GF("+CIPSTART="), GF("\"TCP"), GF("\",\""), host, GF("\","), port);
  367. if (waitResponse(75000L, GF(GSM_NL "+CIPNUM:")) != 1) {
  368. return false;
  369. }
  370. int newMux = stream.readStringUntil('\n').toInt();
  371. int rsp = waitResponse(75000L,
  372. GF("CONNECT OK" GSM_NL),
  373. GF("CONNECT FAIL" GSM_NL),
  374. GF("ALREADY CONNECT" GSM_NL));
  375. if (waitResponse() != 1) {
  376. return false;
  377. }
  378. *mux = newMux;
  379. return (1 == rsp);
  380. }
  381. int modemSend(const void* buff, size_t len, uint8_t mux) {
  382. sendAT(GF("+CIPSEND="), mux, ',', len);
  383. if (waitResponse(2000L, GF(GSM_NL ">")) != 1) {
  384. return -1;
  385. }
  386. stream.write((uint8_t*)buff, len);
  387. stream.flush();
  388. if (waitResponse(10000L, GFP(GSM_OK), GF(GSM_NL "FAIL")) != 1) {
  389. return -1;
  390. }
  391. return len;
  392. }
  393. bool modemGetConnected(uint8_t mux) { //TODO mux?
  394. sendAT(GF("+CIPSTATUS"));
  395. int res = waitResponse(GF(",\"CONNECTED\""), GF(",\"CLOSED\""), GF(",\"CLOSING\""), GF(",\"INITIAL\""));
  396. waitResponse();
  397. return 1 == res;
  398. }
  399. public:
  400. /* Utilities */
  401. template<typename T>
  402. void streamWrite(T last) {
  403. stream.print(last);
  404. }
  405. template<typename T, typename... Args>
  406. void streamWrite(T head, Args... tail) {
  407. stream.print(head);
  408. streamWrite(tail...);
  409. }
  410. bool streamSkipUntil(char c) { //TODO: timeout
  411. while (true) {
  412. while (!stream.available()) { TINY_GSM_YIELD(); }
  413. if (stream.read() == c)
  414. return true;
  415. }
  416. return false;
  417. }
  418. template<typename... Args>
  419. void sendAT(Args... cmd) {
  420. streamWrite("AT", cmd..., GSM_NL);
  421. stream.flush();
  422. TINY_GSM_YIELD();
  423. //DBG("### AT:", cmd...);
  424. }
  425. // TODO: Optimize this!
  426. uint8_t waitResponse(uint32_t timeout, String& data,
  427. GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  428. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  429. {
  430. /*String r1s(r1); r1s.trim();
  431. String r2s(r2); r2s.trim();
  432. String r3s(r3); r3s.trim();
  433. String r4s(r4); r4s.trim();
  434. String r5s(r5); r5s.trim();
  435. DBG("### ..:", r1s, ",", r2s, ",", r3s, ",", r4s, ",", r5s);*/
  436. data.reserve(64);
  437. int index = 0;
  438. unsigned long startMillis = millis();
  439. do {
  440. TINY_GSM_YIELD();
  441. while (stream.available() > 0) {
  442. int a = stream.read();
  443. if (a <= 0) continue; // Skip 0x00 bytes, just in case
  444. data += (char)a;
  445. if (r1 && data.endsWith(r1)) {
  446. index = 1;
  447. goto finish;
  448. } else if (r2 && data.endsWith(r2)) {
  449. index = 2;
  450. goto finish;
  451. } else if (r3 && data.endsWith(r3)) {
  452. index = 3;
  453. goto finish;
  454. } else if (r4 && data.endsWith(r4)) {
  455. index = 4;
  456. goto finish;
  457. } else if (r5 && data.endsWith(r5)) {
  458. index = 5;
  459. goto finish;
  460. } else if (data.endsWith(GF("+CIPRCV:"))) {
  461. int mux = stream.readStringUntil(',').toInt();
  462. int len = stream.readStringUntil(',').toInt();
  463. if (len > sockets[mux]->rx.free()) {
  464. DBG("### Buffer overflow: ", len, "->", sockets[mux]->rx.free());
  465. } else {
  466. DBG("### Got: ", len, "->", sockets[mux]->rx.free());
  467. }
  468. while (len--) {
  469. while (!stream.available()) { TINY_GSM_YIELD(); }
  470. sockets[mux]->rx.put(stream.read());
  471. }
  472. data = "";
  473. } else if (data.endsWith(GF("+TCPCLOSED:"))) {
  474. int mux = stream.readStringUntil('\n').toInt();
  475. sockets[mux]->sock_connected = false;
  476. data = "";
  477. DBG("### Closed: ", mux);
  478. }
  479. }
  480. } while (millis() - startMillis < timeout);
  481. finish:
  482. if (!index) {
  483. data.trim();
  484. if (data.length()) {
  485. DBG("### Unhandled:", data);
  486. }
  487. data = "";
  488. }
  489. return index;
  490. }
  491. uint8_t waitResponse(uint32_t timeout,
  492. GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  493. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  494. {
  495. String data;
  496. return waitResponse(timeout, data, r1, r2, r3, r4, r5);
  497. }
  498. uint8_t waitResponse(GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  499. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  500. {
  501. return waitResponse(1000, r1, r2, r3, r4, r5);
  502. }
  503. private:
  504. Stream& stream;
  505. GsmClient* sockets[TINY_GSM_MUX_COUNT];
  506. };
  507. typedef TinyGsm::GsmClient TinyGsmClient;
  508. #endif