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.

731 lines
16 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
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 TINY_GSM_DEBUG Serial
  11. //#define TINY_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 = TinyGsmMin(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. String getIMEI() {
  224. sendAT(GF("+GSN"));
  225. if (waitResponse(GF(GSM_NL)) != 1) {
  226. return "";
  227. }
  228. String res = stream.readStringUntil('\n');
  229. waitResponse();
  230. res.trim();
  231. return res;
  232. }
  233. int getSignalQuality() {
  234. sendAT(GF("+CSQ"));
  235. if (waitResponse(GF(GSM_NL "+CSQ:")) != 1) {
  236. return 99;
  237. }
  238. int res = stream.readStringUntil(',').toInt();
  239. waitResponse();
  240. return res;
  241. }
  242. String getGsmLocation() {
  243. sendAT(GF("+CIPGSMLOC=1,1"));
  244. if (waitResponse(GF(GSM_NL "+CIPGSMLOC:")) != 1) {
  245. return "";
  246. }
  247. String res = stream.readStringUntil('\n');
  248. waitResponse();
  249. res.trim();
  250. return res;
  251. }
  252. bool setGsmBusy(bool busy = true) {
  253. sendAT(GF("+GSMBUSY="), busy ? 1 : 0);
  254. return waitResponse() == 1;
  255. }
  256. bool callAnswer() {
  257. sendAT(GF("A"));
  258. return waitResponse() == 1;
  259. }
  260. bool callNumber(const String& number) {
  261. sendAT(GF("D"), number);
  262. return waitResponse() == 1;
  263. }
  264. bool callHangup(const String& number) {
  265. sendAT(GF("H"), number);
  266. return waitResponse() == 1;
  267. }
  268. bool sendSMS(const String& number, const String& text) {
  269. sendAT(GF("+CMGF=1"));
  270. waitResponse();
  271. sendAT(GF("+CMGS=\""), number, GF("\""));
  272. if (waitResponse(GF(">")) != 1) {
  273. return false;
  274. }
  275. stream.print(text);
  276. stream.write((char)0x1A);
  277. return waitResponse(60000L) == 1;
  278. }
  279. bool sendSMS_UTF16(const String& number, const void* text, size_t len) {
  280. sendAT(GF("+CMGF=1"));
  281. waitResponse();
  282. sendAT(GF("+CSCS=\"HEX\""));
  283. waitResponse();
  284. sendAT(GF("+CSMP=17,167,0,8"));
  285. waitResponse();
  286. sendAT(GF("+CMGS=\""), number, GF("\""));
  287. if (waitResponse(GF(">")) != 1) {
  288. return false;
  289. }
  290. uint16_t* t = (uint16_t*)text;
  291. for (size_t i=0; i<len; i++) {
  292. uint8_t c = t[i] >> 8;
  293. if (c < 0x10) { stream.print('0'); }
  294. stream.print(c, HEX);
  295. c = t[i] & 0xFF;
  296. if (c < 0x10) { stream.print('0'); }
  297. stream.print(c, HEX);
  298. }
  299. stream.write((char)0x1A);
  300. return waitResponse(60000L) == 1;
  301. }
  302. SimStatus getSimStatus(unsigned long timeout = 10000L) {
  303. for (unsigned long start = millis(); millis() - start < timeout; ) {
  304. sendAT(GF("+CPIN?"));
  305. if (waitResponse(GF(GSM_NL "+CPIN:")) != 1) {
  306. delay(1000);
  307. continue;
  308. }
  309. int status = waitResponse(GF("READY"), GF("SIM PIN"), GF("SIM PUK"), GF("NOT INSERTED"));
  310. waitResponse();
  311. switch (status) {
  312. case 2:
  313. case 3: return SIM_LOCKED;
  314. case 1: return SIM_READY;
  315. default: return SIM_ERROR;
  316. }
  317. }
  318. return SIM_ERROR;
  319. }
  320. RegStatus getRegistrationStatus() {
  321. sendAT(GF("+CREG?"));
  322. if (waitResponse(GF(GSM_NL "+CREG:")) != 1) {
  323. return REG_UNKNOWN;
  324. }
  325. streamSkipUntil(','); // Skip format (0)
  326. int status = stream.readStringUntil('\n').toInt();
  327. waitResponse();
  328. return (RegStatus)status;
  329. }
  330. String getOperator() {
  331. sendAT(GF("+COPS?"));
  332. if (waitResponse(GF(GSM_NL "+COPS:")) != 1) {
  333. return "";
  334. }
  335. streamSkipUntil('"'); // Skip mode and format
  336. String res = stream.readStringUntil('"');
  337. waitResponse();
  338. return res;
  339. }
  340. bool waitForNetwork(unsigned long timeout = 60000L) {
  341. for (unsigned long start = millis(); millis() - start < timeout; ) {
  342. RegStatus s = getRegistrationStatus();
  343. if (s == REG_OK_HOME || s == REG_OK_ROAMING) {
  344. return true;
  345. } else if (s == REG_UNREGISTERED) {
  346. return false;
  347. }
  348. delay(1000);
  349. }
  350. return false;
  351. }
  352. /*
  353. * GPRS functions
  354. */
  355. bool gprsConnect(const char* apn, const char* user, const char* pwd) {
  356. gprsDisconnect();
  357. sendAT(GF("+SAPBR=3,1,\"Contype\",\"GPRS\""));
  358. waitResponse();
  359. sendAT(GF("+SAPBR=3,1,\"APN\",\""), apn, '"');
  360. waitResponse();
  361. if (user) {
  362. sendAT(GF("+SAPBR=3,1,\"USER\",\""), user, '"');
  363. waitResponse();
  364. }
  365. if (pwd) {
  366. sendAT(GF("+SAPBR=3,1,\"PWD\",\""), pwd, '"');
  367. waitResponse();
  368. }
  369. sendAT(GF("+CGDCONT=1,\"IP\",\""), apn, '"');
  370. waitResponse();
  371. sendAT(GF("+CGACT=1,1"));
  372. waitResponse(60000L);
  373. // Open a GPRS context
  374. sendAT(GF("+SAPBR=1,1"));
  375. waitResponse(85000L);
  376. // Query the GPRS context
  377. sendAT(GF("+SAPBR=2,1"));
  378. if (waitResponse(30000L) != 1)
  379. return false;
  380. sendAT(GF("+CGATT=1"));
  381. if (waitResponse(60000L) != 1)
  382. return false;
  383. // TODO: wait AT+CGATT?
  384. sendAT(GF("+CIPMUX=1"));
  385. if (waitResponse() != 1) {
  386. return false;
  387. }
  388. sendAT(GF("+CIPQSEND=1"));
  389. if (waitResponse() != 1) {
  390. return false;
  391. }
  392. sendAT(GF("+CIPRXGET=1"));
  393. if (waitResponse() != 1) {
  394. return false;
  395. }
  396. sendAT(GF("+CSTT=\""), apn, GF("\",\""), user, GF("\",\""), pwd, GF("\""));
  397. if (waitResponse(60000L) != 1) {
  398. return false;
  399. }
  400. sendAT(GF("+CIICR"));
  401. if (waitResponse(60000L) != 1) {
  402. return false;
  403. }
  404. sendAT(GF("+CIFSR;E0"));
  405. String data;
  406. if (waitResponse(10000L, data) != 1) {
  407. data.replace(GSM_NL, "");
  408. return false;
  409. }
  410. sendAT(GF("+CDNSCFG=\"8.8.8.8\",\"8.8.4.4\""));
  411. if (waitResponse() != 1) {
  412. return false;
  413. }
  414. return true;
  415. }
  416. bool gprsDisconnect() {
  417. sendAT(GF("+CIPSHUT"));
  418. return waitResponse(60000L) == 1;
  419. }
  420. /*
  421. * Phone Call functions
  422. */
  423. /*
  424. * Messaging functions
  425. */
  426. void sendUSSD() {
  427. }
  428. void sendSMS() {
  429. }
  430. /*
  431. * Location functions
  432. */
  433. void getLocation() {
  434. }
  435. /*
  436. * Battery functions
  437. */
  438. // Use: float vBatt = modem.getBattVoltage() / 1000.0;
  439. uint16_t getBattVoltage() {
  440. sendAT(GF("+CBC"));
  441. if (waitResponse(GF(GSM_NL "+CBC:")) != 1) {
  442. return 0;
  443. }
  444. streamSkipUntil(','); // Skip
  445. streamSkipUntil(','); // Skip
  446. uint16_t res = stream.readStringUntil(',').toInt();
  447. waitResponse();
  448. return res;
  449. }
  450. private:
  451. int modemConnect(const char* host, uint16_t port, uint8_t mux) {
  452. sendAT(GF("+CIPSTART="), mux, ',', GF("\"TCP"), GF("\",\""), host, GF("\","), port);
  453. int rsp = waitResponse(75000L,
  454. GF("CONNECT OK" GSM_NL),
  455. GF("CONNECT FAIL" GSM_NL),
  456. GF("ALREADY CONNECT" GSM_NL));
  457. return (1 == rsp);
  458. }
  459. int modemSend(const void* buff, size_t len, uint8_t mux) {
  460. sendAT(GF("+CIPSEND="), mux, ',', len);
  461. if (waitResponse(GF(">")) != 1) {
  462. return -1;
  463. }
  464. stream.write((uint8_t*)buff, len);
  465. if (waitResponse(GF(GSM_NL "DATA ACCEPT:")) != 1) {
  466. return -1;
  467. }
  468. streamSkipUntil(','); // Skip mux
  469. return stream.readStringUntil('\n').toInt();
  470. }
  471. size_t modemRead(size_t size, uint8_t mux) {
  472. #ifdef TINY_GSM_USE_HEX
  473. sendAT(GF("+CIPRXGET=3,"), mux, ',', size);
  474. if (waitResponse(GF("+CIPRXGET:")) != 1) {
  475. return 0;
  476. }
  477. #else
  478. sendAT(GF("+CIPRXGET=2,"), mux, ',', size);
  479. if (waitResponse(GF("+CIPRXGET:")) != 1) {
  480. return 0;
  481. }
  482. #endif
  483. streamSkipUntil(','); // Skip mode 2/3
  484. streamSkipUntil(','); // Skip mux
  485. size_t len = stream.readStringUntil(',').toInt();
  486. sockets[mux]->sock_available = stream.readStringUntil('\n').toInt();
  487. for (size_t i=0; i<len; i++) {
  488. #ifdef TINY_GSM_USE_HEX
  489. while (stream.available() < 2) { TINY_GSM_YIELD(); }
  490. char buf[4] = { 0, };
  491. buf[0] = stream.read();
  492. buf[1] = stream.read();
  493. char c = strtol(buf, NULL, 16);
  494. #else
  495. while (!stream.available()) { TINY_GSM_YIELD(); }
  496. char c = stream.read();
  497. #endif
  498. sockets[mux]->rx.put(c);
  499. }
  500. waitResponse();
  501. return len;
  502. }
  503. size_t modemGetAvailable(uint8_t mux) {
  504. sendAT(GF("+CIPRXGET=4,"), mux);
  505. size_t result = 0;
  506. if (waitResponse(GF("+CIPRXGET:")) == 1) {
  507. streamSkipUntil(','); // Skip mode 4
  508. streamSkipUntil(','); // Skip mux
  509. result = stream.readStringUntil('\n').toInt();
  510. waitResponse();
  511. }
  512. if (!result) {
  513. sockets[mux]->sock_connected = modemGetConnected(mux);
  514. }
  515. return result;
  516. }
  517. bool modemGetConnected(uint8_t mux) {
  518. sendAT(GF("+CIPSTATUS="), mux);
  519. int res = waitResponse(GF(",\"CONNECTED\""), GF(",\"CLOSED\""), GF(",\"CLOSING\""), GF(",\"INITIAL\""));
  520. waitResponse();
  521. return 1 == res;
  522. }
  523. /* Utilities */
  524. template<typename T>
  525. void streamWrite(T last) {
  526. stream.print(last);
  527. }
  528. template<typename T, typename... Args>
  529. void streamWrite(T head, Args... tail) {
  530. stream.print(head);
  531. streamWrite(tail...);
  532. }
  533. int streamRead() { return stream.read(); }
  534. bool streamSkipUntil(char c) { //TODO: timeout
  535. while (true) {
  536. while (!stream.available()) { TINY_GSM_YIELD(); }
  537. if (stream.read() == c)
  538. return true;
  539. }
  540. return false;
  541. }
  542. template<typename... Args>
  543. void sendAT(Args... cmd) {
  544. streamWrite("AT", cmd..., GSM_NL);
  545. stream.flush();
  546. TINY_GSM_YIELD();
  547. //DBG("### AT:", cmd...);
  548. }
  549. // TODO: Optimize this!
  550. uint8_t waitResponse(uint32_t timeout, String& data,
  551. GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  552. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  553. {
  554. /*String r1s(r1); r1s.trim();
  555. String r2s(r2); r2s.trim();
  556. String r3s(r3); r3s.trim();
  557. String r4s(r4); r4s.trim();
  558. String r5s(r5); r5s.trim();
  559. DBG("### ..:", r1s, ",", r2s, ",", r3s, ",", r4s, ",", r5s);*/
  560. data.reserve(64);
  561. bool gotData = false;
  562. int mux = -1;
  563. int index = 0;
  564. unsigned long startMillis = millis();
  565. do {
  566. TINY_GSM_YIELD();
  567. while (stream.available() > 0) {
  568. int a = streamRead();
  569. if (a <= 0) continue; // Skip 0x00 bytes, just in case
  570. data += (char)a;
  571. if (r1 && data.endsWith(r1)) {
  572. index = 1;
  573. goto finish;
  574. } else if (r2 && data.endsWith(r2)) {
  575. index = 2;
  576. goto finish;
  577. } else if (r3 && data.endsWith(r3)) {
  578. index = 3;
  579. goto finish;
  580. } else if (r4 && data.endsWith(r4)) {
  581. index = 4;
  582. goto finish;
  583. } else if (r5 && data.endsWith(r5)) {
  584. index = 5;
  585. goto finish;
  586. } else if (data.endsWith(GF(GSM_NL "+CIPRXGET:"))) {
  587. String mode = stream.readStringUntil(',');
  588. if (mode.toInt() == 1) {
  589. mux = stream.readStringUntil('\n').toInt();
  590. gotData = true;
  591. data = "";
  592. } else {
  593. data += mode;
  594. }
  595. } else if (data.endsWith(GF("CLOSED" GSM_NL))) {
  596. int nl = data.lastIndexOf(GSM_NL, data.length()-8);
  597. int coma = data.indexOf(',', nl+2);
  598. mux = data.substring(nl+2, coma).toInt();
  599. if (mux) {
  600. sockets[mux]->sock_connected = false;
  601. data = "";
  602. }
  603. }
  604. }
  605. } while (millis() - startMillis < timeout);
  606. finish:
  607. if (!index) {
  608. data.trim();
  609. if (data.length()) {
  610. DBG("### Unhandled:", data);
  611. }
  612. data = "";
  613. }
  614. if (gotData) {
  615. sockets[mux]->sock_available = modemGetAvailable(mux);
  616. }
  617. return index;
  618. }
  619. uint8_t waitResponse(uint32_t timeout,
  620. GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  621. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  622. {
  623. String data;
  624. return waitResponse(timeout, data, r1, r2, r3, r4, r5);
  625. }
  626. uint8_t waitResponse(GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  627. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  628. {
  629. return waitResponse(1000, r1, r2, r3, r4, r5);
  630. }
  631. private:
  632. Stream& stream;
  633. GsmClient* sockets[5];
  634. };
  635. typedef TinyGsm::GsmClient TinyGsmClient;
  636. #endif