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.

643 lines
14 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
  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. #include <TinyGsmCommon.h>
  15. #define GSM_NL "\r\n"
  16. static const char GSM_OK[] TINY_GSM_PROGMEM = "OK" GSM_NL;
  17. static const char GSM_ERROR[] TINY_GSM_PROGMEM = "ERROR" GSM_NL;
  18. enum SimStatus {
  19. SIM_ERROR = 0,
  20. SIM_READY = 1,
  21. SIM_LOCKED = 2,
  22. };
  23. enum RegStatus {
  24. REG_UNREGISTERED = 0,
  25. REG_SEARCHING = 3,
  26. REG_DENIED = 2,
  27. REG_OK_HOME = 1,
  28. REG_OK_ROAMING = 5,
  29. REG_UNKNOWN = 4,
  30. };
  31. class TinyGsm
  32. {
  33. public:
  34. TinyGsm(Stream& stream)
  35. : stream(stream)
  36. {}
  37. public:
  38. class GsmClient : public Client
  39. {
  40. friend class TinyGsm;
  41. typedef TinyGsmFifo<uint8_t, TINY_GSM_RX_BUFFER> RxFifo;
  42. public:
  43. GsmClient() {}
  44. GsmClient(TinyGsm& modem, uint8_t mux = 1) {
  45. init(&modem, mux);
  46. }
  47. bool init(TinyGsm* modem, uint8_t mux = 1) {
  48. this->at = modem;
  49. this->mux = mux;
  50. sock_connected = false;
  51. at->sockets[mux] = this;
  52. return true;
  53. }
  54. public:
  55. virtual int connect(const char *host, uint16_t port) {
  56. TINY_GSM_YIELD();
  57. rx.clear();
  58. sock_connected = at->modemConnect(host, port, mux);
  59. return sock_connected;
  60. }
  61. virtual int connect(IPAddress ip, uint16_t port) {
  62. String host; host.reserve(16);
  63. host += ip[0];
  64. host += ".";
  65. host += ip[1];
  66. host += ".";
  67. host += ip[2];
  68. host += ".";
  69. host += ip[3];
  70. return connect(host.c_str(), port);
  71. }
  72. virtual void stop() {
  73. TINY_GSM_YIELD();
  74. at->sendAT(GF("+TCPCLOSE="), mux);
  75. sock_connected = false;
  76. at->waitResponse();
  77. }
  78. virtual size_t write(const uint8_t *buf, size_t size) {
  79. TINY_GSM_YIELD();
  80. //at->maintain();
  81. return at->modemSend(buf, size, mux);
  82. }
  83. virtual size_t write(uint8_t c) {
  84. return write(&c, 1);
  85. }
  86. virtual int available() {
  87. TINY_GSM_YIELD();
  88. if (!rx.size()) {
  89. at->maintain();
  90. }
  91. return rx.size();
  92. }
  93. virtual int read(uint8_t *buf, size_t size) {
  94. TINY_GSM_YIELD();
  95. size_t cnt = 0;
  96. while (cnt < size) {
  97. size_t chunk = TinyGsmMin(size-cnt, rx.size());
  98. if (chunk > 0) {
  99. rx.get(buf, chunk);
  100. buf += chunk;
  101. cnt += chunk;
  102. continue;
  103. }
  104. // TODO: Read directly into user buffer?
  105. if (!rx.size()) {
  106. at->maintain();
  107. //break;
  108. }
  109. }
  110. return cnt;
  111. }
  112. virtual int read() {
  113. uint8_t c;
  114. if (read(&c, 1) == 1) {
  115. return c;
  116. }
  117. return -1;
  118. }
  119. virtual int peek() { return -1; } //TODO
  120. virtual void flush() { at->stream.flush(); }
  121. virtual uint8_t connected() {
  122. if (available()) {
  123. return true;
  124. }
  125. return sock_connected;
  126. }
  127. virtual operator bool() { return connected(); }
  128. private:
  129. TinyGsm* at;
  130. uint8_t mux;
  131. bool sock_connected;
  132. RxFifo rx;
  133. };
  134. public:
  135. /*
  136. * Basic functions
  137. */
  138. bool begin() {
  139. return init();
  140. }
  141. bool init() {
  142. if (!autoBaud()) {
  143. return false;
  144. }
  145. sendAT(GF("&FZE0")); // Factory + Reset + Echo Off
  146. if (waitResponse() != 1) {
  147. return false;
  148. }
  149. #ifdef TINY_GSM_DEBUG
  150. sendAT(GF("+CMEE=2"));
  151. waitResponse();
  152. #endif
  153. getSimStatus();
  154. return true;
  155. }
  156. bool autoBaud(unsigned long timeout = 10000L) {
  157. for (unsigned long start = millis(); millis() - start < timeout; ) {
  158. sendAT(GF("E0"));
  159. if (waitResponse(200) == 1) {
  160. delay(100);
  161. return true;
  162. }
  163. delay(100);
  164. }
  165. return false;
  166. }
  167. void maintain() {
  168. //while (stream.available()) {
  169. waitResponse(10, NULL, NULL);
  170. //}
  171. }
  172. bool factoryDefault() {
  173. sendAT(GF("&FZE0&W")); // Factory + Reset + Echo Off + Write
  174. waitResponse();
  175. sendAT(GF("+ICF=3,1")); // 8 data 0 parity 1 stop
  176. waitResponse();
  177. sendAT(GF("+enpwrsave=0")); // Disable PWR save
  178. waitResponse();
  179. sendAT(GF("+XISP=0")); // Use internal stack
  180. waitResponse();
  181. sendAT(GF("&W")); // Write configuration
  182. return waitResponse() == 1;
  183. }
  184. /*
  185. * Power functions
  186. */
  187. bool restart() {
  188. if (!autoBaud()) {
  189. return false;
  190. }
  191. sendAT(GF("+CFUN=15"));
  192. if (waitResponse(10000L) != 1) {
  193. return false;
  194. }
  195. //MODEM:STARTUP
  196. waitResponse(60000L, GF(GSM_NL "+PBREADY" GSM_NL));
  197. return init();
  198. }
  199. /*
  200. * SIM card & Networ Operator functions
  201. */
  202. bool simUnlock(const char *pin) {
  203. sendAT(GF("+CPIN=\""), pin, GF("\""));
  204. return waitResponse() == 1;
  205. }
  206. String getSimCCID() {
  207. sendAT(GF("+CCID"));
  208. if (waitResponse(GF(GSM_NL "+CCID:")) != 1) {
  209. return "";
  210. }
  211. String res = streamReadUntil('\n');
  212. waitResponse();
  213. return res;
  214. }
  215. String getIMEI() {
  216. sendAT(GF("+GSN"));
  217. if (waitResponse(GF(GSM_NL)) != 1) {
  218. return "";
  219. }
  220. String res = streamReadUntil('\n');
  221. waitResponse();
  222. return res;
  223. }
  224. int getSignalQuality() {
  225. sendAT(GF("+CSQ"));
  226. if (waitResponse(GF(GSM_NL "+CSQ:")) != 1) {
  227. return 99;
  228. }
  229. int res = streamReadUntil(',').toInt();
  230. waitResponse();
  231. return res;
  232. }
  233. SimStatus getSimStatus(unsigned long timeout = 10000L) {
  234. for (unsigned long start = millis(); millis() - start < timeout; ) {
  235. sendAT(GF("+CPIN?"));
  236. if (waitResponse(GF(GSM_NL "+CPIN:")) != 1) {
  237. delay(1000);
  238. continue;
  239. }
  240. int status = waitResponse(GF("READY"), GF("SIM PIN"), GF("SIM PUK"));
  241. waitResponse();
  242. switch (status) {
  243. case 2:
  244. case 3: return SIM_LOCKED;
  245. case 1: return SIM_READY;
  246. default: return SIM_ERROR;
  247. }
  248. }
  249. return SIM_ERROR;
  250. }
  251. RegStatus getRegistrationStatus() {
  252. sendAT(GF("+CREG?"));
  253. if (waitResponse(GF(GSM_NL "+CREG:")) != 1) {
  254. return REG_UNKNOWN;
  255. }
  256. streamSkipUntil(','); // Skip format (0)
  257. int status = streamReadUntil('\n').toInt();
  258. waitResponse();
  259. return (RegStatus)status;
  260. }
  261. String getOperator() {
  262. sendAT(GF("+COPS?"));
  263. if (waitResponse(GF(GSM_NL "+COPS:")) != 1) {
  264. return "";
  265. }
  266. streamSkipUntil('"'); // Skip mode and format
  267. String res = streamReadUntil('"');
  268. waitResponse();
  269. return res;
  270. }
  271. bool waitForNetwork(unsigned long timeout = 60000L) {
  272. for (unsigned long start = millis(); millis() - start < timeout; ) {
  273. RegStatus s = getRegistrationStatus();
  274. if (s == REG_OK_HOME || s == REG_OK_ROAMING) {
  275. return true;
  276. }
  277. delay(1000);
  278. }
  279. return false;
  280. }
  281. /*
  282. * WiFi functions
  283. */
  284. bool networkConnect(const char* ssid, const char* pwd) {
  285. return false;
  286. }
  287. bool networkDisconnect() {
  288. return false;
  289. }
  290. /*
  291. * GPRS functions
  292. */
  293. bool gprsConnect(const char* apn, const char* user, const char* pwd) {
  294. gprsDisconnect();
  295. sendAT(GF("+XISP=0"));
  296. waitResponse();
  297. sendAT(GF("+CGDCONT=1,\"IP\",\""), apn, '"');
  298. waitResponse();
  299. if (!user) user = "";
  300. if (!pwd) pwd = "";
  301. sendAT(GF("+XGAUTH=1,1,\""), user, GF("\",\""), pwd, GF("\""));
  302. waitResponse();
  303. sendAT(GF("+XIIC=1"));
  304. waitResponse();
  305. delay(10000L); // TODO
  306. sendAT(GF("+XIIC?"));
  307. waitResponse();
  308. /*sendAT(GF("+DNSSERVER=1,8.8.8.8"));
  309. waitResponse();
  310. sendAT(GF("+DNSSERVER=2,8.8.4.4"));
  311. if (waitResponse() != 1) {
  312. return false;
  313. }*/
  314. return true;
  315. }
  316. bool gprsDisconnect() {
  317. sendAT(GF("+XIIC=0"));
  318. return waitResponse(60000L) == 1;
  319. }
  320. /*
  321. * Phone Call functions
  322. */
  323. bool callAnswer() {
  324. sendAT(GF("A"));
  325. return waitResponse() == 1;
  326. }
  327. bool callNumber(const String& number) {
  328. sendAT(GF("D"), number);
  329. return waitResponse() == 1;
  330. }
  331. bool callHangup(const String& number) {
  332. sendAT(GF("H"), number);
  333. return waitResponse() == 1;
  334. }
  335. /*
  336. * Messaging functions
  337. */
  338. void sendUSSD() {
  339. }
  340. void sendSMS() {
  341. }
  342. bool sendSMS(const String& number, const String& text) {
  343. sendAT(GF("+CMGF=1"));
  344. waitResponse();
  345. sendAT(GF("+CMGS=\""), number, GF("\""));
  346. if (waitResponse(GF(">")) != 1) {
  347. return false;
  348. }
  349. stream.print(text);
  350. stream.write((char)0x1A);
  351. return waitResponse(60000L) == 1;
  352. }
  353. /*
  354. * Location functions
  355. */
  356. void getLocation() {
  357. }
  358. /*
  359. * Battery functions
  360. */
  361. /* Public Utilities */
  362. template<typename... Args>
  363. void sendAT(Args... cmd) {
  364. streamWrite("AT", cmd..., GSM_NL);
  365. stream.flush();
  366. TINY_GSM_YIELD();
  367. DBG(GSM_NL, ">>> AT:", cmd...);
  368. }
  369. // TODO: Optimize this!
  370. uint8_t waitResponse(uint32_t timeout, String& data,
  371. GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  372. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  373. {
  374. /*String r1s(r1); r1s.trim();
  375. String r2s(r2); r2s.trim();
  376. String r3s(r3); r3s.trim();
  377. String r4s(r4); r4s.trim();
  378. String r5s(r5); r5s.trim();
  379. DBG("### ..:", r1s, ",", r2s, ",", r3s, ",", r4s, ",", r5s);*/
  380. data.reserve(64);
  381. bool gotData = false;
  382. int mux = -1;
  383. int len = 0;
  384. int index = 0;
  385. unsigned long startMillis = millis();
  386. do {
  387. TINY_GSM_YIELD();
  388. while (stream.available() > 0) {
  389. int a = streamRead();
  390. if (a <= 0) continue; // Skip 0x00 bytes, just in case
  391. data += (char)a;
  392. if (r1 && data.endsWith(r1)) {
  393. index = 1;
  394. goto finish;
  395. } else if (r2 && data.endsWith(r2)) {
  396. index = 2;
  397. goto finish;
  398. } else if (r3 && data.endsWith(r3)) {
  399. index = 3;
  400. goto finish;
  401. } else if (r4 && data.endsWith(r4)) {
  402. index = 4;
  403. goto finish;
  404. } else if (r5 && data.endsWith(r5)) {
  405. index = 5;
  406. goto finish;
  407. } else if (data.endsWith(GF("+TCPRECV:"))) {
  408. mux = stream.readStringUntil(',').toInt();
  409. data += mux;
  410. data += (',');
  411. len = stream.readStringUntil(',').toInt();
  412. data += len;
  413. data += (',');
  414. gotData = true;
  415. index = 6;
  416. goto finish;
  417. } else if (data.endsWith(GF("+TCPCLOSE:"))) {
  418. mux = stream.readStringUntil(',').toInt();
  419. data += mux;
  420. data += (',');
  421. String concl = stream.readStringUntil('\n');
  422. data += concl;
  423. sockets[mux]->sock_connected = false;
  424. index = 7;
  425. goto finish;
  426. }
  427. }
  428. } while (millis() - startMillis < timeout);
  429. finish:
  430. if (!index) {
  431. data.trim();
  432. if (data.length()) {
  433. DBG("### Unhandled:", data);
  434. }
  435. }
  436. else {
  437. data.trim();
  438. data.replace(GSM_NL GSM_NL, GSM_NL);
  439. data.replace(GSM_NL, GSM_NL " ");
  440. if (data.length()) {
  441. DBG(GSM_NL, "<<< ", data);
  442. }
  443. }
  444. if (gotData) {
  445. int len_orig = len;
  446. if (len > sockets[mux]->rx.free()) {
  447. DBG(GSM_NL, "### Buffer overflow: ", len, "->", sockets[mux]->rx.free());
  448. } else {
  449. DBG(GSM_NL, "### Got: ", len, "->", sockets[mux]->rx.free());
  450. }
  451. while (len--) {
  452. char c[2] = {0};
  453. stream.readBytes(c, 1); // readBytes includes a timeout
  454. if(c[0]) sockets[mux]->rx.put(c[0]);
  455. // DBG(GSM_NL, c[0], " ", len, " ", stream.available(), " ", sockets[mux]->available());
  456. }
  457. if (len_orig > sockets[mux]->available()) {
  458. DBG(GSM_NL, "### Fewer characters received than expected: ", len_orig, "->", sockets[mux]->available());
  459. }
  460. }
  461. return index;
  462. }
  463. uint8_t waitResponse(uint32_t timeout,
  464. GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  465. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  466. {
  467. String data;
  468. return waitResponse(timeout, data, r1, r2, r3, r4, r5);
  469. }
  470. uint8_t waitResponse(GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  471. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  472. {
  473. return waitResponse(1000, r1, r2, r3, r4, r5);
  474. }
  475. private:
  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 = streamReadUntil('\n');
  482. waitResponse(GF("+DNS:OK" GSM_NL));
  483. res.trim();
  484. return res;
  485. }
  486. int modemConnect(const char* host, uint16_t port, uint8_t mux) {
  487. for (int i=0; i<3; i++) {
  488. String ip = dnsIpQuery(host);
  489. sendAT(GF("+TCPSETUP="), mux, GF(","), ip, GF(","), port);
  490. int rsp = waitResponse(75000L,
  491. GF(",OK" GSM_NL),
  492. GF(",FAIL" GSM_NL),
  493. GF("+TCPSETUP:Error" GSM_NL));
  494. if (1 == rsp) {
  495. return true;
  496. } else if (3 == rsp) {
  497. sendAT(GF("+TCPCLOSE="), mux);
  498. waitResponse();
  499. }
  500. delay(1000);
  501. }
  502. return false;
  503. }
  504. int modemSend(const void* buff, size_t len, uint8_t mux) {
  505. sendAT(GF("+TCPSEND="), mux, ',', len);
  506. if (waitResponse(GF(">")) != 1) {
  507. return 0;
  508. }
  509. stream.write((uint8_t*)buff, len);
  510. stream.write((char)0x0D);
  511. if (waitResponse(30000L, GF(GSM_NL "+TCPSEND:")) != 1) {
  512. return 0;
  513. }
  514. streamReadUntil('\n');
  515. return len;
  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. /* Private 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. String streamReadUntil(char c) {
  535. String return_string = stream.readStringUntil(c);
  536. return_string.trim();
  537. if (String(c) == GSM_NL || String(c) == "\n"){
  538. DBG(return_string, c, " ");
  539. } else DBG(return_string, c);
  540. return return_string;
  541. }
  542. bool streamSkipUntil(char c) {
  543. String skipped = stream.readStringUntil(c);
  544. skipped.trim();
  545. if (skipped.length()) {
  546. if (String(c) == GSM_NL || String(c) == "\n"){
  547. DBG(skipped, c, " ");
  548. } else DBG(skipped, c);
  549. return true;
  550. } else return false;
  551. }
  552. private:
  553. Stream& stream;
  554. GsmClient* sockets[2];
  555. };
  556. typedef TinyGsm::GsmClient TinyGsmClient;
  557. #endif