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.

704 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
7 years ago
7 years ago
7 years ago
8 years ago
7 years ago
8 years ago
8 years ago
7 years ago
8 years ago
8 years ago
7 years ago
8 years ago
8 years ago
8 years ago
7 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
7 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 TinyGsmClientM590.h
  3. * @author Volodymyr Shymanskyy
  4. * @license LGPL-3.0
  5. * @copyright Copyright (c) 2016 Volodymyr Shymanskyy
  6. * @date Nov 2016
  7. */
  8. #ifndef TinyGsmClientM590_h
  9. #define TinyGsmClientM590_h
  10. //#define TINY_GSM_DEBUG Serial
  11. #if !defined(TINY_GSM_RX_BUFFER)
  12. #define TINY_GSM_RX_BUFFER 256
  13. #endif
  14. #define TINY_GSM_MUX_COUNT 2
  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 = 3,
  27. REG_DENIED = 2,
  28. REG_OK_HOME = 1,
  29. REG_OK_ROAMING = 5,
  30. REG_UNKNOWN = 4,
  31. };
  32. class TinyGsm
  33. {
  34. public:
  35. class GsmClient : public Client
  36. {
  37. friend class TinyGsm;
  38. typedef TinyGsmFifo<uint8_t, TINY_GSM_RX_BUFFER> RxFifo;
  39. public:
  40. GsmClient() {}
  41. GsmClient(TinyGsm& modem, uint8_t mux = 1) {
  42. init(&modem, mux);
  43. }
  44. bool init(TinyGsm* modem, uint8_t mux = 1) {
  45. this->at = modem;
  46. this->mux = mux;
  47. sock_connected = false;
  48. at->sockets[mux] = this;
  49. return true;
  50. }
  51. public:
  52. virtual int connect(const char *host, uint16_t port) {
  53. TINY_GSM_YIELD();
  54. rx.clear();
  55. sock_connected = at->modemConnect(host, port, mux);
  56. return sock_connected;
  57. }
  58. virtual int connect(IPAddress ip, uint16_t port) {
  59. String host; host.reserve(16);
  60. host += ip[0];
  61. host += ".";
  62. host += ip[1];
  63. host += ".";
  64. host += ip[2];
  65. host += ".";
  66. host += ip[3];
  67. return connect(host.c_str(), port);
  68. }
  69. virtual void stop() {
  70. TINY_GSM_YIELD();
  71. at->sendAT(GF("+TCPCLOSE="), mux);
  72. sock_connected = false;
  73. at->waitResponse();
  74. }
  75. virtual size_t write(const uint8_t *buf, size_t size) {
  76. TINY_GSM_YIELD();
  77. //at->maintain();
  78. return at->modemSend(buf, size, mux);
  79. }
  80. virtual size_t write(uint8_t c) {
  81. return write(&c, 1);
  82. }
  83. virtual int available() {
  84. TINY_GSM_YIELD();
  85. if (!rx.size() && sock_connected) {
  86. at->maintain();
  87. }
  88. return rx.size();
  89. }
  90. virtual int read(uint8_t *buf, size_t size) {
  91. TINY_GSM_YIELD();
  92. size_t cnt = 0;
  93. while (cnt < size) {
  94. size_t chunk = TinyGsmMin(size-cnt, rx.size());
  95. if (chunk > 0) {
  96. rx.get(buf, chunk);
  97. buf += chunk;
  98. cnt += chunk;
  99. continue;
  100. }
  101. // TODO: Read directly into user buffer?
  102. if (!rx.size()) {
  103. at->maintain();
  104. //break;
  105. }
  106. }
  107. return cnt;
  108. }
  109. virtual int read() {
  110. uint8_t c;
  111. if (read(&c, 1) == 1) {
  112. return c;
  113. }
  114. return -1;
  115. }
  116. virtual int peek() { return -1; } //TODO
  117. virtual void flush() { at->stream.flush(); }
  118. virtual uint8_t connected() {
  119. if (available()) {
  120. return true;
  121. }
  122. return sock_connected;
  123. }
  124. virtual operator bool() { return connected(); }
  125. /*
  126. * Extended API
  127. */
  128. String remoteIP() TINY_GSM_ATTR_NOT_IMPLEMENTED;
  129. private:
  130. TinyGsm* at;
  131. uint8_t mux;
  132. bool sock_connected;
  133. RxFifo rx;
  134. };
  135. public:
  136. TinyGsm(Stream& stream)
  137. : stream(stream)
  138. {
  139. memset(sockets, 0, sizeof(sockets));
  140. }
  141. /*
  142. * Basic functions
  143. */
  144. bool begin() {
  145. return init();
  146. }
  147. bool init() {
  148. if (!testAT()) {
  149. return false;
  150. }
  151. sendAT(GF("&FZE0")); // Factory + Reset + Echo Off
  152. if (waitResponse() != 1) {
  153. return false;
  154. }
  155. #ifdef TINY_GSM_DEBUG
  156. sendAT(GF("+CMEE=2"));
  157. waitResponse();
  158. #endif
  159. getSimStatus();
  160. return true;
  161. }
  162. void setBaud(unsigned long baud) {
  163. sendAT(GF("+IPR="), baud);
  164. }
  165. bool testAT(unsigned long timeout = 10000L) {
  166. for (unsigned long start = millis(); millis() - start < timeout; ) {
  167. sendAT(GF(""));
  168. if (waitResponse(200) == 1) {
  169. delay(100);
  170. return true;
  171. }
  172. delay(100);
  173. }
  174. return false;
  175. }
  176. void maintain() {
  177. //while (stream.available()) {
  178. waitResponse(10, NULL, NULL);
  179. //}
  180. }
  181. bool factoryDefault() {
  182. sendAT(GF("&FZE0&W")); // Factory + Reset + Echo Off + Write
  183. waitResponse();
  184. sendAT(GF("+ICF=3,1")); // 8 data 0 parity 1 stop
  185. waitResponse();
  186. sendAT(GF("+ENPWRSAVE=0")); // Disable PWR save
  187. waitResponse();
  188. sendAT(GF("+XISP=0")); // Use internal stack
  189. waitResponse();
  190. sendAT(GF("&W")); // Write configuration
  191. return waitResponse() == 1;
  192. }
  193. String getModemInfo() {
  194. sendAT(GF("I"));
  195. String res;
  196. if (waitResponse(1000L, res) != 1) {
  197. return "";
  198. }
  199. res.replace(GSM_NL "OK" GSM_NL, "");
  200. res.replace(GSM_NL, " ");
  201. res.trim();
  202. return res;
  203. }
  204. /*
  205. * Power functions
  206. */
  207. bool restart() {
  208. if (!testAT()) {
  209. return false;
  210. }
  211. sendAT(GF("+CFUN=15"));
  212. if (waitResponse(10000L) != 1) {
  213. return false;
  214. }
  215. //MODEM:STARTUP
  216. waitResponse(60000L, GF(GSM_NL "+PBREADY" GSM_NL));
  217. return init();
  218. }
  219. bool poweroff() {
  220. sendAT(GF("+CPWROFF"));
  221. return waitResponse(3000L) == 1;
  222. }
  223. bool radioOff() TINY_GSM_ATTR_NOT_IMPLEMENTED;
  224. bool sleepEnable(bool enable = true) {
  225. sendAT(GF("+ENPWRSAVE="), enable);
  226. return waitResponse() == 1;
  227. }
  228. /*
  229. * SIM card functions
  230. */
  231. bool simUnlock(const char *pin) {
  232. sendAT(GF("+CPIN=\""), pin, GF("\""));
  233. return waitResponse() == 1;
  234. }
  235. String getSimCCID() {
  236. sendAT(GF("+CCID"));
  237. if (waitResponse(GF(GSM_NL "+CCID:")) != 1) {
  238. return "";
  239. }
  240. String res = stream.readStringUntil('\n');
  241. waitResponse();
  242. res.trim();
  243. return res;
  244. }
  245. String getIMEI() {
  246. sendAT(GF("+GSN"));
  247. if (waitResponse(GF(GSM_NL)) != 1) {
  248. return "";
  249. }
  250. String res = stream.readStringUntil('\n');
  251. waitResponse();
  252. res.trim();
  253. return res;
  254. }
  255. SimStatus getSimStatus(unsigned long timeout = 10000L) {
  256. for (unsigned long start = millis(); millis() - start < timeout; ) {
  257. sendAT(GF("+CPIN?"));
  258. if (waitResponse(GF(GSM_NL "+CPIN:")) != 1) {
  259. delay(1000);
  260. continue;
  261. }
  262. int status = waitResponse(GF("READY"), GF("SIM PIN"), GF("SIM PUK"));
  263. waitResponse();
  264. switch (status) {
  265. case 2:
  266. case 3: return SIM_LOCKED;
  267. case 1: return SIM_READY;
  268. default: return SIM_ERROR;
  269. }
  270. }
  271. return SIM_ERROR;
  272. }
  273. RegStatus getRegistrationStatus() {
  274. sendAT(GF("+CREG?"));
  275. if (waitResponse(GF(GSM_NL "+CREG:")) != 1) {
  276. return REG_UNKNOWN;
  277. }
  278. streamSkipUntil(','); // Skip format (0)
  279. int status = stream.readStringUntil('\n').toInt();
  280. waitResponse();
  281. return (RegStatus)status;
  282. }
  283. String getOperator() {
  284. sendAT(GF("+COPS?"));
  285. if (waitResponse(GF(GSM_NL "+COPS:")) != 1) {
  286. return "";
  287. }
  288. streamSkipUntil('"'); // Skip mode and format
  289. String res = stream.readStringUntil('"');
  290. waitResponse();
  291. return res;
  292. }
  293. /*
  294. * Generic network functions
  295. */
  296. int getSignalQuality() {
  297. sendAT(GF("+CSQ"));
  298. if (waitResponse(GF(GSM_NL "+CSQ:")) != 1) {
  299. return 99;
  300. }
  301. int res = stream.readStringUntil(',').toInt();
  302. waitResponse();
  303. return res;
  304. }
  305. bool isNetworkConnected() {
  306. RegStatus s = getRegistrationStatus();
  307. return (s == REG_OK_HOME || s == REG_OK_ROAMING);
  308. }
  309. bool waitForNetwork(unsigned long timeout = 60000L) {
  310. for (unsigned long start = millis(); millis() - start < timeout; ) {
  311. if (isNetworkConnected()) {
  312. return true;
  313. }
  314. delay(500);
  315. }
  316. return false;
  317. }
  318. /*
  319. * GPRS functions
  320. */
  321. bool gprsConnect(const char* apn, const char* user, const char* pwd) {
  322. gprsDisconnect();
  323. sendAT(GF("+XISP=0"));
  324. waitResponse();
  325. sendAT(GF("+CGDCONT=1,\"IP\",\""), apn, '"');
  326. waitResponse();
  327. if (!user) user = "";
  328. if (!pwd) pwd = "";
  329. sendAT(GF("+XGAUTH=1,1,\""), user, GF("\",\""), pwd, GF("\""));
  330. waitResponse();
  331. sendAT(GF("+XIIC=1"));
  332. waitResponse();
  333. const unsigned long timeout = 60000L;
  334. for (unsigned long start = millis(); millis() - start < timeout; ) {
  335. if (isGprsConnected()) {
  336. //goto set_dns; // TODO
  337. return true;
  338. }
  339. delay(500);
  340. }
  341. return false;
  342. set_dns:
  343. sendAT(GF("+DNSSERVER=1,8.8.8.8"));
  344. waitResponse();
  345. sendAT(GF("+DNSSERVER=2,8.8.4.4"));
  346. waitResponse();
  347. return true;
  348. }
  349. bool gprsDisconnect() {
  350. // TODO: There is no command in AT command set
  351. // XIIC=0 does not work
  352. return true;
  353. }
  354. bool isGprsConnected() {
  355. sendAT(GF("+XIIC?"));
  356. if (waitResponse(GF(GSM_NL "+XIIC:")) != 1) {
  357. return false;
  358. }
  359. int res = stream.readStringUntil(',').toInt();
  360. waitResponse();
  361. return res == 1;
  362. }
  363. String getLocalIP() {
  364. sendAT(GF("+XIIC?"));
  365. if (waitResponse(GF(GSM_NL "+XIIC:")) != 1) {
  366. return "";
  367. }
  368. stream.readStringUntil(',');
  369. String res = stream.readStringUntil('\n');
  370. waitResponse();
  371. res.trim();
  372. return res;
  373. }
  374. IPAddress localIP() {
  375. return TinyGsmIpFromString(getLocalIP());
  376. }
  377. /*
  378. * Phone Call functions
  379. */
  380. bool setGsmBusy(bool busy = true) TINY_GSM_ATTR_NOT_AVAILABLE;
  381. bool callAnswer() TINY_GSM_ATTR_NOT_AVAILABLE;
  382. bool callNumber(const String& number) TINY_GSM_ATTR_NOT_AVAILABLE;
  383. bool callRedial() TINY_GSM_ATTR_NOT_AVAILABLE;
  384. bool callHangup() TINY_GSM_ATTR_NOT_AVAILABLE;
  385. /*
  386. * Messaging functions
  387. */
  388. String sendUSSD(const String& code) {
  389. sendAT(GF("+CMGF=1"));
  390. waitResponse();
  391. sendAT(GF("+CSCS=\"HEX\""));
  392. waitResponse();
  393. sendAT(GF("D"), code);
  394. if (waitResponse(10000L, GF(GSM_NL "+CUSD:")) != 1) {
  395. return "";
  396. }
  397. stream.readStringUntil('"');
  398. String hex = stream.readStringUntil('"');
  399. stream.readStringUntil(',');
  400. int dcs = stream.readStringUntil('\n').toInt();
  401. if (waitResponse() != 1) {
  402. return "";
  403. }
  404. if (dcs == 15) {
  405. return TinyGsmDecodeHex8bit(hex);
  406. } else if (dcs == 72) {
  407. return TinyGsmDecodeHex16bit(hex);
  408. } else {
  409. return hex;
  410. }
  411. }
  412. bool sendSMS(const String& number, const String& text) {
  413. sendAT(GF("+CSCS=\"GSM\""));
  414. waitResponse();
  415. sendAT(GF("+CMGF=1"));
  416. waitResponse();
  417. sendAT(GF("+CMGS=\""), number, GF("\""));
  418. if (waitResponse(GF(">")) != 1) {
  419. return false;
  420. }
  421. stream.print(text);
  422. stream.write((char)0x1A);
  423. stream.flush();
  424. return waitResponse(60000L) == 1;
  425. }
  426. bool sendSMS_UTF16(const String& number, const void* text, size_t len)
  427. TINY_GSM_ATTR_NOT_AVAILABLE;
  428. /*
  429. * Location functions
  430. */
  431. String getGsmLocation() TINY_GSM_ATTR_NOT_AVAILABLE;
  432. /*
  433. * Battery functions
  434. */
  435. uint16_t getBattVoltage() TINY_GSM_ATTR_NOT_AVAILABLE;
  436. int getBattPercent() TINY_GSM_ATTR_NOT_AVAILABLE;
  437. protected:
  438. bool modemConnect(const char* host, uint16_t port, uint8_t mux) {
  439. for (int i=0; i<3; i++) { // TODO: no need for loop?
  440. String ip = dnsIpQuery(host);
  441. sendAT(GF("+TCPSETUP="), mux, GF(","), ip, GF(","), port);
  442. int rsp = waitResponse(75000L,
  443. GF(",OK" GSM_NL),
  444. GF(",FAIL" GSM_NL),
  445. GF("+TCPSETUP:Error" GSM_NL));
  446. if (1 == rsp) {
  447. return true;
  448. } else if (3 == rsp) {
  449. sendAT(GF("+TCPCLOSE="), mux);
  450. waitResponse();
  451. }
  452. delay(1000);
  453. }
  454. return false;
  455. }
  456. int modemSend(const void* buff, size_t len, uint8_t mux) {
  457. sendAT(GF("+TCPSEND="), mux, ',', len);
  458. if (waitResponse(GF(">")) != 1) {
  459. return 0;
  460. }
  461. stream.write((uint8_t*)buff, len);
  462. stream.write((char)0x0D);
  463. stream.flush();
  464. if (waitResponse(30000L, GF(GSM_NL "+TCPSEND:")) != 1) {
  465. return 0;
  466. }
  467. stream.readStringUntil('\n');
  468. return len;
  469. }
  470. bool modemGetConnected(uint8_t mux) {
  471. sendAT(GF("+CIPSTATUS="), mux);
  472. int res = waitResponse(GF(",\"CONNECTED\""), GF(",\"CLOSED\""), GF(",\"CLOSING\""), GF(",\"INITIAL\""));
  473. waitResponse();
  474. return 1 == res;
  475. }
  476. String dnsIpQuery(const char* host) {
  477. sendAT(GF("+DNS=\""), host, GF("\""));
  478. if (waitResponse(10000L, GF(GSM_NL "+DNS:")) != 1) {
  479. return "";
  480. }
  481. String res = stream.readStringUntil('\n');
  482. waitResponse(GF("+DNS:OK" GSM_NL));
  483. res.trim();
  484. return res;
  485. }
  486. public:
  487. /* Utilities */
  488. template<typename T>
  489. void streamWrite(T last) {
  490. stream.print(last);
  491. }
  492. template<typename T, typename... Args>
  493. void streamWrite(T head, Args... tail) {
  494. stream.print(head);
  495. streamWrite(tail...);
  496. }
  497. bool streamSkipUntil(char c) { //TODO: timeout
  498. while (true) {
  499. while (!stream.available()) { TINY_GSM_YIELD(); }
  500. if (stream.read() == c)
  501. return true;
  502. }
  503. return false;
  504. }
  505. template<typename... Args>
  506. void sendAT(Args... cmd) {
  507. streamWrite("AT", cmd..., GSM_NL);
  508. stream.flush();
  509. TINY_GSM_YIELD();
  510. //DBG("### AT:", cmd...);
  511. }
  512. // TODO: Optimize this!
  513. uint8_t waitResponse(uint32_t timeout, String& data,
  514. GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  515. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  516. {
  517. /*String r1s(r1); r1s.trim();
  518. String r2s(r2); r2s.trim();
  519. String r3s(r3); r3s.trim();
  520. String r4s(r4); r4s.trim();
  521. String r5s(r5); r5s.trim();
  522. DBG("### ..:", r1s, ",", r2s, ",", r3s, ",", r4s, ",", r5s);*/
  523. data.reserve(64);
  524. int index = 0;
  525. unsigned long startMillis = millis();
  526. do {
  527. TINY_GSM_YIELD();
  528. while (stream.available() > 0) {
  529. int a = stream.read();
  530. if (a <= 0) continue; // Skip 0x00 bytes, just in case
  531. data += (char)a;
  532. if (r1 && data.endsWith(r1)) {
  533. index = 1;
  534. goto finish;
  535. } else if (r2 && data.endsWith(r2)) {
  536. index = 2;
  537. goto finish;
  538. } else if (r3 && data.endsWith(r3)) {
  539. index = 3;
  540. goto finish;
  541. } else if (r4 && data.endsWith(r4)) {
  542. index = 4;
  543. goto finish;
  544. } else if (r5 && data.endsWith(r5)) {
  545. index = 5;
  546. goto finish;
  547. } else if (data.endsWith(GF("+TCPRECV:"))) {
  548. int mux = stream.readStringUntil(',').toInt();
  549. int len = stream.readStringUntil(',').toInt();
  550. int len_orig = len;
  551. if (len > sockets[mux]->rx.free()) {
  552. DBG("### Buffer overflow: ", len, "->", sockets[mux]->rx.free());
  553. } else {
  554. DBG("### Got: ", len, "->", sockets[mux]->rx.free());
  555. }
  556. while (len--) {
  557. while (!stream.available()) { TINY_GSM_YIELD(); }
  558. sockets[mux]->rx.put(stream.read());
  559. }
  560. if (len_orig > sockets[mux]->available()) { // TODO
  561. DBG(GSM_NL, "### Fewer characters received than expected: ", sockets[mux]->available(), " vs ", len_orig);
  562. }
  563. data = "";
  564. } else if (data.endsWith(GF("+TCPCLOSE:"))) {
  565. int mux = stream.readStringUntil(',').toInt();
  566. stream.readStringUntil('\n');
  567. if (mux >= 0 && mux < TINY_GSM_MUX_COUNT) {
  568. sockets[mux]->sock_connected = false;
  569. }
  570. data = "";
  571. DBG("### Closed: ", mux);
  572. }
  573. }
  574. } while (millis() - startMillis < timeout);
  575. finish:
  576. if (!index) {
  577. data.trim();
  578. if (data.length()) {
  579. DBG("### Unhandled:", data);
  580. }
  581. data = "";
  582. }
  583. return index;
  584. }
  585. uint8_t waitResponse(uint32_t timeout,
  586. GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  587. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  588. {
  589. String data;
  590. return waitResponse(timeout, data, r1, r2, r3, r4, r5);
  591. }
  592. uint8_t waitResponse(GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  593. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  594. {
  595. return waitResponse(1000, r1, r2, r3, r4, r5);
  596. }
  597. protected:
  598. Stream& stream;
  599. GsmClient* sockets[TINY_GSM_MUX_COUNT];
  600. };
  601. #endif