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.

465 lines
10 KiB

8 years ago
8 years ago
8 years ago
  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 const char GSM_OK[] GSM_PROGMEM = "OK" GSM_NL;
  38. static const 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); //TODO: c_str may be missing
  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. bool simUnlock(const char *pin)
  237. {
  238. sendAT(F("+CPIN="), pin);
  239. return waitResponse() == 1;
  240. }
  241. bool simGetCCID() {
  242. sendAT(F("+CCID"));
  243. //TODO...
  244. }
  245. private:
  246. int modemConnect(const char* host, uint16_t port) {
  247. sendAT(F("+CIPSTART="), mux, ',', F("\"TCP"), F("\",\""), host, F("\","), port);
  248. sock_connected = (1 == waitResponse(75000L, F("CONNECT OK" GSM_NL), F("CONNECT FAIL" GSM_NL), F("ALREADY CONNECT" GSM_NL)));
  249. return sock_connected;
  250. }
  251. int modemSend(const void* buff, size_t len) {
  252. sendAT(F("+CIPSEND="), mux, ',', len);
  253. if (waitResponse(F(">")) != 1) {
  254. return -1;
  255. }
  256. stream.write((uint8_t*)buff, len);
  257. if (waitResponse(F(GSM_NL "DATA ACCEPT:")) != 1) {
  258. return -1;
  259. }
  260. stream.readStringUntil(',');
  261. String data = stream.readStringUntil('\n');
  262. return data.toInt();
  263. }
  264. size_t modemRead(size_t size) {
  265. #ifdef GSM_USE_HEX
  266. sendAT(F("+CIPRXGET=3,"), mux, ',', size);
  267. if (waitResponse(F("+CIPRXGET: 3,")) != 1) {
  268. return 0;
  269. }
  270. #else
  271. sendAT(F("+CIPRXGET=2,"), mux, ',', size);
  272. if (waitResponse(F("+CIPRXGET: 2,")) != 1) {
  273. return 0;
  274. }
  275. #endif
  276. stream.readStringUntil(','); // Skip mux
  277. size_t len = stream.readStringUntil(',').toInt();
  278. sock_available = stream.readStringUntil('\n').toInt();
  279. for (size_t i=0; i<len; i++) {
  280. #ifdef GSM_USE_HEX
  281. while (stream.available() < 2) { delay(1); }
  282. char buf[4] = { 0, };
  283. buf[0] = stream.read();
  284. buf[1] = stream.read();
  285. char c = strtol(buf, NULL, 16);
  286. #else
  287. while (stream.available() < 1) { delay(1); }
  288. char c = stream.read();
  289. #endif
  290. rx.put(c);
  291. }
  292. waitResponse();
  293. return len;
  294. }
  295. size_t modemGetAvailable() {
  296. sendAT(F("+CIPRXGET=4,"), mux);
  297. size_t result = 0;
  298. for (byte i = 0; i < 2; i++) {
  299. int res = waitResponse(F("+CIPRXGET: 4"), FP(GSM_OK), FP(GSM_ERROR));
  300. if (res == 1) {
  301. stream.readStringUntil(',');
  302. stream.readStringUntil(',');
  303. result = stream.readStringUntil('\n').toInt();
  304. } else if (res == 2) {
  305. } else {
  306. return result;
  307. }
  308. }
  309. if (!result) {
  310. sock_connected = modemGetConnected();
  311. }
  312. return result;
  313. }
  314. bool modemGetConnected() {
  315. sendAT(F("+CIPSTATUS="), mux);
  316. int res = waitResponse(F(",\"CONNECTED\""), F(",\"CLOSED\""), F(",\"CLOSING\""), F(",\"INITIAL\""));
  317. waitResponse();
  318. return 1 == res;
  319. }
  320. /* Utilities */
  321. template<typename T>
  322. void streamWrite(T last) {
  323. stream.print(last);
  324. }
  325. template<typename T, typename... Args>
  326. void streamWrite(T head, Args... tail) {
  327. stream.print(head);
  328. streamWrite(tail...);
  329. }
  330. int streamRead() { return stream.read(); }
  331. void streamReadAll() { while(stream.available()) { stream.read(); } }
  332. template<typename... Args>
  333. void sendAT(Args... cmd) {
  334. streamWrite("AT", cmd..., GSM_NL);
  335. }
  336. // TODO: Optimize this!
  337. uint8_t waitResponse(uint32_t timeout, String& data,
  338. GsmConstStr r1=FP(GSM_OK), GsmConstStr r2=FP(GSM_ERROR),
  339. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  340. {
  341. data.reserve(64);
  342. bool gotNewData = false;
  343. int index = 0;
  344. for (unsigned long start = millis(); millis() - start < timeout; ) {
  345. while (stream.available() > 0) {
  346. int a = streamRead();
  347. if (a < 0) continue; //?
  348. data += (char)a;
  349. if (data.indexOf(r1) >= 0) {
  350. index = 1;
  351. goto finish;
  352. } else if (r2 && data.indexOf(r2) >= 0) {
  353. index = 2;
  354. goto finish;
  355. } else if (r3 && data.indexOf(r3) >= 0) {
  356. index = 3;
  357. goto finish;
  358. } else if (r4 && data.indexOf(r4) >= 0) {
  359. index = 4;
  360. goto finish;
  361. } else if (r5 && data.indexOf(r5) >= 0) {
  362. index = 5;
  363. goto finish;
  364. } else if (data.indexOf(F(GSM_NL "+CIPRXGET: 1,1" GSM_NL)) >= 0) { //TODO: use mux
  365. gotNewData = true;
  366. data = "";
  367. } else if (data.indexOf(F(GSM_NL "1, CLOSED" GSM_NL)) >= 0) { //TODO: use mux
  368. sock_connected = false;
  369. data = "";
  370. }
  371. }
  372. }
  373. finish:
  374. if (!index) {
  375. if (data.length()) {
  376. DBG("### Unhandled:", data);
  377. }
  378. data = "";
  379. }
  380. if (gotNewData) {
  381. sock_available = modemGetAvailable();
  382. }
  383. return index;
  384. }
  385. uint8_t waitResponse(uint32_t timeout,
  386. GsmConstStr r1=FP(GSM_OK), GsmConstStr r2=FP(GSM_ERROR),
  387. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  388. {
  389. String data;
  390. return waitResponse(timeout, data, r1, r2, r3, r4, r5);
  391. }
  392. uint8_t waitResponse(GsmConstStr r1=FP(GSM_OK), GsmConstStr r2=FP(GSM_ERROR),
  393. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  394. {
  395. return waitResponse(1000, r1, r2, r3, r4, r5);
  396. }
  397. private:
  398. Stream& stream;
  399. const uint8_t mux;
  400. RxFifo rx;
  401. uint16_t sock_available;
  402. bool sock_connected;
  403. };
  404. #endif