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.

625 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
  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. /*
  191. * Power functions
  192. */
  193. bool restart() {
  194. if (!autoBaud()) {
  195. return false;
  196. }
  197. sendAT(GF("+CFUN=15"));
  198. if (waitResponse(10000L) != 1) {
  199. return false;
  200. }
  201. //MODEM:STARTUP
  202. waitResponse(60000L, GF(GSM_NL "+PBREADY" GSM_NL));
  203. return init();
  204. }
  205. bool poweroff() TINY_GSM_ATTR_NOT_IMPLEMENTED;
  206. /*
  207. * SIM card functions
  208. */
  209. bool simUnlock(const char *pin) {
  210. sendAT(GF("+CPIN=\""), pin, GF("\""));
  211. return waitResponse() == 1;
  212. }
  213. String getSimCCID() {
  214. sendAT(GF("+CCID"));
  215. if (waitResponse(GF(GSM_NL "+CCID:")) != 1) {
  216. return "";
  217. }
  218. String res = stream.readStringUntil('\n');
  219. waitResponse();
  220. res.trim();
  221. return res;
  222. }
  223. String getIMEI() {
  224. sendAT(GF("+GSN"));
  225. if (waitResponse(GF(GSM_NL)) != 1) {
  226. return "";
  227. }
  228. String res = stream.readStringUntil('\n');
  229. waitResponse();
  230. res.trim();
  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 = stream.readStringUntil('\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 = stream.readStringUntil('"');
  268. waitResponse();
  269. return res;
  270. }
  271. /*
  272. * Generic network functions
  273. */
  274. int getSignalQuality() {
  275. sendAT(GF("+CSQ"));
  276. if (waitResponse(GF(GSM_NL "+CSQ:")) != 1) {
  277. return 99;
  278. }
  279. int res = stream.readStringUntil(',').toInt();
  280. waitResponse();
  281. return res;
  282. }
  283. bool waitForNetwork(unsigned long timeout = 60000L) {
  284. for (unsigned long start = millis(); millis() - start < timeout; ) {
  285. RegStatus s = getRegistrationStatus();
  286. if (s == REG_OK_HOME || s == REG_OK_ROAMING) {
  287. return true;
  288. }
  289. delay(1000);
  290. }
  291. return false;
  292. }
  293. /*
  294. * GPRS functions
  295. */
  296. bool gprsConnect(const char* apn, const char* user, const char* pwd) {
  297. gprsDisconnect();
  298. sendAT(GF("+XISP=0"));
  299. waitResponse();
  300. sendAT(GF("+CGDCONT=1,\"IP\",\""), apn, '"');
  301. waitResponse();
  302. if (!user) user = "";
  303. if (!pwd) pwd = "";
  304. sendAT(GF("+XGAUTH=1,1,\""), user, GF("\",\""), pwd, GF("\""));
  305. waitResponse();
  306. sendAT(GF("+XIIC=1"));
  307. waitResponse();
  308. delay(10000L); // TODO
  309. sendAT(GF("+XIIC?"));
  310. waitResponse();
  311. /*
  312. sendAT(GF("+DNSSERVER=1,8.8.8.8"));
  313. waitResponse();
  314. sendAT(GF("+DNSSERVER=2,8.8.4.4"));
  315. if (waitResponse() != 1) {
  316. return false;
  317. }
  318. */
  319. return true;
  320. }
  321. bool gprsDisconnect() {
  322. sendAT(GF("+XIIC=0"));
  323. return waitResponse(60000L) == 1;
  324. }
  325. String getLocalIP() TINY_GSM_ATTR_NOT_IMPLEMENTED;
  326. /*
  327. * Phone Call functions
  328. */
  329. bool setGsmBusy(bool busy = true) TINY_GSM_ATTR_NOT_AVAILABLE;
  330. bool callAnswer() {
  331. sendAT(GF("A"));
  332. return waitResponse() == 1;
  333. }
  334. bool callNumber(const String& number) {
  335. sendAT(GF("D"), number);
  336. return waitResponse() == 1;
  337. }
  338. void callRedial() TINY_GSM_ATTR_NOT_AVAILABLE;
  339. bool callHangup(const String& number) {
  340. sendAT(GF("H"), number);
  341. return waitResponse() == 1;
  342. }
  343. /*
  344. * Messaging functions
  345. */
  346. void sendUSSD() TINY_GSM_ATTR_NOT_IMPLEMENTED;
  347. bool sendSMS(const String& number, const String& text) {
  348. sendAT(GF("+CSCS=\"gsm\""));
  349. waitResponse();
  350. sendAT(GF("+CMGF=1"));
  351. waitResponse();
  352. sendAT(GF("+CMGS=\""), number, GF("\""));
  353. if (waitResponse(GF(">")) != 1) {
  354. return false;
  355. }
  356. stream.print(text);
  357. stream.write((char)0x1A);
  358. stream.flush();
  359. return waitResponse(60000L) == 1;
  360. }
  361. /*
  362. * Location functions
  363. */
  364. String getGsmLocation() TINY_GSM_ATTR_NOT_AVAILABLE;
  365. /*
  366. * Battery functions
  367. */
  368. uint16_t getBattVoltage() TINY_GSM_ATTR_NOT_AVAILABLE;
  369. int getBattPercent() TINY_GSM_ATTR_NOT_AVAILABLE;
  370. private:
  371. int modemConnect(const char* host, uint16_t port, uint8_t mux) {
  372. for (int i=0; i<3; i++) { // TODO: no need for loop?
  373. String ip = dnsIpQuery(host);
  374. sendAT(GF("+TCPSETUP="), mux, GF(","), ip, GF(","), port);
  375. int rsp = waitResponse(75000L,
  376. GF(",OK" GSM_NL),
  377. GF(",FAIL" GSM_NL),
  378. GF("+TCPSETUP:Error" GSM_NL));
  379. if (1 == rsp) {
  380. return true;
  381. } else if (3 == rsp) {
  382. sendAT(GF("+TCPCLOSE="), mux);
  383. waitResponse();
  384. }
  385. delay(1000);
  386. }
  387. return false;
  388. }
  389. int modemSend(const void* buff, size_t len, uint8_t mux) {
  390. sendAT(GF("+TCPSEND="), mux, ',', len);
  391. if (waitResponse(GF(">")) != 1) {
  392. return 0;
  393. }
  394. stream.write((uint8_t*)buff, len);
  395. stream.write((char)0x0D);
  396. stream.flush();
  397. if (waitResponse(30000L, GF(GSM_NL "+TCPSEND:")) != 1) {
  398. return 0;
  399. }
  400. stream.readStringUntil('\n');
  401. return len;
  402. }
  403. bool modemGetConnected(uint8_t mux) {
  404. sendAT(GF("+CIPSTATUS="), mux);
  405. int res = waitResponse(GF(",\"CONNECTED\""), GF(",\"CLOSED\""), GF(",\"CLOSING\""), GF(",\"INITIAL\""));
  406. waitResponse();
  407. return 1 == res;
  408. }
  409. String dnsIpQuery(const char* host) {
  410. sendAT(GF("+DNS=\""), host, GF("\""));
  411. if (waitResponse(10000L, GF(GSM_NL "+DNS:")) != 1) {
  412. return "";
  413. }
  414. String res = stream.readStringUntil('\n');
  415. waitResponse(GF("+DNS:OK" GSM_NL));
  416. res.trim();
  417. return res;
  418. }
  419. public:
  420. /* Utilities */
  421. template<typename T>
  422. void streamWrite(T last) {
  423. stream.print(last);
  424. }
  425. template<typename T, typename... Args>
  426. void streamWrite(T head, Args... tail) {
  427. stream.print(head);
  428. streamWrite(tail...);
  429. }
  430. bool streamSkipUntil(char c) { //TODO: timeout
  431. while (true) {
  432. while (!stream.available()) { TINY_GSM_YIELD(); }
  433. if (stream.read() == c)
  434. return true;
  435. }
  436. return false;
  437. }
  438. template<typename... Args>
  439. void sendAT(Args... cmd) {
  440. streamWrite("AT", cmd..., GSM_NL);
  441. stream.flush();
  442. TINY_GSM_YIELD();
  443. //DBG("### AT:", cmd...);
  444. }
  445. // TODO: Optimize this!
  446. uint8_t waitResponse(uint32_t timeout, String& data,
  447. GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  448. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  449. {
  450. /*String r1s(r1); r1s.trim();
  451. String r2s(r2); r2s.trim();
  452. String r3s(r3); r3s.trim();
  453. String r4s(r4); r4s.trim();
  454. String r5s(r5); r5s.trim();
  455. DBG("### ..:", r1s, ",", r2s, ",", r3s, ",", r4s, ",", r5s);*/
  456. data.reserve(64);
  457. int index = 0;
  458. unsigned long startMillis = millis();
  459. do {
  460. TINY_GSM_YIELD();
  461. while (stream.available() > 0) {
  462. int a = stream.read();
  463. if (a <= 0) continue; // Skip 0x00 bytes, just in case
  464. data += (char)a;
  465. if (r1 && data.endsWith(r1)) {
  466. index = 1;
  467. goto finish;
  468. } else if (r2 && data.endsWith(r2)) {
  469. index = 2;
  470. goto finish;
  471. } else if (r3 && data.endsWith(r3)) {
  472. index = 3;
  473. goto finish;
  474. } else if (r4 && data.endsWith(r4)) {
  475. index = 4;
  476. goto finish;
  477. } else if (r5 && data.endsWith(r5)) {
  478. index = 5;
  479. goto finish;
  480. } else if (data.endsWith(GF("+TCPRECV:"))) {
  481. int mux = stream.readStringUntil(',').toInt();
  482. int len = stream.readStringUntil(',').toInt();
  483. if (len > sockets[mux]->rx.free()) {
  484. DBG("### Buffer overflow: ", len, "->", sockets[mux]->rx.free());
  485. } else {
  486. DBG("### Got: ", len, "->", sockets[mux]->rx.free());
  487. }
  488. while (len--) {
  489. while (!stream.available()) { TINY_GSM_YIELD(); }
  490. sockets[mux]->rx.put(stream.read());
  491. }
  492. data = "";
  493. } else if (data.endsWith(GF("+TCPCLOSE:"))) {
  494. int mux = stream.readStringUntil(',').toInt();
  495. stream.readStringUntil('\n');
  496. sockets[mux]->sock_connected = false;
  497. data = "";
  498. DBG("### Closed: ", mux);
  499. }
  500. }
  501. } while (millis() - startMillis < timeout);
  502. finish:
  503. if (!index) {
  504. data.trim();
  505. if (data.length()) {
  506. DBG("### Unhandled:", data);
  507. }
  508. data = "";
  509. }
  510. return index;
  511. }
  512. uint8_t waitResponse(uint32_t timeout,
  513. GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  514. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  515. {
  516. String data;
  517. return waitResponse(timeout, data, r1, r2, r3, r4, r5);
  518. }
  519. uint8_t waitResponse(GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  520. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  521. {
  522. return waitResponse(1000, r1, r2, r3, r4, r5);
  523. }
  524. private:
  525. Stream& stream;
  526. GsmClient* sockets[TINY_GSM_MUX_COUNT];
  527. };
  528. typedef TinyGsm::GsmClient TinyGsmClient;
  529. #endif