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.

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