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.

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