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.

669 lines
15 KiB

8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
  1. /**
  2. * @file TinyGsmClient.h
  3. * @author Volodymyr Shymanskyy
  4. * @license LGPL-3.0
  5. * @copyright Copyright (c) 2016 Volodymyr Shymanskyy
  6. * @date Nov 2016
  7. */
  8. #ifndef TinyGsmClient_h
  9. #define TinyGsmClient_h
  10. #if defined(SPARK) || defined(PARTICLE)
  11. #include "Particle.h"
  12. #elif defined(ARDUINO)
  13. #if ARDUINO >= 100
  14. #include "Arduino.h"
  15. #else
  16. #include "WProgram.h"
  17. #endif
  18. #endif
  19. #include <Client.h>
  20. #include <TinyGsmFifo.h>
  21. #if defined(__AVR__)
  22. #define TINY_GSM_PROGMEM PROGMEM
  23. typedef const __FlashStringHelper* GsmConstStr;
  24. #define GFP(x) (reinterpret_cast<GsmConstStr>(x))
  25. #define GF(x) F(x)
  26. #else
  27. #define TINY_GSM_PROGMEM
  28. typedef const char* GsmConstStr;
  29. #define GFP(x) x
  30. #define GF(x) x
  31. #endif
  32. //#define GSM_DEBUG Serial
  33. //#define GSM_USE_HEX
  34. #if !defined(TINY_GSM_RX_BUFFER)
  35. #define TINY_GSM_RX_BUFFER 64
  36. #endif
  37. #define GSM_NL "\r\n"
  38. static const char GSM_OK[] TINY_GSM_PROGMEM = "OK" GSM_NL;
  39. static const char GSM_ERROR[] TINY_GSM_PROGMEM = "ERROR" GSM_NL;
  40. #define TINY_GSM_YIELD() delay(0)
  41. enum SimStatus {
  42. SIM_ERROR = 0,
  43. SIM_READY = 1,
  44. SIM_LOCKED = 2,
  45. };
  46. enum RegStatus {
  47. REG_UNREGISTERED = 0,
  48. REG_SEARCHING = 2,
  49. REG_DENIED = 3,
  50. REG_OK_HOME = 1,
  51. REG_OK_ROAMING = 5,
  52. REG_UNKNOWN = 4,
  53. };
  54. class TinyGsm
  55. {
  56. #ifdef GSM_DEBUG
  57. template<typename T>
  58. static void DBG(T last) {
  59. GSM_DEBUG.println(last);
  60. }
  61. template<typename T, typename... Args>
  62. static void DBG(T head, Args... tail) {
  63. GSM_DEBUG.print(head);
  64. GSM_DEBUG.print(' ');
  65. DBG(tail...);
  66. }
  67. #else
  68. #define DBG(...)
  69. #endif
  70. public:
  71. TinyGsm(Stream& stream)
  72. : stream(stream)
  73. {}
  74. public:
  75. class GsmClient : public Client
  76. {
  77. friend class TinyGsm;
  78. typedef TinyGsmFifo<uint8_t, TINY_GSM_RX_BUFFER> RxFifo;
  79. public:
  80. GsmClient() {}
  81. GsmClient(TinyGsm& modem, uint8_t mux = 1) {
  82. init(&modem, mux);
  83. }
  84. bool init(TinyGsm* modem, uint8_t mux = 1) {
  85. this->at = modem;
  86. this->mux = mux;
  87. sock_available = 0;
  88. sock_connected = false;
  89. at->sockets[mux] = this;
  90. return true;
  91. }
  92. public:
  93. virtual int connect(const char *host, uint16_t port) {
  94. TINY_GSM_YIELD();
  95. rx.clear();
  96. sock_connected = at->modemConnect(host, port, mux);
  97. return sock_connected;
  98. }
  99. virtual int connect(IPAddress ip, uint16_t port) {
  100. String host; host.reserve(16);
  101. host += ip[0];
  102. host += ".";
  103. host += ip[1];
  104. host += ".";
  105. host += ip[2];
  106. host += ".";
  107. host += ip[3];
  108. return connect(host.c_str(), port);
  109. }
  110. virtual void stop() {
  111. TINY_GSM_YIELD();
  112. at->sendAT(GF("+CIPCLOSE="), mux);
  113. sock_connected = false;
  114. at->waitResponse();
  115. }
  116. virtual size_t write(const uint8_t *buf, size_t size) {
  117. TINY_GSM_YIELD();
  118. at->maintain();
  119. return at->modemSend(buf, size, mux);
  120. }
  121. virtual size_t write(uint8_t c) {
  122. return write(&c, 1);
  123. }
  124. virtual int available() {
  125. TINY_GSM_YIELD();
  126. if (!rx.size()) {
  127. at->maintain();
  128. }
  129. return rx.size() + sock_available;
  130. }
  131. virtual int read(uint8_t *buf, size_t size) {
  132. TINY_GSM_YIELD();
  133. at->maintain();
  134. size_t cnt = 0;
  135. while (cnt < size) {
  136. size_t chunk = min(size-cnt, rx.size());
  137. if (chunk > 0) {
  138. rx.get(buf, chunk);
  139. buf += chunk;
  140. cnt += chunk;
  141. continue;
  142. }
  143. // TODO: Read directly into user buffer?
  144. at->maintain();
  145. if (sock_available > 0) {
  146. at->modemRead(rx.free(), mux);
  147. } else {
  148. break;
  149. }
  150. }
  151. return cnt;
  152. }
  153. virtual int read() {
  154. uint8_t c;
  155. if (read(&c, 1) == 1) {
  156. return c;
  157. }
  158. return -1;
  159. }
  160. virtual int peek() { return -1; } //TODO
  161. virtual void flush() { at->stream.flush(); }
  162. virtual uint8_t connected() {
  163. if (available()) {
  164. return true;
  165. }
  166. return sock_connected;
  167. }
  168. virtual operator bool() { return connected(); }
  169. private:
  170. TinyGsm* at;
  171. uint8_t mux;
  172. uint16_t sock_available;
  173. bool sock_connected;
  174. RxFifo rx;
  175. };
  176. public:
  177. /*
  178. * Basic functions
  179. */
  180. bool begin() {
  181. return init();
  182. }
  183. bool init() {
  184. if (!autoBaud()) {
  185. return false;
  186. }
  187. sendAT(GF("&FZE0")); // Factory + Reset + Echo Off
  188. if (waitResponse() != 1) {
  189. return false;
  190. }
  191. getSimStatus();
  192. return true;
  193. }
  194. bool autoBaud(unsigned long timeout = 10000L) {
  195. for (unsigned long start = millis(); millis() - start < timeout; ) {
  196. sendAT(GF(""));
  197. if (waitResponse(200) == 1) {
  198. delay(100);
  199. return true;
  200. }
  201. delay(100);
  202. }
  203. return false;
  204. }
  205. void maintain() {
  206. while (stream.available()) {
  207. waitResponse(10, NULL, NULL);
  208. }
  209. }
  210. bool factoryDefault() {
  211. sendAT(GF("&FZE0&W")); // Factory + Reset + Echo Off + Write
  212. waitResponse();
  213. sendAT(GF("+IPR=0")); // Auto-baud
  214. waitResponse();
  215. sendAT(GF("+IFC=0,0")); // No Flow Control
  216. waitResponse();
  217. sendAT(GF("+ICF=3,3")); // 8 data 0 parity 1 stop
  218. waitResponse();
  219. sendAT(GF("+CSCLK=0")); // Disable Slow Clock
  220. waitResponse();
  221. sendAT(GF("&W")); // Write configuration
  222. return waitResponse() == 1;
  223. }
  224. /*
  225. * Power functions
  226. */
  227. bool restart() {
  228. if (!autoBaud()) {
  229. return false;
  230. }
  231. sendAT(GF("+CFUN=0"));
  232. if (waitResponse(10000L) != 1) {
  233. return false;
  234. }
  235. sendAT(GF("+CFUN=1,1"));
  236. if (waitResponse(10000L) != 1) {
  237. return false;
  238. }
  239. delay(3000);
  240. return init();
  241. }
  242. /*
  243. * SIM card & Networ Operator functions
  244. */
  245. bool simUnlock(const char *pin) {
  246. sendAT(GF("+CPIN=\""), pin, GF("\""));
  247. return waitResponse() == 1;
  248. }
  249. String getSimCCID() {
  250. sendAT(GF("+ICCID"));
  251. if (waitResponse(GF(GSM_NL "+ICCID:")) != 1) {
  252. return "";
  253. }
  254. String res = stream.readStringUntil('\n');
  255. waitResponse();
  256. res.trim();
  257. return res;
  258. }
  259. SimStatus getSimStatus(unsigned long timeout = 10000L) {
  260. for (unsigned long start = millis(); millis() - start < timeout; ) {
  261. sendAT(GF("+CPIN?"));
  262. if (waitResponse(GF(GSM_NL "+CPIN:")) != 1) {
  263. delay(1000);
  264. continue;
  265. }
  266. int status = waitResponse(GF("READY"), GF("SIM PIN"), GF("SIM PUK"), GF("NOT INSERTED"));
  267. waitResponse();
  268. switch (status) {
  269. case 2:
  270. case 3: return SIM_LOCKED;
  271. case 1: return SIM_READY;
  272. default: return SIM_ERROR;
  273. }
  274. }
  275. return SIM_ERROR;
  276. }
  277. RegStatus getRegistrationStatus() {
  278. sendAT(GF("+CREG?"));
  279. if (waitResponse(GF(GSM_NL "+CREG:")) != 1) {
  280. return REG_UNKNOWN;
  281. }
  282. streamSkipUntil(','); // Skip format (0)
  283. int status = stream.readStringUntil('\n').toInt();
  284. waitResponse();
  285. return (RegStatus)status;
  286. }
  287. String getOperator() {
  288. sendAT(GF("+COPS?"));
  289. if (waitResponse(GF(GSM_NL "+COPS:")) != 1) {
  290. return "";
  291. }
  292. streamSkipUntil('"'); // Skip mode and format
  293. String res = stream.readStringUntil('"');
  294. waitResponse();
  295. return res;
  296. }
  297. bool waitForNetwork(unsigned long timeout = 60000L) {
  298. for (unsigned long start = millis(); millis() - start < timeout; ) {
  299. RegStatus s = getRegistrationStatus();
  300. if (s == REG_OK_HOME || s == REG_OK_ROAMING) {
  301. return true;
  302. } else if (s == REG_UNREGISTERED) {
  303. return false;
  304. }
  305. delay(1000);
  306. }
  307. return false;
  308. }
  309. /*
  310. * GPRS functions
  311. */
  312. bool gprsConnect(const char* apn, const char* user, const char* pwd) {
  313. gprsDisconnect();
  314. sendAT(GF("+SAPBR=3,1,\"Contype\",\"GPRS\""));
  315. waitResponse();
  316. sendAT(GF("+SAPBR=3,1,\"APN\",\""), apn, '"');
  317. waitResponse();
  318. if (user) {
  319. sendAT(GF("+SAPBR=3,1,\"USER\",\""), user, '"');
  320. waitResponse();
  321. }
  322. if (pwd) {
  323. sendAT(GF("+SAPBR=3,1,\"PWD\",\""), pwd, '"');
  324. waitResponse();
  325. }
  326. sendAT(GF("+CGDCONT=1,\"IP\",\""), apn, '"');
  327. waitResponse();
  328. sendAT(GF("+CGACT=1,1"));
  329. waitResponse(60000L);
  330. // Open a GPRS context
  331. sendAT(GF("+SAPBR=1,1"));
  332. waitResponse(85000L);
  333. // Query the GPRS context
  334. sendAT(GF("+SAPBR=2,1"));
  335. if (waitResponse(30000L) != 1)
  336. return false;
  337. sendAT(GF("+CGATT=1"));
  338. if (waitResponse(60000L) != 1)
  339. return false;
  340. // TODO: wait AT+CGATT?
  341. sendAT(GF("+CIPMUX=1"));
  342. if (waitResponse() != 1) {
  343. return false;
  344. }
  345. sendAT(GF("+CIPQSEND=1"));
  346. if (waitResponse() != 1) {
  347. return false;
  348. }
  349. sendAT(GF("+CIPRXGET=1"));
  350. if (waitResponse() != 1) {
  351. return false;
  352. }
  353. sendAT(GF("+CSTT=\""), apn, GF("\",\""), user, GF("\",\""), pwd, GF("\""));
  354. if (waitResponse(60000L) != 1) {
  355. return false;
  356. }
  357. sendAT(GF("+CIICR"));
  358. if (waitResponse(60000L) != 1) {
  359. return false;
  360. }
  361. sendAT(GF("+CIFSR;E0"));
  362. String data;
  363. if (waitResponse(10000L, data) != 1) {
  364. data.replace(GSM_NL, "");
  365. return false;
  366. }
  367. sendAT(GF("+CDNSCFG=\"8.8.8.8\",\"8.8.4.4\""));
  368. if (waitResponse() != 1) {
  369. return false;
  370. }
  371. return true;
  372. }
  373. bool gprsDisconnect() {
  374. sendAT(GF("+CIPSHUT"));
  375. return waitResponse(60000L) == 1;
  376. }
  377. /*
  378. * Phone Call functions
  379. */
  380. /*
  381. * Messaging functions
  382. */
  383. void sendUSSD() {
  384. }
  385. void sendSMS() {
  386. }
  387. /*
  388. * Location functions
  389. */
  390. void getLocation() {
  391. }
  392. /*
  393. * Battery functions
  394. */
  395. private:
  396. int modemConnect(const char* host, uint16_t port, uint8_t mux) {
  397. sendAT(GF("+CIPSTART="), mux, ',', GF("\"TCP"), GF("\",\""), host, GF("\","), port);
  398. int rsp = waitResponse(75000L,
  399. GF("CONNECT OK" GSM_NL),
  400. GF("CONNECT FAIL" GSM_NL),
  401. GF("ALREADY CONNECT" GSM_NL));
  402. return (1 == rsp);
  403. }
  404. int modemSend(const void* buff, size_t len, uint8_t mux) {
  405. sendAT(GF("+CIPSEND="), mux, ',', len);
  406. if (waitResponse(GF(">")) != 1) {
  407. return -1;
  408. }
  409. stream.write((uint8_t*)buff, len);
  410. if (waitResponse(GF(GSM_NL "DATA ACCEPT:")) != 1) {
  411. return -1;
  412. }
  413. streamSkipUntil(','); // Skip mux
  414. return stream.readStringUntil('\n').toInt();
  415. }
  416. size_t modemRead(size_t size, uint8_t mux) {
  417. #ifdef GSM_USE_HEX
  418. sendAT(GF("+CIPRXGET=3,"), mux, ',', size);
  419. if (waitResponse(GF("+CIPRXGET:")) != 1) {
  420. return 0;
  421. }
  422. #else
  423. sendAT(GF("+CIPRXGET=2,"), mux, ',', size);
  424. if (waitResponse(GF("+CIPRXGET:")) != 1) {
  425. return 0;
  426. }
  427. #endif
  428. streamSkipUntil(','); // Skip mode 2/3
  429. streamSkipUntil(','); // Skip mux
  430. size_t len = stream.readStringUntil(',').toInt();
  431. sockets[mux]->sock_available = stream.readStringUntil('\n').toInt();
  432. for (size_t i=0; i<len; i++) {
  433. #ifdef GSM_USE_HEX
  434. while (stream.available() < 2) {}
  435. char buf[4] = { 0, };
  436. buf[0] = stream.read();
  437. buf[1] = stream.read();
  438. char c = strtol(buf, NULL, 16);
  439. #else
  440. while (!stream.available()) {}
  441. char c = stream.read();
  442. #endif
  443. sockets[mux]->rx.put(c);
  444. }
  445. waitResponse();
  446. return len;
  447. }
  448. size_t modemGetAvailable(uint8_t mux) {
  449. sendAT(GF("+CIPRXGET=4,"), mux);
  450. size_t result = 0;
  451. if (waitResponse(GF("+CIPRXGET:")) == 1) {
  452. streamSkipUntil(','); // Skip mode 4
  453. streamSkipUntil(','); // Skip mux
  454. result = stream.readStringUntil('\n').toInt();
  455. waitResponse();
  456. }
  457. if (!result) {
  458. sockets[mux]->sock_connected = modemGetConnected(mux);
  459. }
  460. return result;
  461. }
  462. bool modemGetConnected(uint8_t mux) {
  463. sendAT(GF("+CIPSTATUS="), mux);
  464. int res = waitResponse(GF(",\"CONNECTED\""), GF(",\"CLOSED\""), GF(",\"CLOSING\""), GF(",\"INITIAL\""));
  465. waitResponse();
  466. return 1 == res;
  467. }
  468. /* Utilities */
  469. template<typename T>
  470. void streamWrite(T last) {
  471. stream.print(last);
  472. }
  473. template<typename T, typename... Args>
  474. void streamWrite(T head, Args... tail) {
  475. stream.print(head);
  476. streamWrite(tail...);
  477. }
  478. int streamRead() { return stream.read(); }
  479. bool streamSkipUntil(char c) { //TODO: timeout
  480. while (true) {
  481. while (!stream.available()) {}
  482. if (stream.read() == c)
  483. return true;
  484. }
  485. return false;
  486. }
  487. template<typename... Args>
  488. void sendAT(Args... cmd) {
  489. streamWrite("AT", cmd..., GSM_NL);
  490. stream.flush();
  491. TINY_GSM_YIELD();
  492. //DBG("### AT:", cmd...);
  493. }
  494. // TODO: Optimize this!
  495. uint8_t waitResponse(uint32_t timeout, String& data,
  496. GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  497. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  498. {
  499. /*String r1s(r1); r1s.trim();
  500. String r2s(r2); r2s.trim();
  501. String r3s(r3); r3s.trim();
  502. String r4s(r4); r4s.trim();
  503. String r5s(r5); r5s.trim();
  504. DBG("### ..:", r1s, ",", r2s, ",", r3s, ",", r4s, ",", r5s);*/
  505. data.reserve(64);
  506. bool gotData = false;
  507. int mux = -1;
  508. int index = 0;
  509. unsigned long startMillis = millis();
  510. do {
  511. TINY_GSM_YIELD();
  512. while (stream.available() > 0) {
  513. int a = streamRead();
  514. if (a <= 0) continue; // Skip 0x00 bytes, just in case
  515. data += (char)a;
  516. if (r1 && data.endsWith(r1)) {
  517. index = 1;
  518. goto finish;
  519. } else if (r2 && data.endsWith(r2)) {
  520. index = 2;
  521. goto finish;
  522. } else if (r3 && data.endsWith(r3)) {
  523. index = 3;
  524. goto finish;
  525. } else if (r4 && data.endsWith(r4)) {
  526. index = 4;
  527. goto finish;
  528. } else if (r5 && data.endsWith(r5)) {
  529. index = 5;
  530. goto finish;
  531. } else if (data.endsWith(GF(GSM_NL "+CIPRXGET:"))) {
  532. String mode = stream.readStringUntil(',');
  533. if (mode.toInt() == 1) {
  534. mux = stream.readStringUntil('\n').toInt();
  535. gotData = true;
  536. data = "";
  537. } else {
  538. data += mode;
  539. }
  540. } else if (data.endsWith(GF("CLOSED" GSM_NL))) {
  541. int nl = data.lastIndexOf(GSM_NL, data.length()-8);
  542. int coma = data.indexOf(',', nl+2);
  543. mux = data.substring(nl+2, coma).toInt();
  544. if (mux) {
  545. sockets[mux]->sock_connected = false;
  546. data = "";
  547. }
  548. }
  549. }
  550. } while (millis() - startMillis < timeout);
  551. finish:
  552. if (!index) {
  553. if (data.length()) {
  554. DBG("### Unhandled:", data);
  555. }
  556. data = "";
  557. }
  558. if (gotData) {
  559. sockets[mux]->sock_available = modemGetAvailable(mux);
  560. }
  561. return index;
  562. }
  563. uint8_t waitResponse(uint32_t timeout,
  564. GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  565. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  566. {
  567. String data;
  568. return waitResponse(timeout, data, r1, r2, r3, r4, r5);
  569. }
  570. uint8_t waitResponse(GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  571. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  572. {
  573. return waitResponse(1000, r1, r2, r3, r4, r5);
  574. }
  575. private:
  576. Stream& stream;
  577. GsmClient* sockets[5];
  578. };
  579. typedef TinyGsm::GsmClient TinyGsmClient;
  580. #endif