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.

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