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.

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