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.

500 lines
12 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
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
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. //#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 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()) {
  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"));
  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. //while (stream.available()) {
  176. waitResponse(10, NULL, NULL);
  177. //}
  178. }
  179. bool factoryDefault() {
  180. sendAT(GF("+RESTORE"));
  181. return waitResponse() == 1;
  182. }
  183. String getModemInfo() {
  184. sendAT(GF("+GMR"));
  185. String res;
  186. if (waitResponse(1000L, res) != 1) {
  187. return "";
  188. }
  189. res.replace(GSM_NL "OK" GSM_NL, "");
  190. res.replace(GSM_NL, " ");
  191. res.trim();
  192. return res;
  193. }
  194. bool hasSSL() {
  195. return true;
  196. }
  197. /*
  198. * Power functions
  199. */
  200. bool restart() {
  201. if (!testAT()) {
  202. return false;
  203. }
  204. sendAT(GF("+RST"));
  205. if (waitResponse(10000L) != 1) {
  206. return false;
  207. }
  208. if (waitResponse(10000L, GF(GSM_NL "ready" GSM_NL)) != 1) {
  209. return false;
  210. }
  211. delay(500);
  212. return init();
  213. }
  214. /*
  215. * Generic network functions
  216. */
  217. int getSignalQuality() {
  218. sendAT(GF("+CWJAP_CUR?"));
  219. int res1 = waitResponse(GF("No AP"), GF("+CWJAP_CUR:"));
  220. if (res1 != 2) {
  221. waitResponse();
  222. return 0;
  223. }
  224. streamSkipUntil(','); // Skip SSID
  225. streamSkipUntil(','); // Skip BSSID/MAC address
  226. streamSkipUntil(','); // Skip Chanel number
  227. int res2 = stream.parseInt(); // Read RSSI
  228. DBG(res2);
  229. waitResponse();
  230. return res2;
  231. }
  232. bool isNetworkConnected() {
  233. return true; // TODO
  234. }
  235. bool waitForNetwork(unsigned long timeout = 60000L) {
  236. for (unsigned long start = millis(); millis() - start < timeout; ) {
  237. sendAT(GF("+CIPSTATUS"));
  238. int res1 = waitResponse(3000, GF("busy p..."), GF("STATUS:"));
  239. if (res1 == 2) {
  240. int res2 = waitResponse(GFP(GSM_ERROR), GF("2"), GF("3"), GF("4"), GF("5"));
  241. if (res2 == 2 || res2 == 3 || res2 == 4) return true;
  242. }
  243. // <stat> status of ESP8266 station interface
  244. // 2 : ESP8266 station connected to an AP and has obtained IP
  245. // 3 : ESP8266 station created a TCP or UDP transmission
  246. // 4 : the TCP or UDP transmission of ESP8266 station disconnected (but AP is connected)
  247. // 5 : ESP8266 station did NOT connect to an AP
  248. delay(1000);
  249. }
  250. return false;
  251. }
  252. /*
  253. * WiFi functions
  254. */
  255. bool networkConnect(const char* ssid, const char* pwd) {
  256. sendAT(GF("+CIPMUX=1"));
  257. if (waitResponse() != 1) {
  258. return false;
  259. }
  260. sendAT(GF("+CWMODE_CUR=1"));
  261. if (waitResponse() != 1) {
  262. return false;
  263. }
  264. sendAT(GF("+CWJAP_CUR=\""), ssid, GF("\",\""), pwd, GF("\""));
  265. if (waitResponse(30000L, GFP(GSM_OK), GF(GSM_NL "FAIL" GSM_NL)) != 1) {
  266. return false;
  267. }
  268. return true;
  269. }
  270. bool networkDisconnect() {
  271. sendAT(GF("+CWQAP"));
  272. return waitResponse(10000L) == 1;
  273. }
  274. String getLocalIP() {
  275. sendAT(GF("+CIPSTA_CUR??"));
  276. int res1 = waitResponse(GF("ERROR"), GF("+CWJAP_CUR:"));
  277. if (res1 != 2) {
  278. return "";
  279. }
  280. String res2 = stream.readStringUntil('"');
  281. DBG(res2);
  282. waitResponse();
  283. return res2;
  284. }
  285. IPAddress localIP() {
  286. return TinyGsmIpFromString(getLocalIP());
  287. }
  288. protected:
  289. bool modemConnect(const char* host, uint16_t port, uint8_t mux, bool ssl = false) {
  290. if (ssl) {
  291. sendAT(GF("+CIPSSLSIZE=4096"));
  292. waitResponse();
  293. }
  294. sendAT(GF("+CIPSTART="), mux, ',', ssl ? GF("\"SSL") : GF("\"TCP"), GF("\",\""), host, GF("\","), port, GF(","), TINY_GSM_TCP_KEEP_ALIVE);
  295. int rsp = waitResponse(75000L,
  296. GFP(GSM_OK),
  297. GFP(GSM_ERROR),
  298. GF(GSM_NL "ALREADY CONNECT" GSM_NL));
  299. waitResponse(100, GF("1,CONNECT")); // TODO
  300. return (1 == rsp);
  301. }
  302. int modemSend(const void* buff, size_t len, uint8_t mux) {
  303. sendAT(GF("+CIPSEND="), mux, ',', len);
  304. if (waitResponse(GF(">")) != 1) {
  305. return -1;
  306. }
  307. stream.write((uint8_t*)buff, len);
  308. stream.flush();
  309. if (waitResponse(GF(GSM_NL "SEND OK" GSM_NL)) != 1) {
  310. return -1;
  311. }
  312. return len;
  313. }
  314. bool modemGetConnected(uint8_t mux) {
  315. sendAT(GF("+CIPSTATUS="), mux);
  316. int res = waitResponse(GF(",\"CONNECTED\""), GF(",\"CLOSED\""), GF(",\"CLOSING\""), GF(",\"INITIAL\""));
  317. waitResponse();
  318. return 1 == res;
  319. }
  320. public:
  321. /* Utilities */
  322. template<typename T>
  323. void streamWrite(T last) {
  324. stream.print(last);
  325. }
  326. template<typename T, typename... Args>
  327. void streamWrite(T head, Args... tail) {
  328. stream.print(head);
  329. streamWrite(tail...);
  330. }
  331. bool streamSkipUntil(char c) { //TODO: timeout
  332. while (true) {
  333. while (!stream.available()) { TINY_GSM_YIELD(); }
  334. if (stream.read() == c)
  335. return true;
  336. }
  337. return false;
  338. }
  339. template<typename... Args>
  340. void sendAT(Args... cmd) {
  341. streamWrite("AT", cmd..., GSM_NL);
  342. stream.flush();
  343. TINY_GSM_YIELD();
  344. //DBG("### AT:", cmd...);
  345. }
  346. // TODO: Optimize this!
  347. uint8_t waitResponse(uint32_t timeout, String& data,
  348. GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  349. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  350. {
  351. /*String r1s(r1); r1s.trim();
  352. String r2s(r2); r2s.trim();
  353. String r3s(r3); r3s.trim();
  354. String r4s(r4); r4s.trim();
  355. String r5s(r5); r5s.trim();
  356. DBG("### ..:", r1s, ",", r2s, ",", r3s, ",", r4s, ",", r5s);*/
  357. data.reserve(64);
  358. int index = 0;
  359. unsigned long startMillis = millis();
  360. do {
  361. TINY_GSM_YIELD();
  362. while (stream.available() > 0) {
  363. int a = stream.read();
  364. if (a <= 0) continue; // Skip 0x00 bytes, just in case
  365. data += (char)a;
  366. if (r1 && data.endsWith(r1)) {
  367. index = 1;
  368. goto finish;
  369. } else if (r2 && data.endsWith(r2)) {
  370. index = 2;
  371. goto finish;
  372. } else if (r3 && data.endsWith(r3)) {
  373. index = 3;
  374. goto finish;
  375. } else if (r4 && data.endsWith(r4)) {
  376. index = 4;
  377. goto finish;
  378. } else if (r5 && data.endsWith(r5)) {
  379. index = 5;
  380. goto finish;
  381. } else if (data.endsWith(GF(GSM_NL "+IPD,"))) {
  382. int mux = stream.readStringUntil(',').toInt();
  383. int len = stream.readStringUntil(':').toInt();
  384. int len_orig = len;
  385. if (len > sockets[mux]->rx.free()) {
  386. DBG("### Buffer overflow: ", len, "->", sockets[mux]->rx.free());
  387. } else {
  388. DBG("### Got: ", len, "->", sockets[mux]->rx.free());
  389. }
  390. while (len--) {
  391. while (!stream.available()) { TINY_GSM_YIELD(); }
  392. sockets[mux]->rx.put(stream.read());
  393. }
  394. if (len_orig > sockets[mux]->available()) { // TODO
  395. DBG(GSM_NL, "### Fewer characters received than expected: ", sockets[mux]->available(), " vs ", len_orig);
  396. }
  397. data = "";
  398. return index;
  399. } else if (data.endsWith(GF(GSM_NL "1,CLOSED" GSM_NL))) { //TODO: use mux
  400. sockets[1]->sock_connected = false;
  401. }
  402. }
  403. } while (millis() - startMillis < timeout);
  404. finish:
  405. if (!index) {
  406. data.trim();
  407. if (data.length()) {
  408. DBG("### Unhandled:", data);
  409. }
  410. data = "";
  411. }
  412. return index;
  413. }
  414. uint8_t waitResponse(uint32_t timeout,
  415. GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  416. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  417. {
  418. String data;
  419. return waitResponse(timeout, data, r1, r2, r3, r4, r5);
  420. }
  421. uint8_t waitResponse(GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  422. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  423. {
  424. return waitResponse(1000, r1, r2, r3, r4, r5);
  425. }
  426. protected:
  427. Stream& stream;
  428. GsmClient* sockets[TINY_GSM_MUX_COUNT];
  429. };
  430. #endif