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.

614 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
  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. private:
  126. TinyGsm* at;
  127. uint8_t mux;
  128. bool sock_connected;
  129. RxFifo rx;
  130. };
  131. public:
  132. TinyGsm(Stream& stream)
  133. : stream(stream)
  134. {
  135. memset(sockets, 0, sizeof(sockets));
  136. }
  137. /*
  138. * Basic functions
  139. */
  140. bool begin() {
  141. return init();
  142. }
  143. bool init() {
  144. if (!autoBaud()) {
  145. return false;
  146. }
  147. sendAT(GF("&FZE0")); // Factory + Reset + Echo Off
  148. if (waitResponse() != 1) {
  149. return false;
  150. }
  151. #ifdef TINY_GSM_DEBUG
  152. sendAT(GF("+CMEE=2"));
  153. waitResponse();
  154. #endif
  155. getSimStatus();
  156. return true;
  157. }
  158. bool autoBaud(unsigned long timeout = 10000L) {
  159. for (unsigned long start = millis(); millis() - start < timeout; ) {
  160. sendAT(GF("E0"));
  161. if (waitResponse(200) == 1) {
  162. delay(100);
  163. return true;
  164. }
  165. delay(100);
  166. }
  167. return false;
  168. }
  169. void maintain() {
  170. //while (stream.available()) {
  171. waitResponse(10, NULL, NULL);
  172. //}
  173. }
  174. bool factoryDefault() {
  175. sendAT(GF("&FZE0&W")); // Factory + Reset + Echo Off + Write
  176. waitResponse();
  177. sendAT(GF("+ICF=3,1")); // 8 data 0 parity 1 stop
  178. waitResponse();
  179. sendAT(GF("+enpwrsave=0")); // Disable PWR save
  180. waitResponse();
  181. sendAT(GF("+XISP=0")); // Use internal stack
  182. waitResponse();
  183. sendAT(GF("&W")); // Write configuration
  184. return waitResponse() == 1;
  185. }
  186. /*
  187. * Power functions
  188. */
  189. bool restart() {
  190. if (!autoBaud()) {
  191. return false;
  192. }
  193. sendAT(GF("+CFUN=15"));
  194. if (waitResponse(10000L) != 1) {
  195. return false;
  196. }
  197. //MODEM:STARTUP
  198. waitResponse(60000L, GF(GSM_NL "+PBREADY" GSM_NL));
  199. return init();
  200. }
  201. bool poweroff() TINY_GSM_ATTR_NOT_IMPLEMENTED;
  202. /*
  203. * SIM card functions
  204. */
  205. bool simUnlock(const char *pin) {
  206. sendAT(GF("+CPIN=\""), pin, GF("\""));
  207. return waitResponse() == 1;
  208. }
  209. String getSimCCID() {
  210. sendAT(GF("+CCID"));
  211. if (waitResponse(GF(GSM_NL "+CCID:")) != 1) {
  212. return "";
  213. }
  214. String res = stream.readStringUntil('\n');
  215. waitResponse();
  216. res.trim();
  217. return res;
  218. }
  219. String getIMEI() {
  220. sendAT(GF("+GSN"));
  221. if (waitResponse(GF(GSM_NL)) != 1) {
  222. return "";
  223. }
  224. String res = stream.readStringUntil('\n');
  225. waitResponse();
  226. res.trim();
  227. return res;
  228. }
  229. SimStatus getSimStatus(unsigned long timeout = 10000L) {
  230. for (unsigned long start = millis(); millis() - start < timeout; ) {
  231. sendAT(GF("+CPIN?"));
  232. if (waitResponse(GF(GSM_NL "+CPIN:")) != 1) {
  233. delay(1000);
  234. continue;
  235. }
  236. int status = waitResponse(GF("READY"), GF("SIM PIN"), GF("SIM PUK"));
  237. waitResponse();
  238. switch (status) {
  239. case 2:
  240. case 3: return SIM_LOCKED;
  241. case 1: return SIM_READY;
  242. default: return SIM_ERROR;
  243. }
  244. }
  245. return SIM_ERROR;
  246. }
  247. RegStatus getRegistrationStatus() {
  248. sendAT(GF("+CREG?"));
  249. if (waitResponse(GF(GSM_NL "+CREG:")) != 1) {
  250. return REG_UNKNOWN;
  251. }
  252. streamSkipUntil(','); // Skip format (0)
  253. int status = stream.readStringUntil('\n').toInt();
  254. waitResponse();
  255. return (RegStatus)status;
  256. }
  257. String getOperator() {
  258. sendAT(GF("+COPS?"));
  259. if (waitResponse(GF(GSM_NL "+COPS:")) != 1) {
  260. return "";
  261. }
  262. streamSkipUntil('"'); // Skip mode and format
  263. String res = stream.readStringUntil('"');
  264. waitResponse();
  265. return res;
  266. }
  267. /*
  268. * Generic network functions
  269. */
  270. int getSignalQuality() {
  271. sendAT(GF("+CSQ"));
  272. if (waitResponse(GF(GSM_NL "+CSQ:")) != 1) {
  273. return 99;
  274. }
  275. int res = stream.readStringUntil(',').toInt();
  276. waitResponse();
  277. return res;
  278. }
  279. bool waitForNetwork(unsigned long timeout = 60000L) {
  280. for (unsigned long start = millis(); millis() - start < timeout; ) {
  281. RegStatus s = getRegistrationStatus();
  282. if (s == REG_OK_HOME || s == REG_OK_ROAMING) {
  283. return true;
  284. }
  285. delay(1000);
  286. }
  287. return false;
  288. }
  289. /*
  290. * GPRS functions
  291. */
  292. bool gprsConnect(const char* apn, const char* user, const char* pwd) {
  293. gprsDisconnect();
  294. sendAT(GF("+XISP=0"));
  295. waitResponse();
  296. sendAT(GF("+CGDCONT=1,\"IP\",\""), apn, '"');
  297. waitResponse();
  298. if (!user) user = "";
  299. if (!pwd) pwd = "";
  300. sendAT(GF("+XGAUTH=1,1,\""), user, GF("\",\""), pwd, GF("\""));
  301. waitResponse();
  302. sendAT(GF("+XIIC=1"));
  303. waitResponse();
  304. delay(10000L); // TODO
  305. sendAT(GF("+XIIC?"));
  306. waitResponse();
  307. /*
  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. */
  315. return true;
  316. }
  317. bool gprsDisconnect() {
  318. sendAT(GF("+XIIC=0"));
  319. return waitResponse(60000L) == 1;
  320. }
  321. String getLocalIP() TINY_GSM_ATTR_NOT_IMPLEMENTED;
  322. /*
  323. * Phone Call functions
  324. */
  325. bool setGsmBusy(bool busy = true) TINY_GSM_ATTR_NOT_AVAILABLE;
  326. bool callAnswer() {
  327. sendAT(GF("A"));
  328. return waitResponse() == 1;
  329. }
  330. bool callNumber(const String& number) {
  331. sendAT(GF("D"), number);
  332. return waitResponse() == 1;
  333. }
  334. void callRedial() TINY_GSM_ATTR_NOT_AVAILABLE;
  335. bool callHangup(const String& number) {
  336. sendAT(GF("H"), number);
  337. return waitResponse() == 1;
  338. }
  339. /*
  340. * Messaging functions
  341. */
  342. void sendUSSD() TINY_GSM_ATTR_NOT_IMPLEMENTED;
  343. bool sendSMS(const String& number, const String& text) {
  344. sendAT(GF("+CSCS=\"gsm\""));
  345. waitResponse();
  346. sendAT(GF("+CMGF=1"));
  347. waitResponse();
  348. sendAT(GF("+CMGS=\""), number, GF("\""));
  349. if (waitResponse(GF(">")) != 1) {
  350. return false;
  351. }
  352. stream.print(text);
  353. stream.write((char)0x1A);
  354. stream.flush();
  355. return waitResponse(60000L) == 1;
  356. }
  357. /*
  358. * Location functions
  359. */
  360. String getGsmLocation() TINY_GSM_ATTR_NOT_AVAILABLE;
  361. /*
  362. * Battery functions
  363. */
  364. private:
  365. int modemConnect(const char* host, uint16_t port, uint8_t mux) {
  366. for (int i=0; i<3; i++) { // TODO: no need for loop?
  367. String ip = dnsIpQuery(host);
  368. sendAT(GF("+TCPSETUP="), mux, GF(","), ip, GF(","), port);
  369. int rsp = waitResponse(75000L,
  370. GF(",OK" GSM_NL),
  371. GF(",FAIL" GSM_NL),
  372. GF("+TCPSETUP:Error" GSM_NL));
  373. if (1 == rsp) {
  374. return true;
  375. } else if (3 == rsp) {
  376. sendAT(GF("+TCPCLOSE="), mux);
  377. waitResponse();
  378. }
  379. delay(1000);
  380. }
  381. return false;
  382. }
  383. int modemSend(const void* buff, size_t len, uint8_t mux) {
  384. sendAT(GF("+TCPSEND="), mux, ',', len);
  385. if (waitResponse(GF(">")) != 1) {
  386. return 0;
  387. }
  388. stream.write((uint8_t*)buff, len);
  389. stream.write((char)0x0D);
  390. stream.flush();
  391. if (waitResponse(30000L, GF(GSM_NL "+TCPSEND:")) != 1) {
  392. return 0;
  393. }
  394. stream.readStringUntil('\n');
  395. return len;
  396. }
  397. bool modemGetConnected(uint8_t mux) {
  398. sendAT(GF("+CIPSTATUS="), mux);
  399. int res = waitResponse(GF(",\"CONNECTED\""), GF(",\"CLOSED\""), GF(",\"CLOSING\""), GF(",\"INITIAL\""));
  400. waitResponse();
  401. return 1 == res;
  402. }
  403. String dnsIpQuery(const char* host) {
  404. sendAT(GF("+DNS=\""), host, GF("\""));
  405. if (waitResponse(10000L, GF(GSM_NL "+DNS:")) != 1) {
  406. return "";
  407. }
  408. String res = stream.readStringUntil('\n');
  409. waitResponse(GF("+DNS:OK" GSM_NL));
  410. res.trim();
  411. return res;
  412. }
  413. public:
  414. /* Utilities */
  415. template<typename T>
  416. void streamWrite(T last) {
  417. stream.print(last);
  418. }
  419. template<typename T, typename... Args>
  420. void streamWrite(T head, Args... tail) {
  421. stream.print(head);
  422. streamWrite(tail...);
  423. }
  424. bool streamSkipUntil(char c) { //TODO: timeout
  425. while (true) {
  426. while (!stream.available()) { TINY_GSM_YIELD(); }
  427. if (stream.read() == c)
  428. return true;
  429. }
  430. return false;
  431. }
  432. template<typename... Args>
  433. void sendAT(Args... cmd) {
  434. streamWrite("AT", cmd..., GSM_NL);
  435. stream.flush();
  436. TINY_GSM_YIELD();
  437. //DBG("### AT:", cmd...);
  438. }
  439. // TODO: Optimize this!
  440. uint8_t waitResponse(uint32_t timeout, String& data,
  441. GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  442. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  443. {
  444. /*String r1s(r1); r1s.trim();
  445. String r2s(r2); r2s.trim();
  446. String r3s(r3); r3s.trim();
  447. String r4s(r4); r4s.trim();
  448. String r5s(r5); r5s.trim();
  449. DBG("### ..:", r1s, ",", r2s, ",", r3s, ",", r4s, ",", r5s);*/
  450. data.reserve(64);
  451. int index = 0;
  452. unsigned long startMillis = millis();
  453. do {
  454. TINY_GSM_YIELD();
  455. while (stream.available() > 0) {
  456. int a = stream.read();
  457. if (a <= 0) continue; // Skip 0x00 bytes, just in case
  458. data += (char)a;
  459. if (r1 && data.endsWith(r1)) {
  460. index = 1;
  461. goto finish;
  462. } else if (r2 && data.endsWith(r2)) {
  463. index = 2;
  464. goto finish;
  465. } else if (r3 && data.endsWith(r3)) {
  466. index = 3;
  467. goto finish;
  468. } else if (r4 && data.endsWith(r4)) {
  469. index = 4;
  470. goto finish;
  471. } else if (r5 && data.endsWith(r5)) {
  472. index = 5;
  473. goto finish;
  474. } else if (data.endsWith(GF("+TCPRECV:"))) {
  475. int mux = stream.readStringUntil(',').toInt();
  476. int len = stream.readStringUntil(',').toInt();
  477. if (len > sockets[mux]->rx.free()) {
  478. DBG("### Buffer overflow: ", len, "->", sockets[mux]->rx.free());
  479. } else {
  480. DBG("### Got: ", len, "->", sockets[mux]->rx.free());
  481. }
  482. while (len--) {
  483. while (!stream.available()) { TINY_GSM_YIELD(); }
  484. sockets[mux]->rx.put(stream.read());
  485. }
  486. data = "";
  487. return index;
  488. } else if (data.endsWith(GF("+TCPCLOSE:"))) {
  489. int mux = stream.readStringUntil(',').toInt();
  490. stream.readStringUntil('\n');
  491. sockets[mux]->sock_connected = false;
  492. data = "";
  493. }
  494. }
  495. } while (millis() - startMillis < timeout);
  496. finish:
  497. if (!index) {
  498. data.trim();
  499. if (data.length()) {
  500. DBG("### Unhandled:", data);
  501. }
  502. data = "";
  503. }
  504. return index;
  505. }
  506. uint8_t waitResponse(uint32_t timeout,
  507. GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  508. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  509. {
  510. String data;
  511. return waitResponse(timeout, data, r1, r2, r3, r4, r5);
  512. }
  513. uint8_t waitResponse(GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  514. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  515. {
  516. return waitResponse(1000, r1, r2, r3, r4, r5);
  517. }
  518. private:
  519. Stream& stream;
  520. GsmClient* sockets[TINY_GSM_MUX_COUNT];
  521. };
  522. typedef TinyGsm::GsmClient TinyGsmClient;
  523. #endif