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.

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