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.

438 lines
10 KiB

  1. /**
  2. * @file TinyGsmClient.h
  3. * @author Volodymyr Shymanskyy
  4. * @license LGPL-3.0
  5. * @copyright Copyright (c) 2016 Volodymyr Shymanskyy
  6. * @date Nov 2016
  7. */
  8. #ifndef TinyGsmClient_h
  9. #define TinyGsmClient_h
  10. #if defined(SPARK) || defined(PARTICLE)
  11. #include "Particle.h"
  12. #elif defined(ARDUINO)
  13. #if ARDUINO >= 100
  14. #include "Arduino.h"
  15. #else
  16. #include "WProgram.h"
  17. #endif
  18. #endif
  19. #include <Client.h>
  20. #include <TinyGsmFifo.h>
  21. #if defined(__AVR__)
  22. #define GSM_PROGMEM PROGMEM
  23. typedef const __FlashStringHelper* GsmConstStr;
  24. #define FP(x) (reinterpret_cast<GsmConstStr>(x))
  25. #else
  26. #define GSM_PROGMEM
  27. typedef const char* GsmConstStr;
  28. #define FP(x) x
  29. #undef F
  30. #define F(x) x
  31. #endif
  32. //#define GSM_USE_HEX
  33. #define GSM_RX_BUFFER 64
  34. #define GSM_NL "\r\n"
  35. static constexpr char GSM_OK[] GSM_PROGMEM = "OK" GSM_NL;
  36. static constexpr char GSM_ERROR[] GSM_PROGMEM = "ERROR" GSM_NL;
  37. class TinyGsmClient
  38. : public Client
  39. {
  40. typedef TinyGsmFifo<uint8_t, GSM_RX_BUFFER> RxFifo;
  41. #ifdef GSM_DEBUG
  42. template<typename T>
  43. void DBG(T last) {
  44. GSM_DEBUG.println(last);
  45. }
  46. template<typename T, typename... Args>
  47. void DBG(T head, Args... tail) {
  48. GSM_DEBUG.print(head);
  49. GSM_DEBUG.print(' ');
  50. DBG(tail...);
  51. }
  52. #else
  53. #define DBG(...)
  54. #endif
  55. public:
  56. TinyGsmClient(Stream& stream, uint8_t mux = 1)
  57. : stream(stream)
  58. , mux(mux)
  59. , sock_available(0)
  60. , sock_connected(false)
  61. {}
  62. public:
  63. virtual int connect(const char *host, uint16_t port) {
  64. return modemConnect(host, port);
  65. }
  66. virtual int connect(IPAddress ip, uint16_t port) {
  67. String host; host.reserve(16);
  68. host += ip[0];
  69. host += ".";
  70. host += ip[1];
  71. host += ".";
  72. host += ip[2];
  73. host += ".";
  74. host += ip[3];
  75. return modemConnect(host.c_str(), port);
  76. }
  77. virtual void stop() {
  78. sendAT(F("+CIPCLOSE="), mux);
  79. sock_connected = false;
  80. waitResponse();
  81. }
  82. virtual size_t write(const uint8_t *buf, size_t size) {
  83. maintain();
  84. return modemSend(buf, size);
  85. }
  86. virtual size_t write(uint8_t c) {
  87. return write(&c, 1);
  88. }
  89. virtual int available() {
  90. maintain();
  91. size_t res = rx.size();
  92. if (res > 0) {
  93. return res;
  94. }
  95. return sock_available;
  96. }
  97. virtual int read(uint8_t *buf, size_t size) {
  98. maintain();
  99. size_t cnt = 0;
  100. while (cnt < size) {
  101. size_t chunk = min(size-cnt, rx.size());
  102. if (chunk > 0) {
  103. rx.get(buf, chunk);
  104. buf += chunk;
  105. cnt += chunk;
  106. } else {
  107. modemRead(rx.free()); //TODO: min(rx.free(), sock_available)
  108. }
  109. }
  110. return cnt;
  111. }
  112. virtual int read() {
  113. uint8_t c;
  114. if (read(&c, 1) == 1) {
  115. return c;
  116. }
  117. return -1;
  118. }
  119. virtual int peek() { return -1; } //TODO
  120. virtual void flush() { stream.flush(); }
  121. virtual uint8_t connected() {
  122. maintain();
  123. return sock_connected;
  124. }
  125. virtual operator bool() { return connected(); }
  126. public:
  127. bool factoryDefault() {
  128. if (!autoBaud()) {
  129. return false;
  130. }
  131. sendAT(F("&FZE0&W")); // Factory + Reset + Echo Off + Write
  132. waitResponse();
  133. sendAT(F("+IPR=0")); // Auto-baud
  134. waitResponse();
  135. sendAT(F("+IFC=0,0")); // No Flow Control
  136. waitResponse();
  137. sendAT(F("+ICF=3,3")); // 8 data 0 parity 1 stop
  138. waitResponse();
  139. sendAT(F("+CSCLK=0")); // Disable Slow Clock
  140. waitResponse();
  141. sendAT(F("&W")); // Write configuration
  142. return waitResponse() == 1;
  143. }
  144. bool restart() {
  145. autoBaud();
  146. sendAT(F("+CFUN=0"));
  147. if (waitResponse(10000L) != 1) {
  148. return false;
  149. }
  150. sendAT(F("+CFUN=1,1"));
  151. if (waitResponse(10000L) != 1) {
  152. return false;
  153. }
  154. delay(3000);
  155. autoBaud();
  156. sendAT(F("E0"));
  157. if (waitResponse() != 1) {
  158. return false;
  159. }
  160. return 1 == waitResponse(60000, F("Ready"));
  161. }
  162. bool networkConnect(const char* apn, const char* user, const char* pwd) {
  163. autoBaud();
  164. // AT+CPIN=pin-code
  165. // AT+CREG?
  166. networkDisconnect();
  167. // AT+CGATT?
  168. // AT+CGATT=1
  169. sendAT(F("+CIPMUX=1"));
  170. if (waitResponse() != 1) {
  171. return false;
  172. }
  173. sendAT(F("+CIPQSEND=1"));
  174. if (waitResponse() != 1) {
  175. return false;
  176. }
  177. sendAT(F("+CIPRXGET=1"));
  178. if (waitResponse() != 1) {
  179. return false;
  180. }
  181. sendAT(F("+CSTT=\""), apn, F("\",\""), user, F("\",\""), pwd, F("\""));
  182. if (waitResponse(60000L) != 1) {
  183. return false;
  184. }
  185. sendAT(F("+CIICR"));
  186. if (waitResponse(60000L) != 1) {
  187. return false;
  188. }
  189. sendAT(F("+CIFSR;E0"));
  190. String data;
  191. if (waitResponse(10000L, data) != 1) {
  192. data.replace(GSM_NL, "");
  193. return false;
  194. }
  195. sendAT(F("+CDNSCFG=\"8.8.8.8\",\"8.8.4.4\""));
  196. if (waitResponse() != 1) {
  197. return false;
  198. }
  199. // AT+CIPSTATUS
  200. return true;
  201. }
  202. bool networkDisconnect() {
  203. sendAT(F("+CIPSHUT"));
  204. return waitResponse(60000L) == 1;
  205. }
  206. bool autoBaud(unsigned long timeout = 10000L) {
  207. for (unsigned long start = millis(); millis() - start < timeout; ) {
  208. sendAT("");
  209. if (waitResponse() == 1) {
  210. delay(100);
  211. return true;
  212. }
  213. delay(100);
  214. }
  215. return false;
  216. }
  217. void maintain() {
  218. while (stream.available()) {
  219. waitResponse(10);
  220. }
  221. }
  222. private:
  223. int modemConnect(const char* host, uint16_t port) {
  224. sendAT(F("+CIPSTART="), mux, ',', F("\"TCP"), F("\",\""), host, F("\","), port);
  225. sock_connected = (1 == waitResponse(75000L, F("CONNECT OK" GSM_NL), F("CONNECT FAIL" GSM_NL), F("ALREADY CONNECT" GSM_NL)));
  226. return sock_connected;
  227. }
  228. int modemSend(const void* buff, size_t len) {
  229. sendAT(F("+CIPSEND="), mux, ',', len);
  230. if (waitResponse(F(">")) != 1) {
  231. return -1;
  232. }
  233. stream.write((uint8_t*)buff, len);
  234. if (waitResponse(F(GSM_NL "DATA ACCEPT:")) != 1) {
  235. return -1;
  236. }
  237. stream.readStringUntil(',');
  238. String data = stream.readStringUntil('\n');
  239. return data.toInt();
  240. }
  241. size_t modemRead(size_t size) {
  242. #ifdef GSM_USE_HEX
  243. sendAT(F("+CIPRXGET=3,"), mux, ',', size);
  244. if (waitResponse(F("+CIPRXGET: 3,")) != 1) {
  245. return 0;
  246. }
  247. #else
  248. sendAT(F("+CIPRXGET=2,"), mux, ',', size);
  249. if (waitResponse(F("+CIPRXGET: 2,")) != 1) {
  250. return 0;
  251. }
  252. #endif
  253. stream.readStringUntil(','); // Skip mux
  254. size_t len = stream.readStringUntil(',').toInt();
  255. sock_available = stream.readStringUntil('\n').toInt();
  256. for (size_t i=0; i<len; i++) {
  257. #ifdef GSM_USE_HEX
  258. while (stream.available() < 2) { delay(1); }
  259. char buf[4] = { 0, };
  260. buf[0] = stream.read();
  261. buf[1] = stream.read();
  262. char c = strtol(buf, NULL, 16);
  263. #else
  264. while (stream.available() < 1) { delay(1); }
  265. char c = stream.read();
  266. #endif
  267. rx.put(c);
  268. }
  269. waitResponse();
  270. return len;
  271. }
  272. size_t modemGetAvailable() {
  273. sendAT(F("+CIPRXGET=4,"), mux);
  274. size_t result = 0;
  275. for (byte i = 0; i < 2; i++) {
  276. int res = waitResponse(F("+CIPRXGET: 4"), FP(GSM_OK), FP(GSM_ERROR));
  277. if (res == 1) {
  278. stream.readStringUntil(',');
  279. stream.readStringUntil(',');
  280. result = stream.readStringUntil('\n').toInt();
  281. } else if (res == 2) {
  282. } else {
  283. return result;
  284. }
  285. }
  286. if (!result) {
  287. sock_connected = modemGetConnected();
  288. }
  289. return result;
  290. }
  291. bool modemGetConnected() {
  292. sendAT(F("+CIPSTATUS="), mux);
  293. int res = waitResponse(F(",\"CONNECTED\""), F(",\"CLOSED\""), F(",\"CLOSING\""), F(",\"INITIAL\""));
  294. waitResponse();
  295. return 1 == res;
  296. }
  297. /* Utilities */
  298. template<typename T>
  299. void streamWrite(T last) {
  300. stream.print(last);
  301. }
  302. template<typename T, typename... Args>
  303. void streamWrite(T head, Args... tail) {
  304. stream.print(head);
  305. streamWrite(tail...);
  306. }
  307. int streamRead() { return stream.read(); }
  308. void streamReadAll() { while(stream.available()) { stream.read(); } }
  309. template<typename... Args>
  310. void sendAT(Args... cmd) {
  311. streamWrite("AT", cmd..., GSM_NL);
  312. }
  313. // TODO: Optimize this!
  314. uint8_t waitResponse(uint32_t timeout, String& data,
  315. GsmConstStr r1=FP(GSM_OK), GsmConstStr r2=FP(GSM_ERROR),
  316. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  317. {
  318. data.reserve(64);
  319. bool gotNewData = false;
  320. int index = 0;
  321. for (unsigned long start = millis(); millis() - start < timeout; ) {
  322. while (stream.available() > 0) {
  323. int a = streamRead();
  324. if (a < 0) continue; //?
  325. data += (char)a;
  326. if (data.indexOf(r1) >= 0) {
  327. index = 1;
  328. goto finish;
  329. } else if (r2 && data.indexOf(r2) >= 0) {
  330. index = 2;
  331. goto finish;
  332. } else if (r3 && data.indexOf(r3) >= 0) {
  333. index = 3;
  334. goto finish;
  335. } else if (r4 && data.indexOf(r4) >= 0) {
  336. index = 4;
  337. goto finish;
  338. } else if (r5 && data.indexOf(r5) >= 0) {
  339. index = 5;
  340. goto finish;
  341. } else if (data.indexOf(F(GSM_NL "+CIPRXGET: 1,1" GSM_NL)) >= 0) { //TODO: use mux
  342. gotNewData = true;
  343. data = "";
  344. } else if (data.indexOf(F(GSM_NL "1, CLOSED" GSM_NL)) >= 0) { //TODO: use mux
  345. sock_connected = false;
  346. data = "";
  347. }
  348. }
  349. }
  350. finish:
  351. if (!index) {
  352. if (data.length()) {
  353. DBG("### Unhandled:", data);
  354. }
  355. data = "";
  356. }
  357. if (gotNewData) {
  358. sock_available = modemGetAvailable();
  359. }
  360. return index;
  361. }
  362. uint8_t waitResponse(uint32_t timeout,
  363. GsmConstStr r1=FP(GSM_OK), GsmConstStr r2=FP(GSM_ERROR),
  364. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  365. {
  366. String data;
  367. return waitResponse(timeout, data, r1, r2, r3, r4, r5);
  368. }
  369. uint8_t waitResponse(GsmConstStr r1=FP(GSM_OK), GsmConstStr r2=FP(GSM_ERROR),
  370. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  371. {
  372. return waitResponse(1000, r1, r2, r3, r4, r5);
  373. }
  374. private:
  375. Stream& stream;
  376. const uint8_t mux;
  377. RxFifo rx;
  378. uint16_t sock_available;
  379. bool sock_connected;
  380. };
  381. #endif