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.

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