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.

611 lines
14 KiB

8 years ago
8 years ago
7 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. /*
  130. * Extended API
  131. */
  132. String remoteIP() TINY_GSM_ATTR_NOT_IMPLEMENTED;
  133. private:
  134. TinyGsm* at;
  135. uint8_t mux;
  136. bool sock_connected;
  137. RxFifo rx;
  138. };
  139. public:
  140. TinyGsm(Stream& stream)
  141. : stream(stream)
  142. {
  143. memset(sockets, 0, sizeof(sockets));
  144. }
  145. /*
  146. * Basic functions
  147. */
  148. bool begin() {
  149. return init();
  150. }
  151. bool init() {
  152. if (!autoBaud()) {
  153. return false;
  154. }
  155. sendAT(GF("&FZE0")); // Factory + Reset + Echo Off
  156. if (waitResponse() != 1) {
  157. return false;
  158. }
  159. sendAT(GF("+CMEE=0"));
  160. waitResponse();
  161. getSimStatus();
  162. return true;
  163. }
  164. bool autoBaud(unsigned long timeout = 10000L) {
  165. for (unsigned long start = millis(); millis() - start < timeout; ) {
  166. sendAT(GF("E0"));
  167. if (waitResponse(200) == 1) {
  168. delay(100);
  169. return true;
  170. }
  171. delay(100);
  172. }
  173. return false;
  174. }
  175. void maintain() {
  176. //while (stream.available()) {
  177. waitResponse(10, NULL, NULL);
  178. //}
  179. }
  180. bool factoryDefault() {
  181. sendAT(GF("&FZE0&W")); // Factory + Reset + Echo Off + Write
  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("+RST=1"));
  194. delay(3000);
  195. return init();
  196. }
  197. bool poweroff() {
  198. sendAT(GF("+CPOF"));
  199. return waitResponse() == 1;
  200. }
  201. /*
  202. * SIM card functions
  203. */
  204. bool simUnlock(const char *pin) {
  205. sendAT(GF("+CPIN=\""), pin, GF("\""));
  206. return waitResponse() == 1;
  207. }
  208. String getSimCCID() {
  209. sendAT(GF("+CCID"));
  210. if (waitResponse(GF(GSM_NL "+ICCID:")) != 1) {
  211. return "";
  212. }
  213. String res = stream.readStringUntil('\n');
  214. waitResponse();
  215. res.trim();
  216. return res;
  217. }
  218. String getIMEI() {
  219. sendAT(GF("+GSN"));
  220. if (waitResponse(GF(GSM_NL)) != 1) {
  221. return "";
  222. }
  223. String res = stream.readStringUntil('\n');
  224. waitResponse();
  225. res.trim();
  226. return res;
  227. }
  228. SimStatus getSimStatus(unsigned long timeout = 10000L) {
  229. for (unsigned long start = millis(); millis() - start < timeout; ) {
  230. sendAT(GF("+CPIN?"));
  231. if (waitResponse(GF(GSM_NL "+CPIN:")) != 1) {
  232. delay(1000);
  233. continue;
  234. }
  235. int status = waitResponse(GF("READY"), GF("SIM PIN"), GF("SIM PUK"));
  236. waitResponse();
  237. switch (status) {
  238. case 2:
  239. case 3: return SIM_LOCKED;
  240. case 1: return SIM_READY;
  241. default: return SIM_ERROR;
  242. }
  243. }
  244. return SIM_ERROR;
  245. }
  246. RegStatus getRegistrationStatus() {
  247. sendAT(GF("+CREG?"));
  248. if (waitResponse(GF(GSM_NL "+CREG:")) != 1) {
  249. return REG_UNKNOWN;
  250. }
  251. streamSkipUntil(','); // Skip format (0)
  252. int status = stream.readStringUntil('\n').toInt();
  253. waitResponse();
  254. return (RegStatus)status;
  255. }
  256. String getOperator() {
  257. sendAT(GF("+COPS?"));
  258. if (waitResponse(GF(GSM_NL "+COPS:")) != 1) {
  259. return "";
  260. }
  261. streamSkipUntil('"'); // Skip mode and format
  262. String res = stream.readStringUntil('"');
  263. waitResponse();
  264. return res;
  265. }
  266. /*
  267. * Generic network functions
  268. */
  269. int getSignalQuality() {
  270. sendAT(GF("+CSQ"));
  271. if (waitResponse(GF(GSM_NL "+CSQ:")) != 1) {
  272. return 99;
  273. }
  274. int res = stream.readStringUntil(',').toInt();
  275. waitResponse();
  276. return res;
  277. }
  278. bool waitForNetwork(unsigned long timeout = 60000L) {
  279. for (unsigned long start = millis(); millis() - start < timeout; ) {
  280. RegStatus s = getRegistrationStatus();
  281. if (s == REG_OK_HOME || s == REG_OK_ROAMING) {
  282. return true;
  283. }
  284. delay(1000);
  285. }
  286. return false;
  287. }
  288. /*
  289. * GPRS functions
  290. */
  291. bool gprsConnect(const char* apn, const char* user, const char* pwd) {
  292. gprsDisconnect();
  293. sendAT(GF("+CGATT=1"));
  294. if (waitResponse(60000L) != 1)
  295. return false;
  296. // TODO: wait AT+CGATT?
  297. sendAT(GF("+CGDCONT=1,\"IP\",\""), apn, '"');
  298. waitResponse();
  299. if (!user) user = "";
  300. if (!pwd) pwd = "";
  301. sendAT(GF("+CSTT=\""), apn, GF("\",\""), user, GF("\",\""), pwd, GF("\""));
  302. if (waitResponse(60000L) != 1) {
  303. return false;
  304. }
  305. sendAT(GF("+CGACT=1,1"));
  306. waitResponse(60000L);
  307. sendAT(GF("+CIPMUX=1"));
  308. if (waitResponse() != 1) {
  309. return false;
  310. }
  311. return true;
  312. }
  313. bool gprsDisconnect() {
  314. sendAT(GF("+CIPSHUT"));
  315. return waitResponse(60000L) == 1;
  316. }
  317. String getLocalIP() {
  318. sendAT(GF("+CIFSR"));
  319. String res;
  320. if (waitResponse(10000L, res) != 1) {
  321. return "";
  322. }
  323. res.trim();
  324. return res;
  325. }
  326. IPAddress localIP() TINY_GSM_ATTR_NOT_IMPLEMENTED;
  327. /*
  328. * Phone Call functions
  329. */
  330. bool setGsmBusy(bool busy = true) TINY_GSM_ATTR_NOT_AVAILABLE;
  331. bool callAnswer() {
  332. sendAT(GF("A"));
  333. return waitResponse() == 1;
  334. }
  335. bool callNumber(const String& number) {
  336. sendAT(GF("D"), number);
  337. return waitResponse() == 1;
  338. }
  339. void callRedial() {
  340. sendAT(GF("DLST"));
  341. return waitResponse() == 1;
  342. }
  343. bool callHangup(const String& number) {
  344. sendAT(GF("H"), number);
  345. return waitResponse() == 1;
  346. }
  347. /*
  348. * Messaging functions
  349. */
  350. void sendUSSD() TINY_GSM_ATTR_NOT_IMPLEMENTED;
  351. bool sendSMS(const String& number, const String& text) {
  352. sendAT(GF("+CMGF=1"));
  353. waitResponse();
  354. sendAT(GF("+CMGS=\""), number, GF("\""));
  355. if (waitResponse(GF(">")) != 1) {
  356. return false;
  357. }
  358. stream.print(text);
  359. stream.write((char)0x1A);
  360. stream.flush();
  361. return waitResponse(60000L) == 1;
  362. }
  363. /*
  364. * Location functions
  365. */
  366. String getGsmLocation() TINY_GSM_ATTR_NOT_AVAILABLE;
  367. /*
  368. * Battery functions
  369. */
  370. uint16_t getBattVoltage() TINY_GSM_ATTR_NOT_AVAILABLE;
  371. int getBattPercent() TINY_GSM_ATTR_NOT_AVAILABLE;
  372. private:
  373. bool modemConnect(const char* host, uint16_t port, uint8_t* mux) {
  374. sendAT(GF("+CIPSTART="), GF("\"TCP"), GF("\",\""), host, GF("\","), port);
  375. if (waitResponse(75000L, GF(GSM_NL "+CIPNUM:")) != 1) {
  376. return false;
  377. }
  378. int newMux = stream.readStringUntil('\n').toInt();
  379. int rsp = waitResponse(75000L,
  380. GF("CONNECT OK" GSM_NL),
  381. GF("CONNECT FAIL" GSM_NL),
  382. GF("ALREADY CONNECT" GSM_NL));
  383. if (waitResponse() != 1) {
  384. return false;
  385. }
  386. *mux = newMux;
  387. return (1 == rsp);
  388. }
  389. int modemSend(const void* buff, size_t len, uint8_t mux) {
  390. sendAT(GF("+CIPSEND="), mux, ',', len);
  391. if (waitResponse(2000L, GF(GSM_NL ">")) != 1) {
  392. return -1;
  393. }
  394. stream.write((uint8_t*)buff, len);
  395. stream.flush();
  396. if (waitResponse(10000L, GFP(GSM_OK), GF(GSM_NL "FAIL")) != 1) {
  397. return -1;
  398. }
  399. return len;
  400. }
  401. bool modemGetConnected(uint8_t mux) { //TODO mux?
  402. sendAT(GF("+CIPSTATUS"));
  403. int res = waitResponse(GF(",\"CONNECTED\""), GF(",\"CLOSED\""), GF(",\"CLOSING\""), GF(",\"INITIAL\""));
  404. waitResponse();
  405. return 1 == res;
  406. }
  407. public:
  408. /* Utilities */
  409. template<typename T>
  410. void streamWrite(T last) {
  411. stream.print(last);
  412. }
  413. template<typename T, typename... Args>
  414. void streamWrite(T head, Args... tail) {
  415. stream.print(head);
  416. streamWrite(tail...);
  417. }
  418. bool streamSkipUntil(char c) { //TODO: timeout
  419. while (true) {
  420. while (!stream.available()) { TINY_GSM_YIELD(); }
  421. if (stream.read() == c)
  422. return true;
  423. }
  424. return false;
  425. }
  426. template<typename... Args>
  427. void sendAT(Args... cmd) {
  428. streamWrite("AT", cmd..., GSM_NL);
  429. stream.flush();
  430. TINY_GSM_YIELD();
  431. //DBG("### AT:", cmd...);
  432. }
  433. // TODO: Optimize this!
  434. uint8_t waitResponse(uint32_t timeout, String& data,
  435. GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  436. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  437. {
  438. /*String r1s(r1); r1s.trim();
  439. String r2s(r2); r2s.trim();
  440. String r3s(r3); r3s.trim();
  441. String r4s(r4); r4s.trim();
  442. String r5s(r5); r5s.trim();
  443. DBG("### ..:", r1s, ",", r2s, ",", r3s, ",", r4s, ",", r5s);*/
  444. data.reserve(64);
  445. int index = 0;
  446. unsigned long startMillis = millis();
  447. do {
  448. TINY_GSM_YIELD();
  449. while (stream.available() > 0) {
  450. int a = stream.read();
  451. if (a <= 0) continue; // Skip 0x00 bytes, just in case
  452. data += (char)a;
  453. if (r1 && data.endsWith(r1)) {
  454. index = 1;
  455. goto finish;
  456. } else if (r2 && data.endsWith(r2)) {
  457. index = 2;
  458. goto finish;
  459. } else if (r3 && data.endsWith(r3)) {
  460. index = 3;
  461. goto finish;
  462. } else if (r4 && data.endsWith(r4)) {
  463. index = 4;
  464. goto finish;
  465. } else if (r5 && data.endsWith(r5)) {
  466. index = 5;
  467. goto finish;
  468. } else if (data.endsWith(GF("+CIPRCV:"))) {
  469. int mux = stream.readStringUntil(',').toInt();
  470. int len = stream.readStringUntil(',').toInt();
  471. if (len > sockets[mux]->rx.free()) {
  472. DBG("### Buffer overflow: ", len, "->", sockets[mux]->rx.free());
  473. } else {
  474. DBG("### Got: ", len, "->", sockets[mux]->rx.free());
  475. }
  476. while (len--) {
  477. while (!stream.available()) { TINY_GSM_YIELD(); }
  478. sockets[mux]->rx.put(stream.read());
  479. }
  480. data = "";
  481. } else if (data.endsWith(GF("+TCPCLOSED:"))) {
  482. int mux = stream.readStringUntil('\n').toInt();
  483. sockets[mux]->sock_connected = false;
  484. data = "";
  485. DBG("### Closed: ", mux);
  486. }
  487. }
  488. } while (millis() - startMillis < timeout);
  489. finish:
  490. if (!index) {
  491. data.trim();
  492. if (data.length()) {
  493. DBG("### Unhandled:", data);
  494. }
  495. data = "";
  496. }
  497. return index;
  498. }
  499. uint8_t waitResponse(uint32_t timeout,
  500. GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  501. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  502. {
  503. String data;
  504. return waitResponse(timeout, data, r1, r2, r3, r4, r5);
  505. }
  506. uint8_t waitResponse(GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  507. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  508. {
  509. return waitResponse(1000, r1, r2, r3, r4, r5);
  510. }
  511. private:
  512. Stream& stream;
  513. GsmClient* sockets[TINY_GSM_MUX_COUNT];
  514. };
  515. typedef TinyGsm::GsmClient TinyGsmClient;
  516. #endif