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.

594 lines
14 KiB

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