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.

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