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.

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