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.

595 lines
14 KiB

  1. /**
  2. * @file TinyGsmClientA6.h
  3. * @author Volodymyr Shymanskyy
  4. * @license LGPL-3.0
  5. * @copyright Copyright (c) 2016 Volodymyr Shymanskyy
  6. * @date Nov 2016
  7. */
  8. #ifndef TinyGsmClientA6_h
  9. #define TinyGsmClientA6_h
  10. //#define TINY_GSM_DEBUG Serial
  11. #if !defined(TINY_GSM_RX_BUFFER)
  12. #define TINY_GSM_RX_BUFFER 256
  13. #endif
  14. #include <TinyGsmCommon.h>
  15. #define GSM_NL "\r\n"
  16. static const char GSM_OK[] TINY_GSM_PROGMEM = "OK" GSM_NL;
  17. static const char GSM_ERROR[] TINY_GSM_PROGMEM = "ERROR" GSM_NL;
  18. enum SimStatus {
  19. SIM_ERROR = 0,
  20. SIM_READY = 1,
  21. SIM_LOCKED = 2,
  22. };
  23. enum RegStatus {
  24. REG_UNREGISTERED = 0,
  25. REG_SEARCHING = 3,
  26. REG_DENIED = 2,
  27. REG_OK_HOME = 1,
  28. REG_OK_ROAMING = 5,
  29. REG_UNKNOWN = 4,
  30. };
  31. class TinyGsm
  32. {
  33. public:
  34. TinyGsm(Stream& stream)
  35. : stream(stream)
  36. {}
  37. public:
  38. class GsmClient : public Client
  39. {
  40. friend class TinyGsm;
  41. typedef TinyGsmFifo<uint8_t, TINY_GSM_RX_BUFFER> RxFifo;
  42. public:
  43. GsmClient() {}
  44. GsmClient(TinyGsm& modem) {
  45. init(&modem);
  46. }
  47. bool init(TinyGsm* modem) {
  48. at = modem;
  49. mux = -1;
  50. sock_connected = false;
  51. return true;
  52. }
  53. public:
  54. virtual int connect(const char *host, uint16_t port) {
  55. TINY_GSM_YIELD();
  56. rx.clear();
  57. uint8_t newMux = -1;
  58. sock_connected = at->modemConnect(host, port, &newMux);
  59. if (sock_connected) {
  60. mux = newMux;
  61. at->sockets[mux] = this;
  62. }
  63. return sock_connected;
  64. }
  65. virtual int connect(IPAddress ip, uint16_t port) {
  66. String host; host.reserve(16);
  67. host += ip[0];
  68. host += ".";
  69. host += ip[1];
  70. host += ".";
  71. host += ip[2];
  72. host += ".";
  73. host += ip[3];
  74. return connect(host.c_str(), port);
  75. }
  76. virtual void stop() {
  77. TINY_GSM_YIELD();
  78. at->sendAT(GF("+CIPCLOSE="), mux);
  79. sock_connected = false;
  80. at->waitResponse();
  81. }
  82. virtual size_t write(const uint8_t *buf, size_t size) {
  83. TINY_GSM_YIELD();
  84. //at->maintain();
  85. return at->modemSend(buf, size, mux);
  86. }
  87. virtual size_t write(uint8_t c) {
  88. return write(&c, 1);
  89. }
  90. virtual int available() {
  91. TINY_GSM_YIELD();
  92. if (!rx.size()) {
  93. at->maintain();
  94. }
  95. return rx.size();
  96. }
  97. virtual int read(uint8_t *buf, size_t size) {
  98. TINY_GSM_YIELD();
  99. size_t cnt = 0;
  100. while (cnt < size) {
  101. size_t chunk = TinyGsmMin(size-cnt, rx.size());
  102. if (chunk > 0) {
  103. rx.get(buf, chunk);
  104. buf += chunk;
  105. cnt += chunk;
  106. continue;
  107. }
  108. // TODO: Read directly into user buffer?
  109. if (!rx.size()) {
  110. at->maintain();
  111. //break;
  112. }
  113. }
  114. return cnt;
  115. }
  116. virtual int read() {
  117. uint8_t c;
  118. if (read(&c, 1) == 1) {
  119. return c;
  120. }
  121. return -1;
  122. }
  123. virtual int peek() { return -1; } //TODO
  124. virtual void flush() { at->stream.flush(); }
  125. virtual uint8_t connected() {
  126. if (available()) {
  127. return true;
  128. }
  129. return sock_connected;
  130. }
  131. virtual operator bool() { return connected(); }
  132. private:
  133. TinyGsm* at;
  134. uint8_t mux;
  135. bool sock_connected;
  136. RxFifo rx;
  137. };
  138. public:
  139. /*
  140. * Basic functions
  141. */
  142. bool begin() {
  143. return init();
  144. }
  145. bool init() {
  146. if (!autoBaud()) {
  147. return false;
  148. }
  149. sendAT(GF("&FZE0")); // Factory + Reset + Echo Off
  150. if (waitResponse() != 1) {
  151. return false;
  152. }
  153. sendAT(GF("+CMEE=0"));
  154. waitResponse();
  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("&W")); // Write configuration
  178. return waitResponse() == 1;
  179. }
  180. /*
  181. * Power functions
  182. */
  183. bool restart() {
  184. if (!autoBaud()) {
  185. return false;
  186. }
  187. sendAT(GF("+RST=1"));
  188. delay(3000);
  189. return init();
  190. }
  191. /*
  192. * SIM card & Networ Operator functions
  193. */
  194. bool simUnlock(const char *pin) {
  195. sendAT(GF("+CPIN=\""), pin, GF("\""));
  196. return waitResponse() == 1;
  197. }
  198. String getSimCCID() {
  199. sendAT(GF("+CCID"));
  200. if (waitResponse(GF(GSM_NL "+ICCID:")) != 1) {
  201. return "";
  202. }
  203. String res = stream.readStringUntil('\n');
  204. waitResponse();
  205. res.trim();
  206. return res;
  207. }
  208. String getIMEI() {
  209. sendAT(GF("+GSN"));
  210. if (waitResponse(GF(GSM_NL)) != 1) {
  211. return "";
  212. }
  213. String res = stream.readStringUntil('\n');
  214. waitResponse();
  215. res.trim();
  216. return res;
  217. }
  218. int getSignalQuality() {
  219. sendAT(GF("+CSQ"));
  220. if (waitResponse(GF(GSM_NL "+CSQ:")) != 1) {
  221. return 99;
  222. }
  223. int res = stream.readStringUntil(',').toInt();
  224. waitResponse();
  225. return res;
  226. }
  227. bool callAnswer() {
  228. sendAT(GF("A"));
  229. return waitResponse() == 1;
  230. }
  231. bool callNumber(const String& number) {
  232. sendAT(GF("D"), number);
  233. return waitResponse() == 1;
  234. }
  235. bool callHangup(const String& number) {
  236. sendAT(GF("H"), number);
  237. return waitResponse() == 1;
  238. }
  239. bool sendSMS(const String& number, const String& text) {
  240. sendAT(GF("+CMGF=1"));
  241. waitResponse();
  242. sendAT(GF("+CMGS=\""), number, GF("\""));
  243. if (waitResponse(GF(">")) != 1) {
  244. return false;
  245. }
  246. stream.print(text);
  247. stream.write((char)0x1A);
  248. return waitResponse(60000L) == 1;
  249. }
  250. SimStatus getSimStatus(unsigned long timeout = 10000L) {
  251. for (unsigned long start = millis(); millis() - start < timeout; ) {
  252. sendAT(GF("+CPIN?"));
  253. if (waitResponse(GF(GSM_NL "+CPIN:")) != 1) {
  254. delay(1000);
  255. continue;
  256. }
  257. int status = waitResponse(GF("READY"), GF("SIM PIN"), GF("SIM PUK"));
  258. waitResponse();
  259. switch (status) {
  260. case 2:
  261. case 3: return SIM_LOCKED;
  262. case 1: return SIM_READY;
  263. default: return SIM_ERROR;
  264. }
  265. }
  266. return SIM_ERROR;
  267. }
  268. RegStatus getRegistrationStatus() {
  269. sendAT(GF("+CREG?"));
  270. if (waitResponse(GF(GSM_NL "+CREG:")) != 1) {
  271. return REG_UNKNOWN;
  272. }
  273. streamSkipUntil(','); // Skip format (0)
  274. int status = stream.readStringUntil('\n').toInt();
  275. waitResponse();
  276. return (RegStatus)status;
  277. }
  278. String getOperator() {
  279. sendAT(GF("+COPS?"));
  280. if (waitResponse(GF(GSM_NL "+COPS:")) != 1) {
  281. return "";
  282. }
  283. streamSkipUntil('"'); // Skip mode and format
  284. String res = stream.readStringUntil('"');
  285. waitResponse();
  286. return res;
  287. }
  288. bool waitForNetwork(unsigned long timeout = 60000L) {
  289. for (unsigned long start = millis(); millis() - start < timeout; ) {
  290. RegStatus s = getRegistrationStatus();
  291. if (s == REG_OK_HOME || s == REG_OK_ROAMING) {
  292. return true;
  293. } else if (s == REG_UNREGISTERED) {
  294. return false;
  295. }
  296. delay(1000);
  297. }
  298. return false;
  299. }
  300. /*
  301. * GPRS functions
  302. */
  303. bool gprsConnect(const char* apn, const char* user, const char* pwd) {
  304. gprsDisconnect();
  305. sendAT(GF("+CGDCONT=1,\"IP\",\""), apn, '"');
  306. waitResponse();
  307. sendAT(GF("+CSTT=\""), apn, GF("\",\""), user, GF("\",\""), pwd, GF("\""));
  308. if (waitResponse(60000L) != 1) {
  309. return false;
  310. }
  311. /*sendAT(GF("+CIICR"));
  312. if (waitResponse(60000L) != 1) {
  313. return false;
  314. }*/
  315. sendAT(GF("+CGACT=1,1"));
  316. waitResponse(60000L);
  317. sendAT(GF("+CGATT=1"));
  318. if (waitResponse(60000L) != 1)
  319. return false;
  320. // TODO: wait AT+CGATT?
  321. sendAT(GF("+CIPMUX=1"));
  322. if (waitResponse() != 1) {
  323. return false;
  324. }
  325. /*sendAT(GF("+CIFSR"));
  326. String data;
  327. if (waitResponse(10000L, data) != 1) {
  328. data.replace(GSM_NL, "");
  329. return false;
  330. }*/
  331. return true;
  332. }
  333. bool gprsDisconnect() {
  334. sendAT(GF("+CIPSHUT"));
  335. return waitResponse(60000L) == 1;
  336. }
  337. /*
  338. * Phone Call functions
  339. */
  340. /*
  341. * Messaging functions
  342. */
  343. void sendUSSD() {
  344. }
  345. void sendSMS() {
  346. }
  347. /*
  348. * Location functions
  349. */
  350. void getLocation() {
  351. }
  352. /*
  353. * Battery functions
  354. */
  355. private:
  356. int modemConnect(const char* host, uint16_t port, uint8_t* mux) {
  357. sendAT(GF("+CIPSTART="), GF("\"TCP"), GF("\",\""), host, GF("\","), port);
  358. if (waitResponse(75000L, GF(GSM_NL "+CIPNUM:")) != 1) {
  359. return -1;
  360. }
  361. int newMux = stream.readStringUntil('\n').toInt();
  362. int rsp = waitResponse(75000L,
  363. GF("CONNECT OK" GSM_NL),
  364. GF("CONNECT FAIL" GSM_NL),
  365. GF("ALREADY CONNECT" GSM_NL));
  366. if (waitResponse() != 1) {
  367. return -1;
  368. }
  369. *mux = newMux;
  370. return (1 == rsp);
  371. }
  372. int modemSend2(const void* buff, size_t len, uint8_t mux) {
  373. streamWrite(GF("AT+CIPSEND="), mux, ",", len, ",");
  374. stream.write((uint8_t*)buff, len);
  375. stream.print(GSM_NL);
  376. stream.flush();
  377. if (waitResponse(10000L, GF(GSM_NL "OK"), GF(GSM_NL "FAIL")) != 1) {
  378. return -1;
  379. }
  380. return len;
  381. }
  382. int modemSend(const void* buff, size_t len, uint8_t mux) {
  383. sendAT(GF("+CIPSEND="), mux, ",", len);
  384. if (waitResponse(10000L, GF(GSM_NL ">")) != 1) {
  385. return -1;
  386. }
  387. stream.write((uint8_t*)buff, len);
  388. stream.flush();
  389. if (waitResponse(10000L, GFP(GSM_OK), GF(GSM_NL "FAIL")) != 1) {
  390. return -1;
  391. }
  392. return len;
  393. }
  394. bool modemGetConnected(uint8_t mux) {
  395. sendAT(GF("+CIPSTATUS"));
  396. int res = waitResponse(GF(",\"CONNECTED\""), GF(",\"CLOSED\""), GF(",\"CLOSING\""), GF(",\"INITIAL\""));
  397. waitResponse();
  398. return 1 == res;
  399. }
  400. /* Utilities */
  401. template<typename T>
  402. void streamWrite(T last) {
  403. stream.print(last);
  404. }
  405. template<typename T, typename... Args>
  406. void streamWrite(T head, Args... tail) {
  407. stream.print(head);
  408. streamWrite(tail...);
  409. }
  410. int streamRead() { return stream.read(); }
  411. bool streamSkipUntil(char c) { //TODO: timeout
  412. while (true) {
  413. while (!stream.available()) {}
  414. if (stream.read() == c)
  415. return true;
  416. }
  417. return false;
  418. }
  419. template<typename... Args>
  420. void sendAT(Args... cmd) {
  421. streamWrite("AT", cmd..., GSM_NL);
  422. stream.flush();
  423. TINY_GSM_YIELD();
  424. //DBG("### AT:", cmd...);
  425. }
  426. // TODO: Optimize this!
  427. uint8_t waitResponse(uint32_t timeout, String& data,
  428. GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  429. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  430. {
  431. /*String r1s(r1); r1s.trim();
  432. String r2s(r2); r2s.trim();
  433. String r3s(r3); r3s.trim();
  434. String r4s(r4); r4s.trim();
  435. String r5s(r5); r5s.trim();
  436. DBG("### ..:", r1s, ",", r2s, ",", r3s, ",", r4s, ",", r5s);*/
  437. data.reserve(64);
  438. int index = 0;
  439. unsigned long startMillis = millis();
  440. do {
  441. TINY_GSM_YIELD();
  442. while (stream.available() > 0) {
  443. int a = streamRead();
  444. if (a <= 0) continue; // Skip 0x00 bytes, just in case
  445. data += (char)a;
  446. if (r1 && data.endsWith(r1)) {
  447. index = 1;
  448. goto finish;
  449. } else if (r2 && data.endsWith(r2)) {
  450. index = 2;
  451. goto finish;
  452. } else if (r3 && data.endsWith(r3)) {
  453. index = 3;
  454. goto finish;
  455. } else if (r4 && data.endsWith(r4)) {
  456. index = 4;
  457. goto finish;
  458. } else if (r5 && data.endsWith(r5)) {
  459. index = 5;
  460. goto finish;
  461. } else if (data.endsWith(GF("+CIPRCV:"))) {
  462. int mux = stream.readStringUntil(',').toInt();
  463. int len = stream.readStringUntil(',').toInt();
  464. if (len > sockets[mux]->rx.free()) {
  465. DBG("### Buffer overflow: ", len, "->", sockets[mux]->rx.free());
  466. } else {
  467. DBG("### Got: ", len, "->", sockets[mux]->rx.free());
  468. }
  469. while (len--) {
  470. while (!stream.available()) {}
  471. sockets[mux]->rx.put(stream.read());
  472. }
  473. data = "";
  474. return index;
  475. } else if (data.endsWith(GF("+TCPCLOSED:"))) {
  476. int mux = stream.readStringUntil(',').toInt();
  477. stream.readStringUntil('\n');
  478. sockets[mux]->sock_connected = false;
  479. data = "";
  480. }
  481. }
  482. } while (millis() - startMillis < timeout);
  483. finish:
  484. if (!index) {
  485. data.trim();
  486. if (data.length()) {
  487. DBG("### Unhandled:", data);
  488. }
  489. data = "";
  490. }
  491. return index;
  492. }
  493. uint8_t waitResponse(uint32_t timeout,
  494. GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  495. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  496. {
  497. String data;
  498. return waitResponse(timeout, data, r1, r2, r3, r4, r5);
  499. }
  500. uint8_t waitResponse(GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  501. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  502. {
  503. return waitResponse(1000, r1, r2, r3, r4, r5);
  504. }
  505. private:
  506. Stream& stream;
  507. GsmClient* sockets[2];
  508. };
  509. typedef TinyGsm::GsmClient TinyGsmClient;
  510. #endif