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.

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