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.

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