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.

529 lines
13 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
7 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
7 years ago
7 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 TinyGsmClientESP8266.h
  3. * @author Volodymyr Shymanskyy
  4. * @license LGPL-3.0
  5. * @copyright Copyright (c) 2016 Volodymyr Shymanskyy
  6. * @date Nov 2016
  7. */
  8. #ifndef TinyGsmClientESP8266_h
  9. #define TinyGsmClientESP8266_h
  10. //#define TINY_GSM_DEBUG Serial
  11. #if !defined(TINY_GSM_RX_BUFFER)
  12. #define TINY_GSM_RX_BUFFER 512
  13. #endif
  14. #define TINY_GSM_MUX_COUNT 5
  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. static unsigned TINY_GSM_TCP_KEEP_ALIVE = 120;
  20. class TinyGsm
  21. {
  22. public:
  23. class GsmClient : public Client
  24. {
  25. friend class TinyGsm;
  26. typedef TinyGsmFifo<uint8_t, TINY_GSM_RX_BUFFER> RxFifo;
  27. public:
  28. GsmClient() {}
  29. GsmClient(TinyGsm& modem, uint8_t mux = 1) {
  30. init(&modem, mux);
  31. }
  32. bool init(TinyGsm* modem, uint8_t mux = 1) {
  33. this->at = modem;
  34. this->mux = mux;
  35. sock_connected = false;
  36. at->sockets[mux] = this;
  37. return true;
  38. }
  39. public:
  40. virtual int connect(const char *host, uint16_t port) {
  41. TINY_GSM_YIELD();
  42. rx.clear();
  43. sock_connected = at->modemConnect(host, port, mux);
  44. return sock_connected;
  45. }
  46. virtual int connect(IPAddress ip, uint16_t port) {
  47. String host; host.reserve(16);
  48. host += ip[0];
  49. host += ".";
  50. host += ip[1];
  51. host += ".";
  52. host += ip[2];
  53. host += ".";
  54. host += ip[3];
  55. return connect(host.c_str(), port);
  56. }
  57. virtual void stop() {
  58. TINY_GSM_YIELD();
  59. at->sendAT(GF("+CIPCLOSE="), mux);
  60. sock_connected = false;
  61. at->waitResponse();
  62. }
  63. virtual size_t write(const uint8_t *buf, size_t size) {
  64. TINY_GSM_YIELD();
  65. //at->maintain();
  66. return at->modemSend(buf, size, mux);
  67. }
  68. virtual size_t write(uint8_t c) {
  69. return write(&c, 1);
  70. }
  71. virtual int available() {
  72. TINY_GSM_YIELD();
  73. if (!rx.size() && sock_connected) {
  74. at->maintain();
  75. }
  76. return rx.size();
  77. }
  78. virtual int read(uint8_t *buf, size_t size) {
  79. TINY_GSM_YIELD();
  80. size_t cnt = 0;
  81. while (cnt < size) {
  82. size_t chunk = TinyGsmMin(size-cnt, rx.size());
  83. if (chunk > 0) {
  84. rx.get(buf, chunk);
  85. buf += chunk;
  86. cnt += chunk;
  87. continue;
  88. }
  89. // TODO: Read directly into user buffer?
  90. if (!rx.size() && sock_connected) {
  91. at->maintain();
  92. //break;
  93. }
  94. }
  95. return cnt;
  96. }
  97. virtual int read() {
  98. uint8_t c;
  99. if (read(&c, 1) == 1) {
  100. return c;
  101. }
  102. return -1;
  103. }
  104. virtual int peek() { return -1; } //TODO
  105. virtual void flush() { at->stream.flush(); }
  106. virtual uint8_t connected() {
  107. if (available()) {
  108. return true;
  109. }
  110. return sock_connected;
  111. }
  112. virtual operator bool() { return connected(); }
  113. /*
  114. * Extended API
  115. */
  116. String remoteIP() TINY_GSM_ATTR_NOT_IMPLEMENTED;
  117. private:
  118. TinyGsm* at;
  119. uint8_t mux;
  120. bool sock_connected;
  121. RxFifo rx;
  122. };
  123. class GsmClientSecure : public GsmClient
  124. {
  125. public:
  126. GsmClientSecure() {}
  127. GsmClientSecure(TinyGsm& modem, uint8_t mux = 1)
  128. : GsmClient(modem, mux)
  129. {}
  130. public:
  131. virtual int connect(const char *host, uint16_t port) {
  132. TINY_GSM_YIELD();
  133. rx.clear();
  134. sock_connected = at->modemConnect(host, port, mux, true);
  135. return sock_connected;
  136. }
  137. };
  138. public:
  139. TinyGsm(Stream& stream)
  140. : stream(stream)
  141. {
  142. memset(sockets, 0, sizeof(sockets));
  143. }
  144. /*
  145. * Basic functions
  146. */
  147. bool begin() {
  148. return init();
  149. }
  150. bool init() {
  151. if (!testAT()) {
  152. return false;
  153. }
  154. sendAT(GF("E0")); // Echo Off
  155. if (waitResponse() != 1) {
  156. return false;
  157. }
  158. return true;
  159. }
  160. void setBaud(unsigned long baud) {
  161. sendAT(GF("+IPR="), baud);
  162. }
  163. bool testAT(unsigned long timeout = 10000L) {
  164. for (unsigned long start = millis(); millis() - start < timeout; ) {
  165. sendAT(GF(""));
  166. if (waitResponse(200) == 1) {
  167. delay(100);
  168. return true;
  169. }
  170. delay(100);
  171. }
  172. return false;
  173. }
  174. void maintain() {
  175. waitResponse(10, NULL, NULL);
  176. }
  177. bool factoryDefault() {
  178. sendAT(GF("+RESTORE"));
  179. return waitResponse() == 1;
  180. }
  181. String getModemInfo() {
  182. sendAT(GF("+GMR"));
  183. String res;
  184. if (waitResponse(1000L, res) != 1) {
  185. return "";
  186. }
  187. res.replace(GSM_NL "OK" GSM_NL, "");
  188. res.replace(GSM_NL, " ");
  189. res.trim();
  190. return res;
  191. }
  192. bool hasSSL() {
  193. return true;
  194. }
  195. /*
  196. * Power functions
  197. */
  198. bool restart() {
  199. if (!testAT()) {
  200. return false;
  201. }
  202. sendAT(GF("+RST"));
  203. if (waitResponse(10000L) != 1) {
  204. return false;
  205. }
  206. if (waitResponse(10000L, GF(GSM_NL "ready" GSM_NL)) != 1) {
  207. return false;
  208. }
  209. delay(500);
  210. return init();
  211. }
  212. /*
  213. * Generic network functions
  214. */
  215. int getSignalQuality() {
  216. sendAT(GF("+CWJAP_CUR?"));
  217. int res1 = waitResponse(GF("No AP"), GF("+CWJAP_CUR:"));
  218. if (res1 != 2) {
  219. waitResponse();
  220. return 0;
  221. }
  222. streamSkipUntil(','); // Skip SSID
  223. streamSkipUntil(','); // Skip BSSID/MAC address
  224. streamSkipUntil(','); // Skip Chanel number
  225. int res2 = stream.parseInt(); // Read RSSI
  226. waitResponse(); // Returns an OK after the value
  227. return res2;
  228. }
  229. bool isNetworkConnected() {
  230. sendAT(GF("+CIPSTATUS"));
  231. int res1 = waitResponse(3000, GF("STATUS:"));
  232. int res2 = 0;
  233. if (res1 == 1) {
  234. res2 = waitResponse(GFP(GSM_ERROR), GF("2"), GF("3"), GF("4"), GF("5"));
  235. }
  236. // <stat> status of ESP8266 station interface
  237. // 2 : ESP8266 station connected to an AP and has obtained IP
  238. // 3 : ESP8266 station created a TCP or UDP transmission
  239. // 4 : the TCP or UDP transmission of ESP8266 station disconnected (but AP is connected)
  240. // 5 : ESP8266 station did NOT connect to an AP
  241. waitResponse(); // Returns an OK after the status
  242. if (res2 == 2 || res2 == 3 || res2 == 4) return true;
  243. else return false;
  244. }
  245. bool waitForNetwork(unsigned long timeout = 60000L) {
  246. for (unsigned long start = millis(); millis() - start < timeout; ) {
  247. sendAT(GF("+CIPSTATUS"));
  248. int res1 = waitResponse(3000, GF("busy p..."), GF("STATUS:"));
  249. if (res1 == 2) {
  250. int res2 = waitResponse(GFP(GSM_ERROR), GF("2"), GF("3"), GF("4"), GF("5"));
  251. if (res2 == 2 || res2 == 3 || res2 == 4) {
  252. waitResponse();
  253. return true;
  254. }
  255. }
  256. delay(250);
  257. }
  258. return false;
  259. }
  260. /*
  261. * WiFi functions
  262. */
  263. bool networkConnect(const char* ssid, const char* pwd) {
  264. sendAT(GF("+CIPMUX=1"));
  265. if (waitResponse() != 1) {
  266. return false;
  267. }
  268. sendAT(GF("+CWMODE_CUR=1"));
  269. if (waitResponse() != 1) {
  270. return false;
  271. }
  272. sendAT(GF("+CWJAP_CUR=\""), ssid, GF("\",\""), pwd, GF("\""));
  273. if (waitResponse(30000L, GFP(GSM_OK), GF(GSM_NL "FAIL" GSM_NL)) != 1) {
  274. return false;
  275. }
  276. return true;
  277. }
  278. bool networkDisconnect() {
  279. sendAT(GF("+CWQAP"));
  280. bool retVal = waitResponse(10000L) == 1;
  281. waitResponse(GF("WIFI DISCONNECT"));
  282. return retVal;
  283. }
  284. String getLocalIP() {
  285. sendAT(GF("+CIPSTA_CUR??"));
  286. int res1 = waitResponse(GF("ERROR"), GF("+CWJAP_CUR:"));
  287. if (res1 != 2) {
  288. return "";
  289. }
  290. String res2 = stream.readStringUntil('"');
  291. waitResponse();
  292. return res2;
  293. }
  294. IPAddress localIP() {
  295. return TinyGsmIpFromString(getLocalIP());
  296. }
  297. protected:
  298. bool modemConnect(const char* host, uint16_t port, uint8_t mux, bool ssl = false) {
  299. if (ssl) {
  300. sendAT(GF("+CIPSSLSIZE=4096"));
  301. waitResponse();
  302. }
  303. sendAT(GF("+CIPSTART="), mux, ',', ssl ? GF("\"SSL") : GF("\"TCP"), GF("\",\""), host, GF("\","), port, GF(","), TINY_GSM_TCP_KEEP_ALIVE);
  304. // TODO: Check mux
  305. int rsp = waitResponse(75000L,
  306. GFP(GSM_OK),
  307. GFP(GSM_ERROR),
  308. GF("ALREADY CONNECT"));
  309. // if (rsp == 3) waitResponse(); // May return "ERROR" after the "ALREADY CONNECT"
  310. return (1 == rsp);
  311. }
  312. int modemSend(const void* buff, size_t len, uint8_t mux) {
  313. sendAT(GF("+CIPSEND="), mux, ',', len);
  314. if (waitResponse(GF(">")) != 1) {
  315. return -1;
  316. }
  317. stream.write((uint8_t*)buff, len);
  318. stream.flush();
  319. if (waitResponse(10000L, GF(GSM_NL "SEND OK" GSM_NL)) != 1) {
  320. return -1;
  321. }
  322. return len;
  323. }
  324. bool modemGetConnected(uint8_t mux) {
  325. // TODO: re-check this
  326. sendAT(GF("+CIPSTATUS="), mux);
  327. int res1 = waitResponse(3000, GF("STATUS:"));
  328. int res2;
  329. if (res1 == 1) {
  330. res2 = waitResponse(GFP(GSM_ERROR), GF("2"), GF("3"), GF("4"), GF("5"));
  331. }
  332. // <stat> status of ESP8266 station interface
  333. // 2 : ESP8266 station connected to an AP and has obtained IP
  334. // 3 : ESP8266 station created a TCP or UDP transmission
  335. // 4 : the TCP or UDP transmission of ESP8266 station disconnected (but AP is connected)
  336. // 5 : ESP8266 station did NOT connect to an AP
  337. waitResponse(); // Returns an OK after the status
  338. if (res2 == 2 || res2 == 3 || res2 == 4) return true;
  339. else return false;
  340. }
  341. public:
  342. /* Utilities */
  343. template<typename T>
  344. void streamWrite(T last) {
  345. stream.print(last);
  346. }
  347. template<typename T, typename... Args>
  348. void streamWrite(T head, Args... tail) {
  349. stream.print(head);
  350. streamWrite(tail...);
  351. }
  352. bool streamSkipUntil(char c) { //TODO: timeout
  353. while (true) {
  354. while (!stream.available()) { TINY_GSM_YIELD(); }
  355. if (stream.read() == c)
  356. return true;
  357. }
  358. return false;
  359. }
  360. template<typename... Args>
  361. void sendAT(Args... cmd) {
  362. streamWrite("AT", cmd..., GSM_NL);
  363. stream.flush();
  364. TINY_GSM_YIELD();
  365. //DBG("### AT:", cmd...);
  366. }
  367. // TODO: Optimize this!
  368. uint8_t waitResponse(uint32_t timeout, String& data,
  369. GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  370. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  371. {
  372. /*String r1s(r1); r1s.trim();
  373. String r2s(r2); r2s.trim();
  374. String r3s(r3); r3s.trim();
  375. String r4s(r4); r4s.trim();
  376. String r5s(r5); r5s.trim();
  377. DBG("### ..:", r1s, ",", r2s, ",", r3s, ",", r4s, ",", r5s);*/
  378. data.reserve(64);
  379. int index = 0;
  380. unsigned long startMillis = millis();
  381. do {
  382. TINY_GSM_YIELD();
  383. while (stream.available() > 0) {
  384. int a = stream.read();
  385. if (a <= 0) continue; // Skip 0x00 bytes, just in case
  386. data += (char)a;
  387. if (r1 && data.endsWith(r1)) {
  388. index = 1;
  389. goto finish;
  390. } else if (r2 && data.endsWith(r2)) {
  391. index = 2;
  392. goto finish;
  393. } else if (r3 && data.endsWith(r3)) {
  394. index = 3;
  395. goto finish;
  396. } else if (r4 && data.endsWith(r4)) {
  397. index = 4;
  398. goto finish;
  399. } else if (r5 && data.endsWith(r5)) {
  400. index = 5;
  401. goto finish;
  402. } else if (data.endsWith(GF(GSM_NL "+IPD,"))) {
  403. int mux = stream.readStringUntil(',').toInt();
  404. int len = stream.readStringUntil(':').toInt();
  405. int len_orig = len;
  406. if (len > sockets[mux]->rx.free()) {
  407. DBG("### Buffer overflow: ", len, "->", sockets[mux]->rx.free());
  408. } else {
  409. DBG("### Got: ", len, "->", sockets[mux]->rx.free());
  410. }
  411. while (len--) {
  412. while (!stream.available()) { TINY_GSM_YIELD(); }
  413. sockets[mux]->rx.put(stream.read());
  414. }
  415. if (len_orig > sockets[mux]->available()) { // TODO
  416. DBG("### Fewer characters received than expected: ", sockets[mux]->available(), " vs ", len_orig);
  417. }
  418. data = "";
  419. } else if (data.endsWith(GF("CLOSED"))) {
  420. int muxStart = max(0,data.lastIndexOf(GSM_NL, data.length()-8));
  421. int coma = data.indexOf(',', muxStart);
  422. int mux = data.substring(muxStart, coma).toInt();
  423. if (mux >= 0 && mux < TINY_GSM_MUX_COUNT && sockets[mux]) {
  424. sockets[mux]->sock_connected = false;
  425. }
  426. data = "";
  427. DBG("### Closed: ", mux);
  428. }
  429. }
  430. } while (millis() - startMillis < timeout);
  431. finish:
  432. if (!index) {
  433. data.trim();
  434. if (data.length()) {
  435. DBG("### Unhandled:", data);
  436. }
  437. data = "";
  438. }
  439. return index;
  440. }
  441. uint8_t waitResponse(uint32_t timeout,
  442. GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  443. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  444. {
  445. String data;
  446. return waitResponse(timeout, data, r1, r2, r3, r4, r5);
  447. }
  448. uint8_t waitResponse(GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  449. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  450. {
  451. return waitResponse(1000, r1, r2, r3, r4, r5);
  452. }
  453. public:
  454. Stream& stream;
  455. protected:
  456. GsmClient* sockets[TINY_GSM_MUX_COUNT];
  457. };
  458. #endif