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.

524 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
  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. /*
  132. * Basic functions
  133. */
  134. bool begin() {
  135. if (!autoBaud()) {
  136. return false;
  137. }
  138. sendAT(F("&FZE0")); // Factory + Reset + Echo Off
  139. return waitResponse() == 1;
  140. // +ICCID
  141. // AT+CPIN?
  142. // AT+CPIN=pin-code
  143. // AT+CREG?
  144. }
  145. bool autoBaud(unsigned long timeout = 10000L) {
  146. for (unsigned long start = millis(); millis() - start < timeout; ) {
  147. sendAT("");
  148. if (waitResponse(200) == 1) {
  149. delay(100);
  150. return true;
  151. }
  152. delay(100);
  153. }
  154. return false;
  155. }
  156. void maintain() {
  157. while (stream.available()) {
  158. waitResponse(10);
  159. }
  160. }
  161. bool factoryDefault() {
  162. sendAT(F("&FZE0&W")); // Factory + Reset + Echo Off + Write
  163. waitResponse();
  164. sendAT(F("+IPR=0")); // Auto-baud
  165. waitResponse();
  166. sendAT(F("+IFC=0,0")); // No Flow Control
  167. waitResponse();
  168. sendAT(F("+ICF=3,3")); // 8 data 0 parity 1 stop
  169. waitResponse();
  170. sendAT(F("+CSCLK=0")); // Disable Slow Clock
  171. waitResponse();
  172. sendAT(F("&W")); // Write configuration
  173. return waitResponse() == 1;
  174. }
  175. /*
  176. * Power functions
  177. */
  178. bool restart() {
  179. return resetSoft();
  180. }
  181. bool resetSoft() {
  182. if (!autoBaud()) {
  183. return false;
  184. }
  185. sendAT(F("+CFUN=0"));
  186. if (waitResponse(10000L) != 1) {
  187. return false;
  188. }
  189. sendAT(F("+CFUN=1,1"));
  190. if (waitResponse(10000L) != 1) {
  191. return false;
  192. }
  193. delay(3000);
  194. autoBaud();
  195. sendAT(F("E0"));
  196. if (waitResponse() != 1) {
  197. return false;
  198. }
  199. return waitResponse(60000L, F("Ready" GSM_NL)) == 1;
  200. }
  201. // Reboot the module by setting the specified pin LOW, then HIGH.
  202. // (The pin should be connected to a P-MOSFET)
  203. bool resetHard(int pwrPin) {
  204. powerOff(pwrPin);
  205. delay(100);
  206. return powerOn(pwrPin);
  207. }
  208. void powerOff(int pwrPin) {
  209. pinMode(pwrPin, OUTPUT);
  210. digitalWrite(pwrPin, LOW);
  211. }
  212. bool powerOn(int pwrPin) {
  213. pinMode(pwrPin, OUTPUT);
  214. digitalWrite(pwrPin, HIGH);
  215. delay(3000);
  216. return autoBaud();
  217. }
  218. /*
  219. * GPRS functions
  220. */
  221. bool networkConnect(const char* apn, const char* user, const char* pwd) {
  222. networkDisconnect();
  223. // AT+CGATT?
  224. // AT+CGATT=1
  225. sendAT(F("+CIPMUX=1"));
  226. if (waitResponse() != 1) {
  227. return false;
  228. }
  229. sendAT(F("+CIPQSEND=1"));
  230. if (waitResponse() != 1) {
  231. return false;
  232. }
  233. sendAT(F("+CIPRXGET=1"));
  234. if (waitResponse() != 1) {
  235. return false;
  236. }
  237. sendAT(F("+CSTT=\""), apn, F("\",\""), user, F("\",\""), pwd, F("\""));
  238. if (waitResponse(60000L) != 1) {
  239. return false;
  240. }
  241. sendAT(F("+CIICR"));
  242. if (waitResponse(60000L) != 1) {
  243. return false;
  244. }
  245. sendAT(F("+CIFSR;E0"));
  246. String data;
  247. if (waitResponse(10000L, data) != 1) {
  248. data.replace(GSM_NL, "");
  249. return false;
  250. }
  251. sendAT(F("+CDNSCFG=\"8.8.8.8\",\"8.8.4.4\""));
  252. if (waitResponse() != 1) {
  253. return false;
  254. }
  255. // AT+CIPSTATUS
  256. return true;
  257. }
  258. bool networkDisconnect() {
  259. sendAT(F("+CIPSHUT"));
  260. return waitResponse(60000L) == 1;
  261. }
  262. /*
  263. * SIM card functions
  264. */
  265. bool simUnlock(const char *pin) {
  266. sendAT(F("+CPIN="), pin);
  267. return waitResponse() == 1;
  268. }
  269. bool simGetCCID() {
  270. sendAT(F("+CCID"));
  271. //TODO...
  272. }
  273. bool getIMEI() {
  274. }
  275. bool getNetworkOperator() {
  276. }
  277. /*
  278. * Phone Call functions
  279. */
  280. /*
  281. * Messaging functions
  282. */
  283. void sendUSSD() {
  284. }
  285. void sendSMS() {
  286. }
  287. /*
  288. * Location functions
  289. */
  290. void getLocation() {
  291. }
  292. private:
  293. int modemConnect(const char* host, uint16_t port) {
  294. sendAT(F("+CIPSTART="), mux, ',', F("\"TCP"), F("\",\""), host, F("\","), port);
  295. sock_connected = (1 == waitResponse(75000L, F("CONNECT OK" GSM_NL), F("CONNECT FAIL" GSM_NL), F("ALREADY CONNECT" GSM_NL)));
  296. return sock_connected;
  297. }
  298. int modemSend(const void* buff, size_t len) {
  299. sendAT(F("+CIPSEND="), mux, ',', len);
  300. if (waitResponse(F(">")) != 1) {
  301. return -1;
  302. }
  303. stream.write((uint8_t*)buff, len);
  304. if (waitResponse(F(GSM_NL "DATA ACCEPT:")) != 1) {
  305. return -1;
  306. }
  307. stream.readStringUntil(',');
  308. String data = stream.readStringUntil('\n');
  309. return data.toInt();
  310. }
  311. size_t modemRead(size_t size) {
  312. #ifdef GSM_USE_HEX
  313. sendAT(F("+CIPRXGET=3,"), mux, ',', size);
  314. if (waitResponse(F("+CIPRXGET: 3,")) != 1) {
  315. return 0;
  316. }
  317. #else
  318. sendAT(F("+CIPRXGET=2,"), mux, ',', size);
  319. if (waitResponse(F("+CIPRXGET: 2,")) != 1) {
  320. return 0;
  321. }
  322. #endif
  323. stream.readStringUntil(','); // Skip mux
  324. size_t len = stream.readStringUntil(',').toInt();
  325. sock_available = stream.readStringUntil('\n').toInt();
  326. for (size_t i=0; i<len; i++) {
  327. #ifdef GSM_USE_HEX
  328. while (stream.available() < 2) { delay(1); }
  329. char buf[4] = { 0, };
  330. buf[0] = stream.read();
  331. buf[1] = stream.read();
  332. char c = strtol(buf, NULL, 16);
  333. #else
  334. while (stream.available() < 1) { delay(1); }
  335. char c = stream.read();
  336. #endif
  337. rx.put(c);
  338. }
  339. waitResponse();
  340. return len;
  341. }
  342. size_t modemGetAvailable() {
  343. sendAT(F("+CIPRXGET=4,"), mux);
  344. size_t result = 0;
  345. for (byte i = 0; i < 2; i++) {
  346. int res = waitResponse(F("+CIPRXGET: 4"), FP(GSM_OK), FP(GSM_ERROR));
  347. if (res == 1) {
  348. stream.readStringUntil(',');
  349. stream.readStringUntil(',');
  350. result = stream.readStringUntil('\n').toInt();
  351. } else if (res == 2) {
  352. } else {
  353. return result;
  354. }
  355. }
  356. if (!result) {
  357. sock_connected = modemGetConnected();
  358. }
  359. return result;
  360. }
  361. bool modemGetConnected() {
  362. sendAT(F("+CIPSTATUS="), mux);
  363. int res = waitResponse(F(",\"CONNECTED\""), F(",\"CLOSED\""), F(",\"CLOSING\""), F(",\"INITIAL\""));
  364. waitResponse();
  365. return 1 == res;
  366. }
  367. /* Utilities */
  368. template<typename T>
  369. void streamWrite(T last) {
  370. stream.print(last);
  371. }
  372. template<typename T, typename... Args>
  373. void streamWrite(T head, Args... tail) {
  374. stream.print(head);
  375. streamWrite(tail...);
  376. }
  377. int streamRead() { return stream.read(); }
  378. void streamReadAll() { while(stream.available()) { stream.read(); } }
  379. template<typename... Args>
  380. void sendAT(Args... cmd) {
  381. streamWrite("AT", cmd..., GSM_NL);
  382. }
  383. // TODO: Optimize this!
  384. uint8_t waitResponse(uint32_t timeout, String& data,
  385. GsmConstStr r1=FP(GSM_OK), GsmConstStr r2=FP(GSM_ERROR),
  386. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  387. {
  388. data.reserve(64);
  389. bool gotNewData = false;
  390. int index = 0;
  391. for (unsigned long start = millis(); millis() - start < timeout; ) {
  392. while (stream.available() > 0) {
  393. int a = streamRead();
  394. if (a < 0) continue; //?
  395. data += (char)a;
  396. if (data.indexOf(r1) >= 0) {
  397. index = 1;
  398. goto finish;
  399. } else if (r2 && data.indexOf(r2) >= 0) {
  400. index = 2;
  401. goto finish;
  402. } else if (r3 && data.indexOf(r3) >= 0) {
  403. index = 3;
  404. goto finish;
  405. } else if (r4 && data.indexOf(r4) >= 0) {
  406. index = 4;
  407. goto finish;
  408. } else if (r5 && data.indexOf(r5) >= 0) {
  409. index = 5;
  410. goto finish;
  411. } else if (data.indexOf(F(GSM_NL "+CIPRXGET: 1,1" GSM_NL)) >= 0) { //TODO: use mux
  412. gotNewData = true;
  413. data = "";
  414. } else if (data.indexOf(F(GSM_NL "1, CLOSED" GSM_NL)) >= 0) { //TODO: use mux
  415. sock_connected = false;
  416. data = "";
  417. }
  418. }
  419. }
  420. finish:
  421. if (!index) {
  422. if (data.length()) {
  423. DBG("### Unhandled:", data);
  424. }
  425. data = "";
  426. }
  427. if (gotNewData) {
  428. sock_available = modemGetAvailable();
  429. }
  430. return index;
  431. }
  432. uint8_t waitResponse(uint32_t timeout,
  433. GsmConstStr r1=FP(GSM_OK), GsmConstStr r2=FP(GSM_ERROR),
  434. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  435. {
  436. String data;
  437. return waitResponse(timeout, data, r1, r2, r3, r4, r5);
  438. }
  439. uint8_t waitResponse(GsmConstStr r1=FP(GSM_OK), GsmConstStr r2=FP(GSM_ERROR),
  440. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  441. {
  442. return waitResponse(1000, r1, r2, r3, r4, r5);
  443. }
  444. private:
  445. Stream& stream;
  446. const uint8_t mux;
  447. RxFifo rx;
  448. uint16_t sock_available;
  449. bool sock_connected;
  450. };
  451. #endif