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.

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