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.

754 lines
17 KiB

6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
  1. /**
  2. * @file TinyGsmClientBG96.h
  3. * @author Volodymyr Shymanskyy
  4. * @license LGPL-3.0
  5. * @copyright Copyright (c) 2016 Volodymyr Shymanskyy
  6. * @date Apr 2018
  7. */
  8. #ifndef TinyGsmClientBG96_h
  9. #define TinyGsmClientBG96_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. #define TINY_GSM_MUX_COUNT 12
  16. #include <TinyGsmCommon.h>
  17. #define GSM_NL "\r\n"
  18. static const char GSM_OK[] TINY_GSM_PROGMEM = "OK" GSM_NL;
  19. static const char GSM_ERROR[] TINY_GSM_PROGMEM = "ERROR" GSM_NL;
  20. enum SimStatus {
  21. SIM_ERROR = 0,
  22. SIM_READY = 1,
  23. SIM_LOCKED = 2,
  24. };
  25. enum RegStatus {
  26. REG_UNREGISTERED = 0,
  27. REG_SEARCHING = 2,
  28. REG_DENIED = 3,
  29. REG_OK_HOME = 1,
  30. REG_OK_ROAMING = 5,
  31. REG_UNKNOWN = 4,
  32. };
  33. class TinyGsmBG96 : public TinyGsmMasterModem
  34. {
  35. public:
  36. class GsmClient : public Client
  37. {
  38. friend class TinyGsmBG96;
  39. typedef TinyGsmFifo<uint8_t, TINY_GSM_RX_BUFFER> RxFifo;
  40. public:
  41. GsmClient() {}
  42. GsmClient(TinyGsmBG96& modem, uint8_t mux = 1) {
  43. init(&modem, mux);
  44. }
  45. bool init(TinyGsmBG96* modem, uint8_t mux = 1) {
  46. this->at = modem;
  47. this->mux = mux;
  48. sock_available = 0;
  49. sock_connected = false;
  50. got_data = false;
  51. at->sockets[mux] = this;
  52. return true;
  53. }
  54. public:
  55. virtual int connect(const char *host, uint16_t port) {
  56. stop();
  57. TINY_GSM_YIELD();
  58. rx.clear();
  59. sock_connected = at->modemConnect(host, port, mux);
  60. return sock_connected;
  61. }
  62. virtual int connect(IPAddress ip, uint16_t port) {
  63. String host; host.reserve(16);
  64. host += ip[0];
  65. host += ".";
  66. host += ip[1];
  67. host += ".";
  68. host += ip[2];
  69. host += ".";
  70. host += ip[3];
  71. return connect(host.c_str(), port);
  72. }
  73. virtual void stop() {
  74. TINY_GSM_YIELD();
  75. at->sendAT(GF("+QICLOSE="), mux);
  76. sock_connected = false;
  77. at->waitResponse();
  78. rx.clear();
  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 size_t write(const char *str) {
  89. if (str == NULL) return 0;
  90. return write((const uint8_t *)str, strlen(str));
  91. }
  92. virtual int available() {
  93. TINY_GSM_YIELD();
  94. if (!rx.size()) {
  95. at->maintain();
  96. }
  97. return rx.size() + sock_available;
  98. }
  99. virtual int read(uint8_t *buf, size_t size) {
  100. TINY_GSM_YIELD();
  101. at->maintain();
  102. size_t cnt = 0;
  103. while (cnt < size) {
  104. size_t chunk = TinyGsmMin(size-cnt, rx.size());
  105. if (chunk > 0) {
  106. rx.get(buf, chunk);
  107. buf += chunk;
  108. cnt += chunk;
  109. continue;
  110. }
  111. // TODO: Read directly into user buffer?
  112. at->maintain();
  113. if (sock_available > 0) {
  114. sock_available -= at->modemRead(TinyGsmMin((uint16_t)rx.free(), sock_available), mux);
  115. } else {
  116. break;
  117. }
  118. }
  119. return cnt;
  120. }
  121. virtual int read() {
  122. uint8_t c;
  123. if (read(&c, 1) == 1) {
  124. return c;
  125. }
  126. return -1;
  127. }
  128. virtual int peek() { return -1; } //TODO
  129. virtual void flush() { at->stream.flush(); }
  130. virtual uint8_t connected() {
  131. if (available()) {
  132. return true;
  133. }
  134. return sock_connected;
  135. }
  136. virtual operator bool() { return connected(); }
  137. /*
  138. * Extended API
  139. */
  140. String remoteIP() TINY_GSM_ATTR_NOT_IMPLEMENTED;
  141. private:
  142. TinyGsmBG96* at;
  143. uint8_t mux;
  144. uint16_t sock_available;
  145. bool sock_connected;
  146. bool got_data;
  147. RxFifo rx;
  148. };
  149. class GsmClientSecure : public GsmClient
  150. {
  151. public:
  152. GsmClientSecure() {}
  153. GsmClientSecure(TinyGsmBG96& modem, uint8_t mux = 1)
  154. : GsmClient(modem, mux)
  155. {}
  156. public:
  157. virtual int connect(const char *host, uint16_t port) {
  158. stop();
  159. TINY_GSM_YIELD();
  160. rx.clear();
  161. sock_connected = at->modemConnect(host, port, mux, true);
  162. return sock_connected;
  163. }
  164. };
  165. public:
  166. #ifdef GSM_DEFAULT_STREAM
  167. TinyGsmBG96(Stream& stream = GSM_DEFAULT_STREAM)
  168. #else
  169. TinyGsmBG96(Stream& stream)
  170. #endif
  171. : TinyGsmMasterModem(stream), stream(stream)
  172. {
  173. memset(sockets, 0, sizeof(sockets));
  174. }
  175. /*
  176. * Basic functions
  177. */
  178. bool init(const char* pin = NULL) {
  179. if (!testAT()) {
  180. return false;
  181. }
  182. sendAT(GF("&FZE0")); // Factory + Reset + Echo Off
  183. if (waitResponse() != 1) {
  184. return false;
  185. }
  186. getSimStatus();
  187. return true;
  188. }
  189. String getModemName() {
  190. return "Quectel BG96";
  191. }
  192. void setBaud(unsigned long baud) {
  193. sendAT(GF("+IPR="), baud);
  194. }
  195. bool testAT(unsigned long timeout = 10000L) {
  196. for (unsigned long start = millis(); millis() - start < timeout; ) {
  197. sendAT(GF(""));
  198. if (waitResponse(200) == 1) {
  199. delay(100);
  200. return true;
  201. }
  202. delay(100);
  203. }
  204. return false;
  205. }
  206. void maintain() {
  207. for (int mux = 0; mux < TINY_GSM_MUX_COUNT; mux++) {
  208. GsmClient* sock = sockets[mux];
  209. if (sock && sock->got_data) {
  210. sock->got_data = false;
  211. sock->sock_available = modemGetAvailable(mux);
  212. }
  213. }
  214. while (stream.available()) {
  215. waitResponse(10, NULL, NULL);
  216. }
  217. }
  218. bool factoryDefault() {
  219. sendAT(GF("&FZE0&W")); // Factory + Reset + Echo Off + Write
  220. waitResponse();
  221. sendAT(GF("+IPR=0")); // Auto-baud
  222. waitResponse();
  223. sendAT(GF("&W")); // Write configuration
  224. return waitResponse() == 1;
  225. }
  226. String getModemInfo() {
  227. sendAT(GF("I"));
  228. String res;
  229. if (waitResponse(1000L, res) != 1) {
  230. return "";
  231. }
  232. res.replace(GSM_NL "OK" GSM_NL, "");
  233. res.replace(GSM_NL, " ");
  234. res.trim();
  235. return res;
  236. }
  237. bool hasSSL() {
  238. return false; // TODO: For now
  239. }
  240. bool hasWifi() {
  241. return false;
  242. }
  243. bool hasGPRS() {
  244. return true;
  245. }
  246. /*
  247. * Power functions
  248. */
  249. bool restart() {
  250. if (!testAT()) {
  251. return false;
  252. }
  253. sendAT(GF("+CFUN=1,1"));
  254. if (waitResponse(60000L, GF("POWERED DOWN")) != 1) {
  255. return false;
  256. }
  257. delay(3000);
  258. return init();
  259. }
  260. bool poweroff() {
  261. sendAT(GF("+QPOWD"));
  262. return waitResponse(GF("POWERED DOWN")) == 1; // TODO
  263. }
  264. bool radioOff() {
  265. sendAT(GF("+CFUN=0"));
  266. if (waitResponse(10000L) != 1) {
  267. return false;
  268. }
  269. delay(3000);
  270. return true;
  271. }
  272. /*
  273. * SIM card functions
  274. */
  275. bool simUnlock(const char *pin) {
  276. sendAT(GF("+CPIN=\""), pin, GF("\""));
  277. return waitResponse() == 1;
  278. }
  279. String getSimCCID() {
  280. sendAT(GF("+ICCID"));
  281. if (waitResponse(GF(GSM_NL "+ICCID:")) != 1) {
  282. return "";
  283. }
  284. String res = stream.readStringUntil('\n');
  285. waitResponse();
  286. res.trim();
  287. return res;
  288. }
  289. String getIMEI() {
  290. sendAT(GF("+GSN"));
  291. if (waitResponse(GF(GSM_NL)) != 1) {
  292. return "";
  293. }
  294. String res = stream.readStringUntil('\n');
  295. waitResponse();
  296. res.trim();
  297. return res;
  298. }
  299. SimStatus getSimStatus(unsigned long timeout = 10000L) {
  300. for (unsigned long start = millis(); millis() - start < timeout; ) {
  301. sendAT(GF("+CPIN?"));
  302. if (waitResponse(GF(GSM_NL "+CPIN:")) != 1) {
  303. delay(1000);
  304. continue;
  305. }
  306. int status = waitResponse(GF("READY"), GF("SIM PIN"), GF("SIM PUK"), GF("NOT INSERTED"));
  307. waitResponse();
  308. switch (status) {
  309. case 2:
  310. case 3: return SIM_LOCKED;
  311. case 1: return SIM_READY;
  312. default: return SIM_ERROR;
  313. }
  314. }
  315. return SIM_ERROR;
  316. }
  317. RegStatus getRegistrationStatus() {
  318. sendAT(GF("+CREG?"));
  319. if (waitResponse(GF(GSM_NL "+CREG:")) != 1) {
  320. return REG_UNKNOWN;
  321. }
  322. streamSkipUntil(','); // Skip format (0)
  323. int status = stream.readStringUntil('\n').toInt();
  324. waitResponse();
  325. return (RegStatus)status;
  326. }
  327. String getOperator() {
  328. sendAT(GF("+COPS?"));
  329. if (waitResponse(GF(GSM_NL "+COPS:")) != 1) {
  330. return "";
  331. }
  332. streamSkipUntil('"'); // Skip mode and format
  333. String res = stream.readStringUntil('"');
  334. waitResponse();
  335. return res;
  336. }
  337. /*
  338. * Generic network functions
  339. */
  340. int getSignalQuality() {
  341. sendAT(GF("+CSQ"));
  342. if (waitResponse(GF(GSM_NL "+CSQ:")) != 1) {
  343. return 99;
  344. }
  345. int res = stream.readStringUntil(',').toInt();
  346. waitResponse();
  347. return res;
  348. }
  349. bool isNetworkConnected() {
  350. RegStatus s = getRegistrationStatus();
  351. return (s == REG_OK_HOME || s == REG_OK_ROAMING);
  352. }
  353. /*
  354. * GPRS functions
  355. */
  356. bool gprsConnect(const char* apn, const char* user = NULL, const char* pwd = NULL) {
  357. gprsDisconnect();
  358. sendAT(GF("+QICSGP=1,1,\""), apn, GF("\",\""), user, GF("\",\""), pwd, GF("\""));
  359. if (waitResponse() != 1) {
  360. return false;
  361. }
  362. sendAT(GF("+QIACT=1"));
  363. if (waitResponse(150000L) != 1) {
  364. return false;
  365. }
  366. sendAT(GF("+CGATT=1"));
  367. if (waitResponse(60000L) != 1) {
  368. return false;
  369. }
  370. return true;
  371. }
  372. bool gprsDisconnect() {
  373. sendAT(GF("+QIDEACT=1")); // Deactivate the bearer context
  374. if (waitResponse(40000L) != 1)
  375. return false;
  376. return true;
  377. }
  378. bool isGprsConnected() {
  379. sendAT(GF("+CGATT?"));
  380. if (waitResponse(GF(GSM_NL "+CGATT:")) != 1) {
  381. return false;
  382. }
  383. int res = stream.readStringUntil('\n').toInt();
  384. waitResponse();
  385. if (res != 1)
  386. return false;
  387. return localIP() != 0;
  388. }
  389. /*
  390. * IP Address functions
  391. */
  392. String getLocalIP() {
  393. sendAT(GF("+CGPADDR=1"));
  394. if (waitResponse(10000L, GF(GSM_NL "+CGPADDR:")) != 1) {
  395. return "";
  396. }
  397. streamSkipUntil(',');
  398. String res = stream.readStringUntil('\n');
  399. if (waitResponse() != 1) {
  400. return "";
  401. }
  402. return res;
  403. }
  404. /*
  405. * Messaging functions
  406. */
  407. String sendUSSD(const String& code) TINY_GSM_ATTR_NOT_IMPLEMENTED;
  408. bool sendSMS(const String& number, const String& text) {
  409. sendAT(GF("+CMGF=1"));
  410. waitResponse();
  411. //Set GSM 7 bit default alphabet (3GPP TS 23.038)
  412. sendAT(GF("+CSCS=\"GSM\""));
  413. waitResponse();
  414. sendAT(GF("+CMGS=\""), number, GF("\""));
  415. if (waitResponse(GF(">")) != 1) {
  416. return false;
  417. }
  418. stream.print(text);
  419. stream.write((char)0x1A);
  420. stream.flush();
  421. return waitResponse(60000L) == 1;
  422. }
  423. bool sendSMS_UTF16(const String& number, const void* text, size_t len) {
  424. sendAT(GF("+CMGF=1"));
  425. waitResponse();
  426. sendAT(GF("+CSMP=17,167,0,8"));
  427. waitResponse();
  428. sendAT(GF("+CMGS=\""), number, GF("\""));
  429. if (waitResponse(GF(">")) != 1) {
  430. return false;
  431. }
  432. uint16_t* t = (uint16_t*)text;
  433. for (size_t i=0; i<len; i++) {
  434. uint8_t c = t[i] >> 8;
  435. if (c < 0x10) { stream.print('0'); }
  436. stream.print(c, HEX);
  437. c = t[i] & 0xFF;
  438. if (c < 0x10) { stream.print('0'); }
  439. stream.print(c, HEX);
  440. }
  441. stream.write((char)0x1A);
  442. stream.flush();
  443. return waitResponse(60000L) == 1;
  444. }
  445. /*
  446. * Location functions
  447. */
  448. String getGsmLocation() TINY_GSM_ATTR_NOT_AVAILABLE;
  449. /*
  450. * Battery functions
  451. */
  452. uint16_t getBattVoltage() TINY_GSM_ATTR_NOT_IMPLEMENTED;
  453. int getBattPercent() TINY_GSM_ATTR_NOT_IMPLEMENTED;
  454. protected:
  455. bool modemConnect(const char* host, uint16_t port, uint8_t mux, bool ssl = false) {
  456. int rsp;
  457. sendAT(GF("+QIOPEN=1,"), mux, ',', GF("\"TCP"), GF("\",\""), host, GF("\","), port, GF(",0,0"));
  458. rsp = waitResponse();
  459. if (waitResponse(20000L, GF(GSM_NL "+QIOPEN:")) != 1) {
  460. return false;
  461. }
  462. if (stream.readStringUntil(',').toInt() != mux) {
  463. return false;
  464. }
  465. // Read status
  466. rsp = stream.readStringUntil('\n').toInt();
  467. return (0 == rsp);
  468. }
  469. int modemSend(const void* buff, size_t len, uint8_t mux) {
  470. sendAT(GF("+QISEND="), mux, ',', len);
  471. if (waitResponse(GF(">")) != 1) {
  472. return 0;
  473. }
  474. stream.write((uint8_t*)buff, len);
  475. stream.flush();
  476. if (waitResponse(GF(GSM_NL "SEND OK")) != 1) {
  477. return 0;
  478. }
  479. // TODO: Wait for ACK? AT+QISEND=id,0
  480. return len;
  481. }
  482. size_t modemRead(size_t size, uint8_t mux) {
  483. sendAT(GF("+QIRD="), mux, ',', size);
  484. if (waitResponse(GF("+QIRD:")) != 1) {
  485. return 0;
  486. }
  487. size_t len = stream.readStringUntil('\n').toInt();
  488. for (size_t i=0; i<len; i++) {
  489. while (!stream.available()) { TINY_GSM_YIELD(); }
  490. char c = stream.read();
  491. sockets[mux]->rx.put(c);
  492. }
  493. waitResponse();
  494. DBG("### READ:", mux, ",", len);
  495. return len;
  496. }
  497. size_t modemGetAvailable(uint8_t mux) {
  498. sendAT(GF("+QIRD="), mux, GF(",0"));
  499. size_t result = 0;
  500. if (waitResponse(GF("+QIRD:")) == 1) {
  501. streamSkipUntil(','); // Skip total received
  502. streamSkipUntil(','); // Skip have read
  503. result = stream.readStringUntil('\n').toInt();
  504. DBG("### STILL:", mux, "has", result);
  505. waitResponse();
  506. }
  507. if (!result) {
  508. sockets[mux]->sock_connected = modemGetConnected(mux);
  509. }
  510. return result;
  511. }
  512. bool modemGetConnected(uint8_t mux) {
  513. sendAT(GF("+QISTATE=1,"), mux);
  514. //+QISTATE: 0,"TCP","151.139.237.11",80,5087,4,1,0,0,"uart1"
  515. if (waitResponse(GF("+QISTATE:")))
  516. return false;
  517. streamSkipUntil(','); // Skip mux
  518. streamSkipUntil(','); // Skip socket type
  519. streamSkipUntil(','); // Skip remote ip
  520. streamSkipUntil(','); // Skip remote port
  521. streamSkipUntil(','); // Skip local port
  522. int res = stream.readStringUntil(',').toInt(); // socket state
  523. waitResponse();
  524. // 0 Initial, 1 Opening, 2 Connected, 3 Listening, 4 Closing
  525. return 2 == res;
  526. }
  527. public:
  528. /* Utilities */
  529. template<typename T>
  530. void streamWrite(T last) {
  531. stream.print(last);
  532. }
  533. template<typename T, typename... Args>
  534. void streamWrite(T head, Args... tail) {
  535. stream.print(head);
  536. streamWrite(tail...);
  537. }
  538. bool streamSkipUntil(char c, const unsigned long timeout = 1000L) {
  539. unsigned long startMillis = millis();
  540. while (millis() - startMillis < timeout) {
  541. while (millis() - startMillis < timeout && !stream.available()) {
  542. TINY_GSM_YIELD();
  543. }
  544. if (stream.read() == c)
  545. return true;
  546. }
  547. return false;
  548. }
  549. template<typename... Args>
  550. void sendAT(Args... cmd) {
  551. streamWrite("AT", cmd..., GSM_NL);
  552. stream.flush();
  553. TINY_GSM_YIELD();
  554. DBG("### AT:", cmd...);
  555. }
  556. // TODO: Optimize this!
  557. uint8_t waitResponse(uint32_t timeout, String& data,
  558. GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  559. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  560. {
  561. String r1s(r1); r1s.trim();
  562. String r2s(r2); r2s.trim();
  563. String r3s(r3); r3s.trim();
  564. String r4s(r4); r4s.trim();
  565. String r5s(r5); r5s.trim();
  566. DBG("### ..:", r1s, ",", r2s, ",", r3s, ",", r4s, ",", r5s);
  567. data.reserve(64);
  568. int index = 0;
  569. unsigned long startMillis = millis();
  570. do {
  571. TINY_GSM_YIELD();
  572. while (stream.available() > 0) {
  573. int a = stream.read();
  574. if (a <= 0) continue; // Skip 0x00 bytes, just in case
  575. data += (char)a;
  576. if (r1 && data.endsWith(r1)) {
  577. index = 1;
  578. goto finish;
  579. } else if (r2 && data.endsWith(r2)) {
  580. index = 2;
  581. goto finish;
  582. } else if (r3 && data.endsWith(r3)) {
  583. index = 3;
  584. goto finish;
  585. } else if (r4 && data.endsWith(r4)) {
  586. index = 4;
  587. goto finish;
  588. } else if (r5 && data.endsWith(r5)) {
  589. index = 5;
  590. goto finish;
  591. } else if (data.endsWith(GF(GSM_NL "+QIURC:"))) {
  592. stream.readStringUntil('\"');
  593. String urc = stream.readStringUntil('\"');
  594. stream.readStringUntil(',');
  595. if (urc == "recv") {
  596. int mux = stream.readStringUntil('\n').toInt();
  597. DBG("### URC RECV:", mux);
  598. if (mux >= 0 && mux < TINY_GSM_MUX_COUNT && sockets[mux]) {
  599. sockets[mux]->got_data = true;
  600. }
  601. } else if (urc == "closed") {
  602. int mux = stream.readStringUntil('\n').toInt();
  603. DBG("### URC CLOSE:", mux);
  604. if (mux >= 0 && mux < TINY_GSM_MUX_COUNT && sockets[mux]) {
  605. sockets[mux]->sock_connected = false;
  606. }
  607. } else {
  608. stream.readStringUntil('\n');
  609. }
  610. data = "";
  611. }
  612. }
  613. } while (millis() - startMillis < timeout);
  614. finish:
  615. if (!index) {
  616. data.trim();
  617. if (data.length()) {
  618. DBG("### Unhandled:", data);
  619. }
  620. data = "";
  621. }
  622. DBG('<', index, '>');
  623. return index;
  624. }
  625. uint8_t waitResponse(uint32_t timeout,
  626. GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  627. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  628. {
  629. String data;
  630. return waitResponse(timeout, data, r1, r2, r3, r4, r5);
  631. }
  632. uint8_t waitResponse(GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  633. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  634. {
  635. return waitResponse(1000, r1, r2, r3, r4, r5);
  636. }
  637. public:
  638. Stream& stream;
  639. protected:
  640. GsmClient* sockets[TINY_GSM_MUX_COUNT];
  641. };
  642. #endif