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.

627 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
7 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
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
  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. IPAddress localIP() TINY_GSM_ATTR_NOT_IMPLEMENTED;
  327. /*
  328. * Phone Call functions
  329. */
  330. bool setGsmBusy(bool busy = true) TINY_GSM_ATTR_NOT_AVAILABLE;
  331. bool callAnswer() {
  332. sendAT(GF("A"));
  333. return waitResponse() == 1;
  334. }
  335. bool callNumber(const String& number) {
  336. sendAT(GF("D"), number);
  337. return waitResponse() == 1;
  338. }
  339. bool callRedial() TINY_GSM_ATTR_NOT_AVAILABLE;
  340. bool callHangup(const String& number) {
  341. sendAT(GF("H"), number);
  342. return waitResponse() == 1;
  343. }
  344. /*
  345. * Messaging functions
  346. */
  347. void sendUSSD() TINY_GSM_ATTR_NOT_IMPLEMENTED;
  348. bool sendSMS(const String& number, const String& text) {
  349. sendAT(GF("+CSCS=\"gsm\""));
  350. waitResponse();
  351. sendAT(GF("+CMGF=1"));
  352. waitResponse();
  353. sendAT(GF("+CMGS=\""), number, GF("\""));
  354. if (waitResponse(GF(">")) != 1) {
  355. return false;
  356. }
  357. stream.print(text);
  358. stream.write((char)0x1A);
  359. stream.flush();
  360. return waitResponse(60000L) == 1;
  361. }
  362. /*
  363. * Location functions
  364. */
  365. String getGsmLocation() TINY_GSM_ATTR_NOT_AVAILABLE;
  366. /*
  367. * Battery functions
  368. */
  369. uint16_t getBattVoltage() TINY_GSM_ATTR_NOT_AVAILABLE;
  370. int getBattPercent() TINY_GSM_ATTR_NOT_AVAILABLE;
  371. private:
  372. bool modemConnect(const char* host, uint16_t port, uint8_t mux) {
  373. for (int i=0; i<3; i++) { // TODO: no need for loop?
  374. String ip = dnsIpQuery(host);
  375. sendAT(GF("+TCPSETUP="), mux, GF(","), ip, GF(","), port);
  376. int rsp = waitResponse(75000L,
  377. GF(",OK" GSM_NL),
  378. GF(",FAIL" GSM_NL),
  379. GF("+TCPSETUP:Error" GSM_NL));
  380. if (1 == rsp) {
  381. return true;
  382. } else if (3 == rsp) {
  383. sendAT(GF("+TCPCLOSE="), mux);
  384. waitResponse();
  385. }
  386. delay(1000);
  387. }
  388. return false;
  389. }
  390. int modemSend(const void* buff, size_t len, uint8_t mux) {
  391. sendAT(GF("+TCPSEND="), mux, ',', len);
  392. if (waitResponse(GF(">")) != 1) {
  393. return 0;
  394. }
  395. stream.write((uint8_t*)buff, len);
  396. stream.write((char)0x0D);
  397. stream.flush();
  398. if (waitResponse(30000L, GF(GSM_NL "+TCPSEND:")) != 1) {
  399. return 0;
  400. }
  401. stream.readStringUntil('\n');
  402. return len;
  403. }
  404. bool modemGetConnected(uint8_t mux) {
  405. sendAT(GF("+CIPSTATUS="), mux);
  406. int res = waitResponse(GF(",\"CONNECTED\""), GF(",\"CLOSED\""), GF(",\"CLOSING\""), GF(",\"INITIAL\""));
  407. waitResponse();
  408. return 1 == res;
  409. }
  410. String dnsIpQuery(const char* host) {
  411. sendAT(GF("+DNS=\""), host, GF("\""));
  412. if (waitResponse(10000L, GF(GSM_NL "+DNS:")) != 1) {
  413. return "";
  414. }
  415. String res = stream.readStringUntil('\n');
  416. waitResponse(GF("+DNS:OK" GSM_NL));
  417. res.trim();
  418. return res;
  419. }
  420. public:
  421. /* Utilities */
  422. template<typename T>
  423. void streamWrite(T last) {
  424. stream.print(last);
  425. }
  426. template<typename T, typename... Args>
  427. void streamWrite(T head, Args... tail) {
  428. stream.print(head);
  429. streamWrite(tail...);
  430. }
  431. bool streamSkipUntil(char c) { //TODO: timeout
  432. while (true) {
  433. while (!stream.available()) { TINY_GSM_YIELD(); }
  434. if (stream.read() == c)
  435. return true;
  436. }
  437. return false;
  438. }
  439. template<typename... Args>
  440. void sendAT(Args... cmd) {
  441. streamWrite("AT", cmd..., GSM_NL);
  442. stream.flush();
  443. TINY_GSM_YIELD();
  444. //DBG("### AT:", cmd...);
  445. }
  446. // TODO: Optimize this!
  447. uint8_t waitResponse(uint32_t timeout, String& data,
  448. GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  449. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  450. {
  451. /*String r1s(r1); r1s.trim();
  452. String r2s(r2); r2s.trim();
  453. String r3s(r3); r3s.trim();
  454. String r4s(r4); r4s.trim();
  455. String r5s(r5); r5s.trim();
  456. DBG("### ..:", r1s, ",", r2s, ",", r3s, ",", r4s, ",", r5s);*/
  457. data.reserve(64);
  458. int index = 0;
  459. unsigned long startMillis = millis();
  460. do {
  461. TINY_GSM_YIELD();
  462. while (stream.available() > 0) {
  463. int a = stream.read();
  464. if (a <= 0) continue; // Skip 0x00 bytes, just in case
  465. data += (char)a;
  466. if (r1 && data.endsWith(r1)) {
  467. index = 1;
  468. goto finish;
  469. } else if (r2 && data.endsWith(r2)) {
  470. index = 2;
  471. goto finish;
  472. } else if (r3 && data.endsWith(r3)) {
  473. index = 3;
  474. goto finish;
  475. } else if (r4 && data.endsWith(r4)) {
  476. index = 4;
  477. goto finish;
  478. } else if (r5 && data.endsWith(r5)) {
  479. index = 5;
  480. goto finish;
  481. } else if (data.endsWith(GF("+TCPRECV:"))) {
  482. int mux = stream.readStringUntil(',').toInt();
  483. int len = stream.readStringUntil(',').toInt();
  484. if (len > sockets[mux]->rx.free()) {
  485. DBG("### Buffer overflow: ", len, "->", sockets[mux]->rx.free());
  486. } else {
  487. DBG("### Got: ", len, "->", sockets[mux]->rx.free());
  488. }
  489. while (len--) {
  490. while (!stream.available()) { TINY_GSM_YIELD(); }
  491. sockets[mux]->rx.put(stream.read());
  492. }
  493. data = "";
  494. } else if (data.endsWith(GF("+TCPCLOSE:"))) {
  495. int mux = stream.readStringUntil(',').toInt();
  496. stream.readStringUntil('\n');
  497. sockets[mux]->sock_connected = false;
  498. data = "";
  499. DBG("### Closed: ", mux);
  500. }
  501. }
  502. } while (millis() - startMillis < timeout);
  503. finish:
  504. if (!index) {
  505. data.trim();
  506. if (data.length()) {
  507. DBG("### Unhandled:", data);
  508. }
  509. data = "";
  510. }
  511. return index;
  512. }
  513. uint8_t waitResponse(uint32_t timeout,
  514. GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  515. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  516. {
  517. String data;
  518. return waitResponse(timeout, data, r1, r2, r3, r4, r5);
  519. }
  520. uint8_t waitResponse(GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  521. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  522. {
  523. return waitResponse(1000, r1, r2, r3, r4, r5);
  524. }
  525. private:
  526. Stream& stream;
  527. GsmClient* sockets[TINY_GSM_MUX_COUNT];
  528. };
  529. typedef TinyGsm::GsmClient TinyGsmClient;
  530. #endif