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.

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