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.

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