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.

741 lines
17 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
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
  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 (!autoBaud()) {
  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. bool autoBaud(unsigned long timeout = 10000L) {
  163. for (unsigned long start = millis(); millis() - start < timeout; ) {
  164. sendAT(GF("E0"));
  165. if (waitResponse(200) == 1) {
  166. delay(100);
  167. return true;
  168. }
  169. delay(100);
  170. }
  171. return false;
  172. }
  173. void maintain() {
  174. //while (stream.available()) {
  175. waitResponse(10, NULL, NULL);
  176. //}
  177. }
  178. bool factoryDefault() {
  179. sendAT(GF("&FZE0&W")); // Factory + Reset + Echo Off + Write
  180. waitResponse();
  181. sendAT(GF("+ICF=3,1")); // 8 data 0 parity 1 stop
  182. waitResponse();
  183. sendAT(GF("+enpwrsave=0")); // Disable PWR save
  184. waitResponse();
  185. sendAT(GF("+XISP=0")); // Use internal stack
  186. waitResponse();
  187. sendAT(GF("&W")); // Write configuration
  188. return waitResponse() == 1;
  189. }
  190. String getModemInfo() {
  191. sendAT(GF("I"));
  192. String res;
  193. if (waitResponse(1000L, res) != 1) {
  194. return "";
  195. }
  196. res.replace(GSM_NL "OK" GSM_NL, "");
  197. res.replace(GSM_NL, " ");
  198. res.trim();
  199. return res;
  200. }
  201. /*
  202. * Power functions
  203. */
  204. bool restart() {
  205. if (!autoBaud()) {
  206. return false;
  207. }
  208. sendAT(GF("+CFUN=15"));
  209. if (waitResponse(10000L) != 1) {
  210. return false;
  211. }
  212. //MODEM:STARTUP
  213. waitResponse(60000L, GF(GSM_NL "+PBREADY" GSM_NL));
  214. return init();
  215. }
  216. bool poweroff() {
  217. sendAT(GF("+CPWROFF"));
  218. return waitResponse(3000L) == 1;
  219. }
  220. /*
  221. * SIM card functions
  222. */
  223. bool simUnlock(const char *pin) {
  224. sendAT(GF("+CPIN=\""), pin, GF("\""));
  225. return waitResponse() == 1;
  226. }
  227. String getSimCCID() {
  228. sendAT(GF("+CCID"));
  229. if (waitResponse(GF(GSM_NL "+CCID:")) != 1) {
  230. return "";
  231. }
  232. String res = streamReadUntil('\n');
  233. waitResponse();
  234. return res;
  235. }
  236. String getIMEI() {
  237. sendAT(GF("+GSN"));
  238. if (waitResponse(GF(GSM_NL)) != 1) {
  239. return "";
  240. }
  241. String res = streamReadUntil('\n');
  242. waitResponse();
  243. return res;
  244. }
  245. SimStatus getSimStatus(unsigned long timeout = 10000L) {
  246. for (unsigned long start = millis(); millis() - start < timeout; ) {
  247. sendAT(GF("+CPIN?"));
  248. if (waitResponse(GF(GSM_NL "+CPIN:")) != 1) {
  249. delay(1000);
  250. continue;
  251. }
  252. int status = waitResponse(GF("READY"), GF("SIM PIN"), GF("SIM PUK"));
  253. waitResponse();
  254. switch (status) {
  255. case 2:
  256. case 3: return SIM_LOCKED;
  257. case 1: return SIM_READY;
  258. default: return SIM_ERROR;
  259. }
  260. }
  261. return SIM_ERROR;
  262. }
  263. RegStatus getRegistrationStatus() {
  264. sendAT(GF("+CREG?"));
  265. if (waitResponse(GF(GSM_NL "+CREG:")) != 1) {
  266. return REG_UNKNOWN;
  267. }
  268. streamSkipUntil(','); // Skip format (0)
  269. int status = streamReadUntil('\n').toInt();
  270. waitResponse();
  271. return (RegStatus)status;
  272. }
  273. String getOperator() {
  274. sendAT(GF("+COPS?"));
  275. if (waitResponse(GF(GSM_NL "+COPS:")) != 1) {
  276. return "";
  277. }
  278. streamSkipUntil('"'); // Skip mode and format
  279. String res = streamReadUntil('"');
  280. waitResponse();
  281. return res;
  282. }
  283. /*
  284. * Generic network functions
  285. */
  286. int getSignalQuality() {
  287. sendAT(GF("+CSQ"));
  288. if (waitResponse(GF(GSM_NL "+CSQ:")) != 1) {
  289. return 99;
  290. }
  291. int res = stream.readStringUntil(',').toInt();
  292. waitResponse();
  293. return res;
  294. }
  295. bool waitForNetwork(unsigned long timeout = 60000L) {
  296. for (unsigned long start = millis(); millis() - start < timeout; ) {
  297. RegStatus s = getRegistrationStatus();
  298. if (s == REG_OK_HOME || s == REG_OK_ROAMING) {
  299. return true;
  300. }
  301. delay(1000);
  302. }
  303. return false;
  304. }
  305. /*
  306. * WiFi functions
  307. */
  308. bool networkConnect(const char* ssid, const char* pwd) {
  309. return false;
  310. }
  311. bool networkDisconnect() {
  312. return false;
  313. }
  314. /*
  315. * GPRS functions
  316. */
  317. bool gprsConnect(const char* apn, const char* user, const char* pwd) {
  318. gprsDisconnect();
  319. sendAT(GF("+XISP=0"));
  320. waitResponse();
  321. sendAT(GF("+CGDCONT=1,\"IP\",\""), apn, '"');
  322. waitResponse();
  323. if (!user) user = "";
  324. if (!pwd) pwd = "";
  325. sendAT(GF("+XGAUTH=1,1,\""), user, GF("\",\""), pwd, GF("\""));
  326. waitResponse();
  327. sendAT(GF("+XIIC=1"));
  328. waitResponse();
  329. delay(10000L); // TODO
  330. sendAT(GF("+XIIC?"));
  331. waitResponse();
  332. /*
  333. sendAT(GF("+DNSSERVER=1,8.8.8.8"));
  334. waitResponse();
  335. sendAT(GF("+DNSSERVER=2,8.8.4.4"));
  336. if (waitResponse() != 1) {
  337. return false;
  338. }
  339. */
  340. return true;
  341. }
  342. bool gprsDisconnect() {
  343. sendAT(GF("+XIIC=0"));
  344. return waitResponse(60000L) == 1;
  345. }
  346. String getLocalIP() {
  347. sendAT(GF("+XIIC?"));
  348. if (waitResponse(GF(GSM_NL "+XIIC:")) != 1) {
  349. return "";
  350. }
  351. stream.readStringUntil(',');
  352. String res = stream.readStringUntil('\n');
  353. waitResponse();
  354. res.trim();
  355. return res;
  356. }
  357. IPAddress localIP() {
  358. IPAddress res;
  359. res.fromString(getLocalIP());
  360. return res;
  361. }
  362. /*
  363. * Phone Call functions
  364. */
  365. bool setGsmBusy(bool busy = true) TINY_GSM_ATTR_NOT_AVAILABLE;
  366. bool callAnswer() TINY_GSM_ATTR_NOT_AVAILABLE;
  367. bool callNumber(const String& number) TINY_GSM_ATTR_NOT_AVAILABLE;
  368. bool callRedial() TINY_GSM_ATTR_NOT_AVAILABLE;
  369. bool callHangup() TINY_GSM_ATTR_NOT_AVAILABLE;
  370. /*
  371. * Messaging functions
  372. */
  373. String sendUSSD(const String& code) {
  374. sendAT(GF("+CMGF=1"));
  375. waitResponse();
  376. sendAT(GF("+CSCS=\"HEX\""));
  377. waitResponse();
  378. sendAT(GF("D"), code);
  379. if (waitResponse(10000L, GF(GSM_NL "+CUSD:")) != 1) {
  380. return "";
  381. }
  382. stream.readStringUntil('"');
  383. String hex = stream.readStringUntil('"');
  384. stream.readStringUntil(',');
  385. int dcs = stream.readStringUntil('\n').toInt();
  386. if (waitResponse() != 1) {
  387. return "";
  388. }
  389. if (dcs == 15) {
  390. return decodeHex8bit(hex);
  391. } else if (dcs == 72) {
  392. return decodeHex16bit(hex);
  393. } else {
  394. return hex;
  395. }
  396. }
  397. bool sendSMS(const String& number, const String& text) {
  398. sendAT(GF("+CSCS=\"GSM\""));
  399. waitResponse();
  400. sendAT(GF("+CMGF=1"));
  401. waitResponse();
  402. sendAT(GF("+CMGS=\""), number, GF("\""));
  403. if (waitResponse(GF(">")) != 1) {
  404. return false;
  405. }
  406. stream.print(text);
  407. stream.write((char)0x1A);
  408. stream.flush();
  409. return waitResponse(60000L) == 1;
  410. }
  411. bool sendSMS_UTF16(const String& number, const void* text, size_t len)
  412. TINY_GSM_ATTR_NOT_AVAILABLE;
  413. /*
  414. * Location functions
  415. */
  416. String getGsmLocation() TINY_GSM_ATTR_NOT_AVAILABLE;
  417. /*
  418. * Battery functions
  419. */
  420. uint16_t getBattVoltage() TINY_GSM_ATTR_NOT_AVAILABLE;
  421. int getBattPercent() TINY_GSM_ATTR_NOT_AVAILABLE;
  422. private:
  423. bool modemConnect(const char* host, uint16_t port, uint8_t mux) {
  424. for (int i=0; i<3; i++) { // TODO: no need for loop?
  425. String ip = dnsIpQuery(host);
  426. sendAT(GF("+TCPSETUP="), mux, GF(","), ip, GF(","), port);
  427. int rsp = waitResponse(75000L,
  428. GF(",OK" GSM_NL),
  429. GF(",FAIL" GSM_NL),
  430. GF("+TCPSETUP:Error" GSM_NL));
  431. if (1 == rsp) {
  432. return true;
  433. } else if (3 == rsp) {
  434. sendAT(GF("+TCPCLOSE="), mux);
  435. waitResponse();
  436. }
  437. delay(1000);
  438. }
  439. return false;
  440. }
  441. int modemSend(const void* buff, size_t len, uint8_t mux) {
  442. sendAT(GF("+TCPSEND="), mux, ',', len);
  443. if (waitResponse(GF(">")) != 1) {
  444. return 0;
  445. }
  446. stream.write((uint8_t*)buff, len);
  447. stream.write((char)0x0D);
  448. stream.flush();
  449. if (waitResponse(30000L, GF(GSM_NL "+TCPSEND:")) != 1) {
  450. return 0;
  451. }
  452. streamReadUntil('\n');
  453. return len;
  454. }
  455. bool modemGetConnected(uint8_t mux) {
  456. sendAT(GF("+CIPSTATUS="), mux);
  457. int res = waitResponse(GF(",\"CONNECTED\""), GF(",\"CLOSED\""), GF(",\"CLOSING\""), GF(",\"INITIAL\""));
  458. waitResponse();
  459. return 1 == res;
  460. }
  461. String dnsIpQuery(const char* host) {
  462. sendAT(GF("+DNS=\""), host, GF("\""));
  463. if (waitResponse(10000L, GF(GSM_NL "+DNS:")) != 1) {
  464. return "";
  465. }
  466. String res = stream.readStringUntil('\n');
  467. waitResponse(GF("+DNS:OK" GSM_NL));
  468. res.trim();
  469. return res;
  470. }
  471. static String decodeHex8bit(String &instr) {
  472. String result;
  473. for (unsigned i=0; i<instr.length(); i+=2) {
  474. char buf[4] = { 0, };
  475. buf[0] = instr[i];
  476. buf[1] = instr[i+1];
  477. char b = strtol(buf, NULL, 16);
  478. result += b;
  479. }
  480. return result;
  481. }
  482. static String decodeHex16bit(String &instr) {
  483. String result;
  484. for (unsigned i=0; i<instr.length(); i+=4) {
  485. char buf[4] = { 0, };
  486. buf[0] = instr[i];
  487. buf[1] = instr[i+1];
  488. char b = strtol(buf, NULL, 16);
  489. if (b) { // If high byte is non-zero, we can't handle it ;(
  490. b = '?';
  491. } else {
  492. buf[0] = instr[i+2];
  493. buf[1] = instr[i+3];
  494. b = strtol(buf, NULL, 16);
  495. }
  496. result += b;
  497. }
  498. return result;
  499. }
  500. public:
  501. /* Utilities */
  502. template<typename T>
  503. void streamWrite(T last) {
  504. stream.print(last);
  505. }
  506. template<typename T, typename... Args>
  507. void streamWrite(T head, Args... tail) {
  508. stream.print(head);
  509. streamWrite(tail...);
  510. }
  511. bool streamSkipUntil(char c) { //TODO: timeout
  512. while (true) {
  513. while (!stream.available()) { TINY_GSM_YIELD(); }
  514. if (stream.read() == c)
  515. return true;
  516. }
  517. return false;
  518. }
  519. template<typename... Args>
  520. void sendAT(Args... cmd) {
  521. streamWrite("AT", cmd..., GSM_NL);
  522. stream.flush();
  523. TINY_GSM_YIELD();
  524. DBG(GSM_NL, ">>> AT:", cmd...);
  525. }
  526. // TODO: Optimize this!
  527. uint8_t waitResponse(uint32_t timeout, String& data,
  528. GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  529. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  530. {
  531. /*String r1s(r1); r1s.trim();
  532. String r2s(r2); r2s.trim();
  533. String r3s(r3); r3s.trim();
  534. String r4s(r4); r4s.trim();
  535. String r5s(r5); r5s.trim();
  536. DBG("### ..:", r1s, ",", r2s, ",", r3s, ",", r4s, ",", r5s);*/
  537. data.reserve(64);
  538. bool gotData = false;
  539. int mux = -1;
  540. int len = 0;
  541. int index = 0;
  542. unsigned long startMillis = millis();
  543. do {
  544. TINY_GSM_YIELD();
  545. while (stream.available() > 0) {
  546. int a = stream.read();
  547. if (a <= 0) continue; // Skip 0x00 bytes, just in case
  548. data += (char)a;
  549. if (r1 && data.endsWith(r1)) {
  550. index = 1;
  551. goto finish;
  552. } else if (r2 && data.endsWith(r2)) {
  553. index = 2;
  554. goto finish;
  555. } else if (r3 && data.endsWith(r3)) {
  556. index = 3;
  557. goto finish;
  558. } else if (r4 && data.endsWith(r4)) {
  559. index = 4;
  560. goto finish;
  561. } else if (r5 && data.endsWith(r5)) {
  562. index = 5;
  563. goto finish;
  564. } else if (data.endsWith(GF("+TCPRECV:"))) {
  565. int mux = stream.readStringUntil(',').toInt();
  566. int len = stream.readStringUntil(',').toInt();
  567. if (len > sockets[mux]->rx.free()) {
  568. DBG("### Buffer overflow: ", len, "->", sockets[mux]->rx.free());
  569. } else {
  570. DBG("### Got: ", len, "->", sockets[mux]->rx.free());
  571. }
  572. while (len--) {
  573. while (!stream.available()) { TINY_GSM_YIELD(); }
  574. sockets[mux]->rx.put(stream.read());
  575. }
  576. data = "";
  577. } else if (data.endsWith(GF("+TCPCLOSE:"))) {
  578. int mux = stream.readStringUntil(',').toInt();
  579. stream.readStringUntil('\n');
  580. if (mux >= 0 && mux < TINY_GSM_MUX_COUNT) {
  581. sockets[mux]->sock_connected = false;
  582. }
  583. data = "";
  584. DBG("### Closed: ", mux);
  585. }
  586. }
  587. } while (millis() - startMillis < timeout);
  588. finish:
  589. if (!index) {
  590. data.trim();
  591. if (data.length()) {
  592. DBG(GSM_NL, "### Unhandled:", data);
  593. }
  594. }
  595. else {
  596. data.trim();
  597. data.replace(GSM_NL GSM_NL, GSM_NL);
  598. data.replace(GSM_NL, GSM_NL " ");
  599. if (data.length()) {
  600. DBG(GSM_NL, "<<< ", data);
  601. }
  602. }
  603. if (gotData) {
  604. int len_orig = len;
  605. if (len > sockets[mux]->rx.free()) {
  606. DBG(GSM_NL, "### Buffer overflow: ", len, "->", sockets[mux]->rx.free());
  607. } else {
  608. DBG(GSM_NL, "### Got: ", len, "->", sockets[mux]->rx.free());
  609. }
  610. while (len--) {
  611. TINY_GSM_YIELD();
  612. int r = stream.read();
  613. if (r <= 0) continue; // Skip 0x00 bytes, just in case
  614. sockets[mux]->rx.put((char)r);
  615. }
  616. if (len_orig > sockets[mux]->available()) {
  617. DBG(GSM_NL, "### Fewer characters received than expected: ", sockets[mux]->available(), " vs ", len_orig);
  618. }
  619. }
  620. return index;
  621. }
  622. uint8_t waitResponse(uint32_t timeout,
  623. GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  624. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  625. {
  626. String data;
  627. return waitResponse(timeout, data, r1, r2, r3, r4, r5);
  628. }
  629. uint8_t waitResponse(GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  630. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  631. {
  632. return waitResponse(1000, r1, r2, r3, r4, r5);
  633. }
  634. private:
  635. Stream& stream;
  636. GsmClient* sockets[TINY_GSM_MUX_COUNT];
  637. };
  638. #endif