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