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.

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