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.

615 lines
14 KiB

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