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.

592 lines
13 KiB

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(GSM_RX_BUFFER)
  35. #define GSM_RX_BUFFER 256
  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 = 3,
  49. REG_DENIED = 2,
  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, GSM_RX_BUFFER> RxFifo;
  79. public:
  80. GsmClient() {}
  81. GsmClient(TinyGsm& modem, uint8_t mux = 0) {
  82. init(&modem, mux);
  83. }
  84. bool init(TinyGsm* modem, uint8_t mux = 0) {
  85. this->at = modem;
  86. this->mux = mux;
  87. sock_connected = false;
  88. at->sockets[mux] = this;
  89. return true;
  90. }
  91. public:
  92. virtual int connect(const char *host, uint16_t port) {
  93. TINY_GSM_YIELD();
  94. rx.clear();
  95. sock_connected = at->modemConnect(host, port, mux);
  96. return sock_connected;
  97. }
  98. virtual int connect(IPAddress ip, uint16_t port) {
  99. String host; host.reserve(16);
  100. host += ip[0];
  101. host += ".";
  102. host += ip[1];
  103. host += ".";
  104. host += ip[2];
  105. host += ".";
  106. host += ip[3];
  107. return connect(host.c_str(), port);
  108. }
  109. virtual void stop() {
  110. TINY_GSM_YIELD();
  111. at->sendAT(GF("+TCPCLOSE="), mux);
  112. sock_connected = false;
  113. at->waitResponse();
  114. }
  115. virtual size_t write(const uint8_t *buf, size_t size) {
  116. TINY_GSM_YIELD();
  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. TINY_GSM_YIELD();
  125. if (!rx.size()) {
  126. at->maintain();
  127. }
  128. return rx.size();
  129. }
  130. virtual int read(uint8_t *buf, size_t size) {
  131. TINY_GSM_YIELD();
  132. size_t cnt = 0;
  133. while (cnt < size) {
  134. size_t chunk = min(size-cnt, rx.size());
  135. if (chunk > 0) {
  136. rx.get(buf, chunk);
  137. buf += chunk;
  138. cnt += chunk;
  139. continue;
  140. }
  141. // TODO: Read directly into user buffer?
  142. if (!rx.size()) {
  143. at->maintain();
  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. bool sock_connected;
  169. RxFifo rx;
  170. };
  171. public:
  172. /*
  173. * Basic functions
  174. */
  175. bool begin() {
  176. return init();
  177. }
  178. bool init() {
  179. if (!autoBaud()) {
  180. return false;
  181. }
  182. sendAT(GF("&FZE0")); // Factory + Reset + Echo Off
  183. if (waitResponse() != 1) {
  184. return false;
  185. }
  186. #ifdef GSM_DEBUG
  187. sendAT(GF("+CMEE=2"));
  188. waitResponse();
  189. #endif
  190. getSimStatus();
  191. return true;
  192. }
  193. bool autoBaud(unsigned long timeout = 10000L) {
  194. for (unsigned long start = millis(); millis() - start < timeout; ) {
  195. sendAT(GF("E0"));
  196. if (waitResponse(200) == 1) {
  197. delay(100);
  198. return true;
  199. }
  200. delay(100);
  201. }
  202. return false;
  203. }
  204. void maintain() {
  205. //while (stream.available()) {
  206. waitResponse(10, NULL, NULL);
  207. //}
  208. }
  209. bool factoryDefault() {
  210. sendAT(GF("&FZE0&W")); // Factory + Reset + Echo Off + Write
  211. waitResponse();
  212. sendAT(GF("+ICF=3,1")); // 8 data 0 parity 1 stop
  213. waitResponse();
  214. sendAT(GF("+enpwrsave=0")); // Disable PWR save
  215. waitResponse();
  216. sendAT(GF("+XISP=0")); // Use internal stack
  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=15"));
  229. if (waitResponse(10000L) != 1) {
  230. return false;
  231. }
  232. //MODEM:STARTUP
  233. waitResponse(60000L, GF(GSM_NL "+PBREADY" GSM_NL));
  234. return init();
  235. }
  236. /*
  237. * SIM card & Networ Operator functions
  238. */
  239. bool simUnlock(const char *pin) {
  240. sendAT(GF("+CPIN=\""), pin, GF("\""));
  241. return waitResponse() == 1;
  242. }
  243. String getSimCCID() {
  244. sendAT(GF("+CCID"));
  245. if (waitResponse(GF(GSM_NL "+CCID:")) != 1) {
  246. return "";
  247. }
  248. String res = stream.readStringUntil('\n');
  249. waitResponse();
  250. res.trim();
  251. return res;
  252. }
  253. SimStatus getSimStatus(unsigned long timeout = 10000L) {
  254. for (unsigned long start = millis(); millis() - start < timeout; ) {
  255. sendAT(GF("+CPIN?"));
  256. if (waitResponse(GF(GSM_NL "+CPIN:")) != 1) {
  257. delay(1000);
  258. continue;
  259. }
  260. int status = waitResponse(GF("READY"), GF("SIM PIN"), GF("SIM PUK"));
  261. waitResponse();
  262. switch (status) {
  263. case 2:
  264. case 3: return SIM_LOCKED;
  265. case 1: return SIM_READY;
  266. default: return SIM_ERROR;
  267. }
  268. }
  269. return SIM_ERROR;
  270. }
  271. RegStatus getRegistrationStatus() {
  272. sendAT(GF("+CREG?"));
  273. if (waitResponse(GF(GSM_NL "+CREG:")) != 1) {
  274. return REG_UNKNOWN;
  275. }
  276. streamSkipUntil(','); // Skip format (0)
  277. int status = stream.readStringUntil('\n').toInt();
  278. waitResponse();
  279. return (RegStatus)status;
  280. }
  281. String getOperator() {
  282. sendAT(GF("+COPS?"));
  283. if (waitResponse(GF(GSM_NL "+COPS:")) != 1) {
  284. return "";
  285. }
  286. streamSkipUntil('"'); // Skip mode and format
  287. String res = stream.readStringUntil('"');
  288. waitResponse();
  289. return res;
  290. }
  291. bool waitForNetwork(unsigned long timeout = 60000L) {
  292. for (unsigned long start = millis(); millis() - start < timeout; ) {
  293. RegStatus s = getRegistrationStatus();
  294. if (s == REG_OK_HOME || s == REG_OK_ROAMING) {
  295. return true;
  296. } else if (s == REG_UNREGISTERED) {
  297. return false;
  298. }
  299. delay(1000);
  300. }
  301. return false;
  302. }
  303. /*
  304. * GPRS functions
  305. */
  306. bool gprsConnect(const char* apn, const char* user, const char* pwd) {
  307. gprsDisconnect();
  308. sendAT(GF("+XISP=0"));
  309. waitResponse();
  310. sendAT(GF("+CGDCONT=1,\"IP\",\""), apn, '"');
  311. waitResponse();
  312. if (!user) user = "";
  313. if (!pwd) pwd = "";
  314. sendAT(GF("+XGAUTH=1,1,\""), user, GF("\",\""), pwd, GF("\""));
  315. waitResponse();
  316. sendAT(GF("+XIIC=1"));
  317. waitResponse();
  318. delay(10000L); // TODO
  319. sendAT(GF("+XIIC?"));
  320. waitResponse();
  321. /*sendAT(GF("+DNSSERVER=1,8.8.8.8"));
  322. waitResponse();
  323. sendAT(GF("+DNSSERVER=2,8.8.4.4"));
  324. if (waitResponse() != 1) {
  325. return false;
  326. }*/
  327. return true;
  328. }
  329. bool gprsDisconnect() {
  330. sendAT(GF("+XIIC=0"));
  331. return waitResponse(60000L) == 1;
  332. }
  333. /*
  334. * Phone Call functions
  335. */
  336. /*
  337. * Messaging functions
  338. */
  339. void sendUSSD() {
  340. }
  341. void sendSMS() {
  342. }
  343. /*
  344. * Location functions
  345. */
  346. void getLocation() {
  347. }
  348. /*
  349. * Battery functions
  350. */
  351. private:
  352. String dnsIpQuery(const char* host) {
  353. sendAT(GF("+DNS=\""), host, GF("\""));
  354. if (waitResponse(10000L, GF(GSM_NL "+DNS:")) != 1) {
  355. return "";
  356. }
  357. String res = stream.readStringUntil('\n');
  358. waitResponse(GF("+DNS:OK" GSM_NL));
  359. res.trim();
  360. return res;
  361. }
  362. int modemConnect(const char* host, uint16_t port, uint8_t mux) {
  363. int rsp = 0;
  364. for (int i=0; i<3; i++) {
  365. String ip = dnsIpQuery(host);
  366. sendAT(GF("+TCPSETUP="), mux, GF(","), ip, GF(","), port);
  367. int rsp = waitResponse(75000L,
  368. GF(",OK" GSM_NL),
  369. GF(",FAIL" GSM_NL),
  370. GF("+TCPSETUP:Error" GSM_NL));
  371. if (1 == rsp) {
  372. return true;
  373. } else if (3 == rsp) {
  374. sendAT(GF("+TCPCLOSE="), mux);
  375. waitResponse();
  376. }
  377. delay(1000);
  378. }
  379. return false;
  380. }
  381. int modemSend(const void* buff, size_t len, uint8_t mux) {
  382. sendAT(GF("+TCPSEND="), mux, ',', len);
  383. if (waitResponse(GF(">")) != 1) {
  384. return 0;
  385. }
  386. stream.write((uint8_t*)buff, len);
  387. stream.write((char)0x0D);
  388. if (waitResponse(30000L, GF(GSM_NL "+TCPSEND:")) != 1) {
  389. return 0;
  390. }
  391. stream.readStringUntil('\n');
  392. return len;
  393. }
  394. bool modemGetConnected(uint8_t mux) {
  395. sendAT(GF("+CIPSTATUS="), mux);
  396. int res = waitResponse(GF(",\"CONNECTED\""), GF(",\"CLOSED\""), GF(",\"CLOSING\""), GF(",\"INITIAL\""));
  397. waitResponse();
  398. return 1 == res;
  399. }
  400. /* Utilities */
  401. template<typename T>
  402. void streamWrite(T last) {
  403. stream.print(last);
  404. }
  405. template<typename T, typename... Args>
  406. void streamWrite(T head, Args... tail) {
  407. stream.print(head);
  408. streamWrite(tail...);
  409. }
  410. int streamRead() { return stream.read(); }
  411. bool streamSkipUntil(char c) { //TODO: timeout
  412. while (true) {
  413. while (!stream.available()) {}
  414. if (stream.read() == c)
  415. return true;
  416. }
  417. return false;
  418. }
  419. template<typename... Args>
  420. void sendAT(Args... cmd) {
  421. streamWrite("AT", cmd..., GSM_NL);
  422. stream.flush();
  423. TINY_GSM_YIELD();
  424. //DBG("### AT:", cmd...);
  425. }
  426. // TODO: Optimize this!
  427. uint8_t waitResponse(uint32_t timeout, String& data,
  428. GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  429. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  430. {
  431. /*String r1s(r1); r1s.trim();
  432. String r2s(r2); r2s.trim();
  433. String r3s(r3); r3s.trim();
  434. String r4s(r4); r4s.trim();
  435. String r5s(r5); r5s.trim();
  436. DBG("### ..:", r1s, ",", r2s, ",", r3s, ",", r4s, ",", r5s);*/
  437. data.reserve(64);
  438. int index = 0;
  439. unsigned long startMillis = millis();
  440. do {
  441. TINY_GSM_YIELD();
  442. while (stream.available() > 0) {
  443. int a = streamRead();
  444. if (a <= 0) continue; // Skip 0x00 bytes, just in case
  445. data += (char)a;
  446. if (r1 && data.endsWith(r1)) {
  447. index = 1;
  448. goto finish;
  449. } else if (r2 && data.endsWith(r2)) {
  450. index = 2;
  451. goto finish;
  452. } else if (r3 && data.endsWith(r3)) {
  453. index = 3;
  454. goto finish;
  455. } else if (r4 && data.endsWith(r4)) {
  456. index = 4;
  457. goto finish;
  458. } else if (r5 && data.endsWith(r5)) {
  459. index = 5;
  460. goto finish;
  461. } else if (data.endsWith(GF("+TCPRECV:"))) {
  462. int mux = stream.readStringUntil(',').toInt();
  463. int len = stream.readStringUntil(',').toInt();
  464. if (len > sockets[mux]->rx.free()) {
  465. DBG("### Buffer overflow: ", len, "->", sockets[mux]->rx.free());
  466. } else {
  467. DBG("### Got: ", len, "->", sockets[mux]->rx.free());
  468. }
  469. while (len--) {
  470. while (!stream.available()) {}
  471. sockets[mux]->rx.put(stream.read());
  472. }
  473. data = "";
  474. return index;
  475. } else if (data.endsWith(GF("+TCPCLOSE:"))) {
  476. int mux = stream.readStringUntil(',').toInt();
  477. stream.readStringUntil('\n');
  478. sockets[mux]->sock_connected = false;
  479. data = "";
  480. }
  481. }
  482. } while (millis() - startMillis < timeout);
  483. finish:
  484. if (!index) {
  485. if (data.length()) {
  486. DBG("### Unhandled:", data);
  487. }
  488. data = "";
  489. }
  490. return index;
  491. }
  492. uint8_t waitResponse(uint32_t timeout,
  493. GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  494. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  495. {
  496. String data;
  497. return waitResponse(timeout, data, r1, r2, r3, r4, r5);
  498. }
  499. uint8_t waitResponse(GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  500. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  501. {
  502. return waitResponse(1000, r1, r2, r3, r4, r5);
  503. }
  504. private:
  505. Stream& stream;
  506. GsmClient* sockets[2];
  507. };
  508. typedef TinyGsm::GsmClient TinyGsmClient;
  509. #endif