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.

531 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. uint32_t _startMillis = millis();
  82. while (cnt < size && millis() - _startMillis < _timeout) {
  83. size_t chunk = TinyGsmMin(size-cnt, rx.size());
  84. if (chunk > 0) {
  85. rx.get(buf, chunk);
  86. buf += chunk;
  87. cnt += chunk;
  88. continue;
  89. }
  90. // TODO: Read directly into user buffer?
  91. if (!rx.size() && sock_connected) {
  92. at->maintain();
  93. //break;
  94. }
  95. }
  96. return cnt;
  97. }
  98. virtual int read() {
  99. uint8_t c;
  100. if (read(&c, 1) == 1) {
  101. return c;
  102. }
  103. return -1;
  104. }
  105. virtual int peek() { return -1; } //TODO
  106. virtual void flush() { at->stream.flush(); }
  107. virtual uint8_t connected() {
  108. if (available()) {
  109. return true;
  110. }
  111. return sock_connected;
  112. }
  113. virtual operator bool() { return connected(); }
  114. /*
  115. * Extended API
  116. */
  117. String remoteIP() TINY_GSM_ATTR_NOT_IMPLEMENTED;
  118. private:
  119. TinyGsm* at;
  120. uint8_t mux;
  121. bool sock_connected;
  122. RxFifo rx;
  123. };
  124. class GsmClientSecure : public GsmClient
  125. {
  126. public:
  127. GsmClientSecure() {}
  128. GsmClientSecure(TinyGsm& modem, uint8_t mux = 1)
  129. : GsmClient(modem, mux)
  130. {}
  131. public:
  132. virtual int connect(const char *host, uint16_t port) {
  133. TINY_GSM_YIELD();
  134. rx.clear();
  135. sock_connected = at->modemConnect(host, port, mux, true);
  136. return sock_connected;
  137. }
  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 (!testAT()) {
  153. return false;
  154. }
  155. sendAT(GF("E0")); // Echo Off
  156. if (waitResponse() != 1) {
  157. return false;
  158. }
  159. return true;
  160. }
  161. void setBaud(unsigned long baud) {
  162. sendAT(GF("+IPR="), baud);
  163. }
  164. bool testAT(unsigned long timeout = 10000L) {
  165. for (unsigned long start = millis(); millis() - start < timeout; ) {
  166. sendAT(GF(""));
  167. if (waitResponse(200) == 1) {
  168. delay(100);
  169. return true;
  170. }
  171. delay(100);
  172. }
  173. return false;
  174. }
  175. void maintain() {
  176. waitResponse(10, NULL, NULL);
  177. }
  178. bool factoryDefault() {
  179. sendAT(GF("+RESTORE"));
  180. return waitResponse() == 1;
  181. }
  182. String getModemInfo() {
  183. sendAT(GF("+GMR"));
  184. String res;
  185. if (waitResponse(1000L, res) != 1) {
  186. return "";
  187. }
  188. res.replace(GSM_NL "OK" GSM_NL, "");
  189. res.replace(GSM_NL, " ");
  190. res.trim();
  191. return res;
  192. }
  193. bool hasSSL() {
  194. return true;
  195. }
  196. /*
  197. * Power functions
  198. */
  199. bool restart() {
  200. if (!testAT()) {
  201. return false;
  202. }
  203. sendAT(GF("+RST"));
  204. if (waitResponse(10000L) != 1) {
  205. return false;
  206. }
  207. if (waitResponse(10000L, GF(GSM_NL "ready" GSM_NL)) != 1) {
  208. return false;
  209. }
  210. delay(500);
  211. return init();
  212. }
  213. /*
  214. * Generic network functions
  215. */
  216. int getSignalQuality() {
  217. sendAT(GF("+CWJAP_CUR?"));
  218. int res1 = waitResponse(GF("No AP"), GF("+CWJAP_CUR:"));
  219. if (res1 != 2) {
  220. waitResponse();
  221. return 0;
  222. }
  223. streamSkipUntil(','); // Skip SSID
  224. streamSkipUntil(','); // Skip BSSID/MAC address
  225. streamSkipUntil(','); // Skip Chanel number
  226. int res2 = stream.parseInt(); // Read RSSI
  227. waitResponse(); // Returns an OK after the value
  228. return res2;
  229. }
  230. bool isNetworkConnected() {
  231. sendAT(GF("+CIPSTATUS"));
  232. int res1 = waitResponse(3000, GF("STATUS:"));
  233. int res2 = 0;
  234. if (res1 == 1) {
  235. res2 = waitResponse(GFP(GSM_ERROR), GF("2"), GF("3"), GF("4"), GF("5"));
  236. }
  237. // <stat> status of ESP8266 station interface
  238. // 2 : ESP8266 station connected to an AP and has obtained IP
  239. // 3 : ESP8266 station created a TCP or UDP transmission
  240. // 4 : the TCP or UDP transmission of ESP8266 station disconnected
  241. // 5 : ESP8266 station did NOT connect to an AP
  242. waitResponse(); // Returns an OK after the status
  243. if (res2 == 2 || res2 == 3) return true;
  244. else return false;
  245. }
  246. bool waitForNetwork(unsigned long timeout = 60000L) {
  247. for (unsigned long start = millis(); millis() - start < timeout; ) {
  248. sendAT(GF("+CIPSTATUS"));
  249. int res1 = waitResponse(3000, GF("busy p..."), GF("STATUS:"));
  250. if (res1 == 2) {
  251. int res2 = waitResponse(GFP(GSM_ERROR), GF("2"), GF("3"), GF("4"), GF("5"));
  252. if (res2 == 2 || res2 == 3) {
  253. waitResponse();
  254. return true;
  255. }
  256. }
  257. delay(250);
  258. }
  259. return false;
  260. }
  261. /*
  262. * WiFi functions
  263. */
  264. bool networkConnect(const char* ssid, const char* pwd) {
  265. sendAT(GF("+CIPMUX=1"));
  266. if (waitResponse() != 1) {
  267. return false;
  268. }
  269. sendAT(GF("+CWMODE_CUR=1"));
  270. if (waitResponse() != 1) {
  271. return false;
  272. }
  273. sendAT(GF("+CWJAP_CUR=\""), ssid, GF("\",\""), pwd, GF("\""));
  274. if (waitResponse(30000L, GFP(GSM_OK), GF(GSM_NL "FAIL" GSM_NL)) != 1) {
  275. return false;
  276. }
  277. return true;
  278. }
  279. bool networkDisconnect() {
  280. sendAT(GF("+CWQAP"));
  281. bool retVal = waitResponse(10000L) == 1;
  282. waitResponse(GF("WIFI DISCONNECT"));
  283. return retVal;
  284. }
  285. String getLocalIP() {
  286. sendAT(GF("+CIPSTA_CUR??"));
  287. int res1 = waitResponse(GF("ERROR"), GF("+CWJAP_CUR:"));
  288. if (res1 != 2) {
  289. return "";
  290. }
  291. String res2 = stream.readStringUntil('"');
  292. waitResponse();
  293. return res2;
  294. }
  295. IPAddress localIP() {
  296. return TinyGsmIpFromString(getLocalIP());
  297. }
  298. protected:
  299. bool modemConnect(const char* host, uint16_t port, uint8_t mux, bool ssl = false) {
  300. if (ssl) {
  301. sendAT(GF("+CIPSSLSIZE=4096"));
  302. waitResponse();
  303. }
  304. sendAT(GF("+CIPSTART="), mux, ',', ssl ? GF("\"SSL") : GF("\"TCP"), GF("\",\""), host, GF("\","), port, GF(","), TINY_GSM_TCP_KEEP_ALIVE);
  305. // TODO: Check mux
  306. int rsp = waitResponse(75000L,
  307. GFP(GSM_OK),
  308. GFP(GSM_ERROR),
  309. GF("ALREADY CONNECT"));
  310. // if (rsp == 3) waitResponse(); // May return "ERROR" after the "ALREADY CONNECT"
  311. return (1 == rsp);
  312. }
  313. int modemSend(const void* buff, size_t len, uint8_t mux) {
  314. sendAT(GF("+CIPSEND="), mux, ',', len);
  315. if (waitResponse(GF(">")) != 1) {
  316. return -1;
  317. }
  318. stream.write((uint8_t*)buff, len);
  319. stream.flush();
  320. if (waitResponse(10000L, GF(GSM_NL "SEND OK" GSM_NL)) != 1) {
  321. return -1;
  322. }
  323. return len;
  324. }
  325. bool modemGetConnected(uint8_t mux) {
  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
  336. // 5 : ESP8266 station did NOT connect to an AP
  337. waitResponse(); // Returns an OK after the status
  338. if (res2 == 2 || res2 == 3) 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) {
  353. const unsigned long timeout = 1000L;
  354. unsigned long startMillis = millis();
  355. while (millis() - startMillis < timeout) {
  356. while (millis() - startMillis < timeout && !stream.available()) {
  357. TINY_GSM_YIELD();
  358. }
  359. if (stream.read() == c)
  360. return true;
  361. }
  362. return false;
  363. }
  364. template<typename... Args>
  365. void sendAT(Args... cmd) {
  366. streamWrite("AT", cmd..., GSM_NL);
  367. stream.flush();
  368. TINY_GSM_YIELD();
  369. //DBG("### AT:", cmd...);
  370. }
  371. // TODO: Optimize this!
  372. uint8_t waitResponse(uint32_t timeout, String& data,
  373. GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  374. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  375. {
  376. /*String r1s(r1); r1s.trim();
  377. String r2s(r2); r2s.trim();
  378. String r3s(r3); r3s.trim();
  379. String r4s(r4); r4s.trim();
  380. String r5s(r5); r5s.trim();
  381. DBG("### ..:", r1s, ",", r2s, ",", r3s, ",", r4s, ",", r5s);*/
  382. data.reserve(64);
  383. int index = 0;
  384. unsigned long startMillis = millis();
  385. do {
  386. TINY_GSM_YIELD();
  387. while (stream.available() > 0) {
  388. int a = stream.read();
  389. if (a <= 0) continue; // Skip 0x00 bytes, just in case
  390. data += (char)a;
  391. if (r1 && data.endsWith(r1)) {
  392. index = 1;
  393. goto finish;
  394. } else if (r2 && data.endsWith(r2)) {
  395. index = 2;
  396. goto finish;
  397. } else if (r3 && data.endsWith(r3)) {
  398. index = 3;
  399. goto finish;
  400. } else if (r4 && data.endsWith(r4)) {
  401. index = 4;
  402. goto finish;
  403. } else if (r5 && data.endsWith(r5)) {
  404. index = 5;
  405. goto finish;
  406. } else if (data.endsWith(GF(GSM_NL "+IPD,"))) {
  407. int mux = stream.readStringUntil(',').toInt();
  408. int len = stream.readStringUntil(':').toInt();
  409. int len_orig = len;
  410. if (len > sockets[mux]->rx.free()) {
  411. DBG("### Buffer overflow: ", len, "->", sockets[mux]->rx.free());
  412. } else {
  413. DBG("### Got: ", len, "->", sockets[mux]->rx.free());
  414. }
  415. while (len--) {
  416. while (!stream.available()) { TINY_GSM_YIELD(); }
  417. sockets[mux]->rx.put(stream.read());
  418. }
  419. if (len_orig > sockets[mux]->available()) { // TODO
  420. DBG("### Fewer characters received than expected: ", sockets[mux]->available(), " vs ", len_orig);
  421. }
  422. data = "";
  423. } else if (data.endsWith(GF("CLOSED"))) {
  424. int muxStart = max(0,data.lastIndexOf(GSM_NL, data.length()-8));
  425. int coma = data.indexOf(',', muxStart);
  426. int mux = data.substring(muxStart, coma).toInt();
  427. if (mux >= 0 && mux < TINY_GSM_MUX_COUNT && sockets[mux]) {
  428. sockets[mux]->sock_connected = false;
  429. }
  430. data = "";
  431. DBG("### Closed: ", mux);
  432. }
  433. }
  434. } while (millis() - startMillis < timeout);
  435. finish:
  436. if (!index) {
  437. data.trim();
  438. if (data.length()) {
  439. DBG("### Unhandled:", data);
  440. }
  441. data = "";
  442. }
  443. return index;
  444. }
  445. uint8_t waitResponse(uint32_t timeout,
  446. GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  447. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  448. {
  449. String data;
  450. return waitResponse(timeout, data, r1, r2, r3, r4, r5);
  451. }
  452. uint8_t waitResponse(GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  453. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  454. {
  455. return waitResponse(1000, r1, r2, r3, r4, r5);
  456. }
  457. protected:
  458. Stream& stream;
  459. GsmClient* sockets[TINY_GSM_MUX_COUNT];
  460. };
  461. #endif