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.

657 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
  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. }
  299. delay(1000);
  300. }
  301. return true;
  302. }
  303. /*
  304. * GPRS functions
  305. */
  306. bool gprsConnect(const char* apn, const char* user, const char* pwd) {
  307. gprsDisconnect();
  308. sendAT(GF("+SAPBR=3,1,\"Contype\",\"GPRS\""));
  309. waitResponse();
  310. sendAT(GF("+SAPBR=3,1,\"APN\",\""), apn, '"');
  311. waitResponse();
  312. if (user) {
  313. sendAT(GF("+SAPBR=3,1,\"USER\",\""), user, '"');
  314. waitResponse();
  315. }
  316. if (pwd) {
  317. sendAT(GF("+SAPBR=3,1,\"PWD\",\""), pwd, '"');
  318. waitResponse();
  319. }
  320. sendAT(GF("+CGDCONT=1,\"IP\",\""), apn, '"');
  321. waitResponse();
  322. sendAT(GF("+CGACT=1,1"));
  323. waitResponse(60000L);
  324. // Open a GPRS context
  325. sendAT(GF("+SAPBR=1,1"));
  326. waitResponse(85000L);
  327. // Query the GPRS context
  328. sendAT(GF("+SAPBR=2,1"));
  329. if (waitResponse(30000L) != 1)
  330. return false;
  331. sendAT(GF("+CGATT=1"));
  332. if (waitResponse(60000L) != 1)
  333. return false;
  334. // TODO: wait AT+CGATT?
  335. sendAT(GF("+CIPMUX=1"));
  336. if (waitResponse() != 1) {
  337. return false;
  338. }
  339. sendAT(GF("+CIPQSEND=1"));
  340. if (waitResponse() != 1) {
  341. return false;
  342. }
  343. sendAT(GF("+CIPRXGET=1"));
  344. if (waitResponse() != 1) {
  345. return false;
  346. }
  347. sendAT(GF("+CSTT=\""), apn, GF("\",\""), user, GF("\",\""), pwd, GF("\""));
  348. if (waitResponse(60000L) != 1) {
  349. return false;
  350. }
  351. sendAT(GF("+CIICR"));
  352. if (waitResponse(60000L) != 1) {
  353. return false;
  354. }
  355. sendAT(GF("+CIFSR;E0"));
  356. String data;
  357. if (waitResponse(10000L, data) != 1) {
  358. data.replace(GSM_NL, "");
  359. return false;
  360. }
  361. sendAT(GF("+CDNSCFG=\"8.8.8.8\",\"8.8.4.4\""));
  362. if (waitResponse() != 1) {
  363. return false;
  364. }
  365. return true;
  366. }
  367. bool gprsDisconnect() {
  368. sendAT(GF("+CIPSHUT"));
  369. return waitResponse(60000L) == 1;
  370. }
  371. /*
  372. * Phone Call functions
  373. */
  374. /*
  375. * Messaging functions
  376. */
  377. void sendUSSD() {
  378. }
  379. void sendSMS() {
  380. }
  381. /*
  382. * Location functions
  383. */
  384. void getLocation() {
  385. }
  386. /*
  387. * Battery functions
  388. */
  389. private:
  390. int modemConnect(const char* host, uint16_t port, uint8_t mux) {
  391. sendAT(GF("+CIPSTART="), mux, ',', GF("\"TCP"), GF("\",\""), host, GF("\","), port);
  392. int rsp = waitResponse(75000L,
  393. GF("CONNECT OK" GSM_NL),
  394. GF("CONNECT FAIL" GSM_NL),
  395. GF("ALREADY CONNECT" GSM_NL));
  396. return (1 == rsp);
  397. }
  398. int modemSend(const void* buff, size_t len, uint8_t mux) {
  399. sendAT(GF("+CIPSEND="), mux, ',', len);
  400. if (waitResponse(GF(">")) != 1) {
  401. return -1;
  402. }
  403. stream.write((uint8_t*)buff, len);
  404. if (waitResponse(GF(GSM_NL "DATA ACCEPT:")) != 1) {
  405. return -1;
  406. }
  407. streamSkipUntil(','); // Skip mux
  408. return stream.readStringUntil('\n').toInt();
  409. }
  410. size_t modemRead(size_t size, uint8_t mux) {
  411. #ifdef GSM_USE_HEX
  412. sendAT(GF("+CIPRXGET=3,"), mux, ',', size);
  413. if (waitResponse(GF("+CIPRXGET:")) != 1) {
  414. return 0;
  415. }
  416. #else
  417. sendAT(GF("+CIPRXGET=2,"), mux, ',', size);
  418. if (waitResponse(GF("+CIPRXGET:")) != 1) {
  419. return 0;
  420. }
  421. #endif
  422. streamSkipUntil(','); // Skip mode 2/3
  423. streamSkipUntil(','); // Skip mux
  424. size_t len = stream.readStringUntil(',').toInt();
  425. sockets[mux]->sock_available = stream.readStringUntil('\n').toInt();
  426. for (size_t i=0; i<len; i++) {
  427. #ifdef GSM_USE_HEX
  428. while (stream.available() < 2) {}
  429. char buf[4] = { 0, };
  430. buf[0] = stream.read();
  431. buf[1] = stream.read();
  432. char c = strtol(buf, NULL, 16);
  433. #else
  434. while (!stream.available()) {}
  435. char c = stream.read();
  436. #endif
  437. sockets[mux]->rx.put(c);
  438. }
  439. waitResponse();
  440. return len;
  441. }
  442. size_t modemGetAvailable(uint8_t mux) {
  443. sendAT(GF("+CIPRXGET=4,"), mux);
  444. size_t result = 0;
  445. if (waitResponse(GF("+CIPRXGET:")) == 1) {
  446. streamSkipUntil(','); // Skip mode 4
  447. streamSkipUntil(','); // Skip mux
  448. result = stream.readStringUntil('\n').toInt();
  449. waitResponse();
  450. }
  451. if (!result) {
  452. sockets[mux]->sock_connected = modemGetConnected(mux);
  453. }
  454. return result;
  455. }
  456. bool modemGetConnected(uint8_t mux) {
  457. sendAT(GF("+CIPSTATUS="), mux);
  458. int res = waitResponse(GF(",\"CONNECTED\""), GF(",\"CLOSED\""), GF(",\"CLOSING\""), GF(",\"INITIAL\""));
  459. waitResponse();
  460. return 1 == res;
  461. }
  462. /* Utilities */
  463. template<typename T>
  464. void streamWrite(T last) {
  465. stream.print(last);
  466. }
  467. template<typename T, typename... Args>
  468. void streamWrite(T head, Args... tail) {
  469. stream.print(head);
  470. streamWrite(tail...);
  471. }
  472. int streamRead() { return stream.read(); }
  473. bool streamSkipUntil(char c) { //TODO: timeout
  474. while (true) {
  475. while (!stream.available()) {}
  476. if (stream.read() == c)
  477. return true;
  478. }
  479. return false;
  480. }
  481. template<typename... Args>
  482. void sendAT(Args... cmd) {
  483. streamWrite("AT", cmd..., GSM_NL);
  484. stream.flush();
  485. //DBG("### AT:", cmd...);
  486. }
  487. // TODO: Optimize this!
  488. uint8_t waitResponse(uint32_t timeout, String& data,
  489. GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  490. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  491. {
  492. /*String r1s(r1); r1s.trim();
  493. String r2s(r2); r2s.trim();
  494. String r3s(r3); r3s.trim();
  495. String r4s(r4); r4s.trim();
  496. String r5s(r5); r5s.trim();
  497. DBG("### ..:", r1s, ",", r2s, ",", r3s, ",", r4s, ",", r5s);*/
  498. data.reserve(64);
  499. bool gotData = false;
  500. int mux = -1;
  501. int index = 0;
  502. unsigned long startMillis = millis();
  503. do {
  504. while (stream.available() > 0) {
  505. int a = streamRead();
  506. if (a <= 0) continue; // Skip 0x00 bytes, just in case
  507. data += (char)a;
  508. if (r1 && data.endsWith(r1)) {
  509. index = 1;
  510. goto finish;
  511. } else if (r2 && data.endsWith(r2)) {
  512. index = 2;
  513. goto finish;
  514. } else if (r3 && data.endsWith(r3)) {
  515. index = 3;
  516. goto finish;
  517. } else if (r4 && data.endsWith(r4)) {
  518. index = 4;
  519. goto finish;
  520. } else if (r5 && data.endsWith(r5)) {
  521. index = 5;
  522. goto finish;
  523. } else if (data.endsWith(GF(GSM_NL "+CIPRXGET:"))) {
  524. String mode = stream.readStringUntil(',');
  525. if (mode.toInt() == 1) {
  526. mux = stream.readStringUntil('\n').toInt();
  527. gotData = true;
  528. data = "";
  529. } else {
  530. data += mode;
  531. }
  532. } else if (data.endsWith(GF("CLOSED" GSM_NL))) {
  533. int nl = data.lastIndexOf(GSM_NL, data.length()-8);
  534. int coma = data.indexOf(',', nl+2);
  535. mux = data.substring(nl+2, coma).toInt();
  536. if (mux) {
  537. sockets[mux]->sock_connected = false;
  538. data = "";
  539. }
  540. }
  541. }
  542. } while (millis() - startMillis < timeout);
  543. finish:
  544. if (!index) {
  545. if (data.length()) {
  546. DBG("### Unhandled:", data);
  547. }
  548. data = "";
  549. }
  550. if (gotData) {
  551. sockets[mux]->sock_available = modemGetAvailable(mux);
  552. }
  553. return index;
  554. }
  555. uint8_t waitResponse(uint32_t timeout,
  556. GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  557. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  558. {
  559. String data;
  560. return waitResponse(timeout, data, r1, r2, r3, r4, r5);
  561. }
  562. uint8_t waitResponse(GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  563. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  564. {
  565. return waitResponse(1000, r1, r2, r3, r4, r5);
  566. }
  567. private:
  568. Stream& stream;
  569. GsmClient* sockets[5];
  570. };
  571. typedef TinyGsm::GsmClient TinyGsmClient;
  572. #endif