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.

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