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.

588 lines
13 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
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
  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 GFP(x) (reinterpret_cast<GsmConstStr>(x))
  25. #define GF(x) F(x)
  26. #else
  27. #define GSM_PROGMEM
  28. typedef const char* GsmConstStr;
  29. #define GFP(x) x
  30. #define GF(x) x
  31. #endif
  32. //#define GSM_DEBUG Serial
  33. //#define GSM_USE_HEX
  34. #if !defined(TINY_GSM_RX_BUFFER)
  35. #define TINY_GSM_RX_BUFFER 64
  36. #endif
  37. #define GSM_NL "\r\n"
  38. static const char GSM_OK[] GSM_PROGMEM = "OK" GSM_NL;
  39. static const char GSM_ERROR[] GSM_PROGMEM = "ERROR" GSM_NL;
  40. enum SimStatus {
  41. SIM_ERROR = 0,
  42. SIM_READY = 1,
  43. SIM_LOCKED = 2,
  44. };
  45. enum RegStatus {
  46. REG_UNREGISTERED = 0,
  47. REG_SEARCHING = 2,
  48. REG_DENIED = 3,
  49. REG_OK_HOME = 1,
  50. REG_OK_ROAMING = 5,
  51. REG_UNKNOWN = 4,
  52. };
  53. class TinyGsmClient
  54. : public Client
  55. {
  56. typedef TinyGsmFifo<uint8_t, TINY_GSM_RX_BUFFER> RxFifo;
  57. #ifdef GSM_DEBUG
  58. template<typename T>
  59. void DBG(T last) {
  60. GSM_DEBUG.println(last);
  61. }
  62. template<typename T, typename... Args>
  63. void DBG(T head, Args... tail) {
  64. GSM_DEBUG.print(head);
  65. GSM_DEBUG.print(' ');
  66. DBG(tail...);
  67. }
  68. #else
  69. #define DBG(...)
  70. #endif
  71. public:
  72. TinyGsmClient(Stream& stream, uint8_t mux = 1)
  73. : stream(stream)
  74. , mux(mux)
  75. , sock_available(0)
  76. , sock_connected(false)
  77. {}
  78. public:
  79. virtual int connect(const char *host, uint16_t port) {
  80. return modemConnect(host, port);
  81. }
  82. virtual int connect(IPAddress ip, uint16_t port) {
  83. String host; host.reserve(16);
  84. host += ip[0];
  85. host += ".";
  86. host += ip[1];
  87. host += ".";
  88. host += ip[2];
  89. host += ".";
  90. host += ip[3];
  91. return modemConnect(host.c_str(), port); //TODO: c_str may be missing
  92. }
  93. virtual void stop() {
  94. sendAT(GF("+CIPCLOSE="), mux);
  95. sock_connected = false;
  96. waitResponse();
  97. }
  98. virtual size_t write(const uint8_t *buf, size_t size) {
  99. maintain();
  100. return modemSend(buf, size);
  101. }
  102. virtual size_t write(uint8_t c) {
  103. return write(&c, 1);
  104. }
  105. virtual int available() {
  106. maintain();
  107. return rx.size() + sock_available;
  108. }
  109. virtual int read(uint8_t *buf, size_t size) {
  110. maintain();
  111. size_t cnt = 0;
  112. while (cnt < size) {
  113. size_t chunk = min(size-cnt, rx.size());
  114. if (chunk > 0) {
  115. rx.get(buf, chunk);
  116. buf += chunk;
  117. cnt += chunk;
  118. continue;
  119. }
  120. // TODO: Read directly into user buffer?
  121. maintain();
  122. if (sock_available > 0) {
  123. modemRead(rx.free());
  124. } else {
  125. break;
  126. }
  127. }
  128. return cnt;
  129. }
  130. virtual int read() {
  131. uint8_t c;
  132. if (read(&c, 1) == 1) {
  133. return c;
  134. }
  135. return -1;
  136. }
  137. virtual int peek() { return -1; } //TODO
  138. virtual void flush() { stream.flush(); }
  139. virtual uint8_t connected() {
  140. maintain();
  141. return sock_connected;
  142. }
  143. virtual operator bool() { return connected(); }
  144. public:
  145. /*
  146. * Basic functions
  147. */
  148. bool begin() {
  149. if (!autoBaud()) {
  150. return false;
  151. }
  152. sendAT(GF("&FZE0")); // Factory + Reset + Echo Off
  153. if (waitResponse() != 1) {
  154. return false;
  155. }
  156. return true;
  157. }
  158. bool autoBaud(unsigned long timeout = 10000L) {
  159. for (unsigned long start = millis(); millis() - start < timeout; ) {
  160. sendAT("");
  161. if (waitResponse(200) == 1) {
  162. delay(100);
  163. return true;
  164. }
  165. delay(100);
  166. }
  167. return false;
  168. }
  169. void maintain() {
  170. while (stream.available()) {
  171. waitResponse(10);
  172. }
  173. }
  174. bool factoryDefault() {
  175. sendAT(GF("&FZE0&W")); // Factory + Reset + Echo Off + Write
  176. waitResponse();
  177. sendAT(GF("+IPR=0")); // Auto-baud
  178. waitResponse();
  179. sendAT(GF("+IFC=0,0")); // No Flow Control
  180. waitResponse();
  181. sendAT(GF("+ICF=3,3")); // 8 data 0 parity 1 stop
  182. waitResponse();
  183. sendAT(GF("+CSCLK=0")); // Disable Slow Clock
  184. waitResponse();
  185. sendAT(GF("&W")); // Write configuration
  186. return waitResponse() == 1;
  187. }
  188. /*
  189. * Power functions
  190. */
  191. bool restart() {
  192. return resetSoft();
  193. }
  194. bool resetSoft() {
  195. if (!autoBaud()) {
  196. return false;
  197. }
  198. sendAT(GF("+CFUN=0"));
  199. if (waitResponse(10000L) != 1) {
  200. return false;
  201. }
  202. sendAT(GF("+CFUN=1,1"));
  203. if (waitResponse(10000L) != 1) {
  204. return false;
  205. }
  206. delay(3000);
  207. return begin();
  208. }
  209. // Reboot the module by setting the specified pin LOW, then HIGH.
  210. // (The pin should be connected to a P-MOSFET)
  211. bool resetHard(int pwrPin) {
  212. powerOff(pwrPin);
  213. delay(100);
  214. return powerOn(pwrPin);
  215. }
  216. void powerOff(int pwrPin) {
  217. pinMode(pwrPin, OUTPUT);
  218. digitalWrite(pwrPin, LOW);
  219. }
  220. bool powerOn(int pwrPin) {
  221. pinMode(pwrPin, OUTPUT);
  222. digitalWrite(pwrPin, HIGH);
  223. delay(3000);
  224. return begin();
  225. }
  226. /*
  227. * SIM card & Networ Operator functions
  228. */
  229. bool simUnlock(const char *pin) {
  230. sendAT(GF("+CPIN="), pin);
  231. return waitResponse() == 1;
  232. }
  233. String getSimCCID() {
  234. sendAT(GF("+ICCID"));
  235. if (waitResponse(GF(GSM_NL "+ICCID: ")) != 1) {
  236. return "";
  237. }
  238. String res = stream.readStringUntil('\n');
  239. waitResponse();
  240. res.trim();
  241. return res;
  242. }
  243. SimStatus getSimStatus(unsigned long timeout = 10000L) {
  244. for (unsigned long start = millis(); millis() - start < timeout; ) {
  245. sendAT(GF("+CPIN?"));
  246. if (waitResponse(GF(GSM_NL "+CPIN: ")) != 1) {
  247. delay(1000);
  248. continue;
  249. }
  250. int status = waitResponse(GF("READY"), GF("SIM PIN"), GF("SIM PUK"), GF("NOT INSERTED"));
  251. waitResponse();
  252. switch (status) {
  253. case 2:
  254. case 3: return SIM_LOCKED;
  255. case 1: return SIM_READY;
  256. default: return SIM_ERROR;
  257. }
  258. }
  259. return 0;
  260. }
  261. RegStatus getRegistrationStatus() {
  262. sendAT(GF("+CREG?"));
  263. if (waitResponse(GF(GSM_NL "+CREG: 0,")) != 1) {
  264. return 0;
  265. }
  266. int status = stream.readStringUntil('\n').toInt();
  267. waitResponse();
  268. return (RegStatus)status;
  269. }
  270. String getOperator() {
  271. sendAT(GF("+COPS?"));
  272. if (waitResponse(GF(GSM_NL "+COPS: ")) != 1) {
  273. return "";
  274. }
  275. stream.readStringUntil('"'); // Skip mode and format
  276. String res = stream.readStringUntil('"');
  277. waitResponse();
  278. return res;
  279. }
  280. bool waitForNetwork(unsigned long timeout = 60000L) {
  281. for (unsigned long start = millis(); millis() - start < timeout; ) {
  282. RegStatus s = getRegistrationStatus();
  283. if(s == REG_OK_HOME || s == REG_OK_ROAMING) {
  284. return true;
  285. }
  286. delay(1000);
  287. }
  288. return true;
  289. }
  290. /*
  291. * GPRS functions
  292. */
  293. bool networkConnect(const char* apn, const char* user, const char* pwd) {
  294. networkDisconnect();
  295. // AT+CGATT?
  296. // AT+CGATT=1
  297. sendAT(GF("+CIPMUX=1"));
  298. if (waitResponse() != 1) {
  299. return false;
  300. }
  301. sendAT(GF("+CIPQSEND=1"));
  302. if (waitResponse() != 1) {
  303. return false;
  304. }
  305. sendAT(GF("+CIPRXGET=1"));
  306. if (waitResponse() != 1) {
  307. return false;
  308. }
  309. sendAT(GF("+CSTT=\""), apn, GF("\",\""), user, GF("\",\""), pwd, GF("\""));
  310. if (waitResponse(60000L) != 1) {
  311. return false;
  312. }
  313. sendAT(GF("+CIICR"));
  314. if (waitResponse(60000L) != 1) {
  315. return false;
  316. }
  317. sendAT(GF("+CIFSR;E0"));
  318. String data;
  319. if (waitResponse(10000L, data) != 1) {
  320. data.replace(GSM_NL, "");
  321. return false;
  322. }
  323. sendAT(GF("+CDNSCFG=\"8.8.8.8\",\"8.8.4.4\""));
  324. if (waitResponse() != 1) {
  325. return false;
  326. }
  327. return true;
  328. }
  329. bool networkDisconnect() {
  330. sendAT(GF("+CIPSHUT"));
  331. return waitResponse(60000L) == 1;
  332. }
  333. /*
  334. * Phone Call functions
  335. */
  336. /*
  337. * Messaging functions
  338. */
  339. void sendUSSD() {
  340. }
  341. void sendSMS() {
  342. }
  343. /*
  344. * Location functions
  345. */
  346. void getLocation() {
  347. }
  348. /*
  349. * Battery functions
  350. */
  351. private:
  352. int modemConnect(const char* host, uint16_t port) {
  353. sendAT(GF("+CIPSTART="), mux, ',', GF("\"TCP"), GF("\",\""), host, GF("\","), port);
  354. sock_connected = (1 == waitResponse(75000L, GF("CONNECT OK" GSM_NL), GF("CONNECT FAIL" GSM_NL), GF("ALREADY CONNECT" GSM_NL)));
  355. return sock_connected;
  356. }
  357. int modemSend(const void* buff, size_t len) {
  358. sendAT(GF("+CIPSEND="), mux, ',', len);
  359. if (waitResponse(GF(">")) != 1) {
  360. return -1;
  361. }
  362. stream.write((uint8_t*)buff, len);
  363. if (waitResponse(GF(GSM_NL "DATA ACCEPT:")) != 1) {
  364. return -1;
  365. }
  366. stream.readStringUntil(',');
  367. String data = stream.readStringUntil('\n');
  368. return data.toInt();
  369. }
  370. size_t modemRead(size_t size) {
  371. #ifdef GSM_USE_HEX
  372. sendAT(GF("+CIPRXGET=3,"), mux, ',', size);
  373. if (waitResponse(GF("+CIPRXGET: 3,")) != 1) {
  374. return 0;
  375. }
  376. #else
  377. sendAT(GF("+CIPRXGET=2,"), mux, ',', size);
  378. if (waitResponse(GF("+CIPRXGET: 2,")) != 1) {
  379. return 0;
  380. }
  381. #endif
  382. stream.readStringUntil(','); // Skip mux
  383. size_t len = stream.readStringUntil(',').toInt();
  384. sock_available = stream.readStringUntil('\n').toInt();
  385. for (size_t i=0; i<len; i++) {
  386. #ifdef GSM_USE_HEX
  387. while (stream.available() < 2) { delay(1); }
  388. char buf[4] = { 0, };
  389. buf[0] = stream.read();
  390. buf[1] = stream.read();
  391. char c = strtol(buf, NULL, 16);
  392. #else
  393. while (stream.available() < 1) { delay(1); }
  394. char c = stream.read();
  395. #endif
  396. rx.put(c);
  397. }
  398. waitResponse();
  399. return len;
  400. }
  401. size_t modemGetAvailable() {
  402. sendAT(GF("+CIPRXGET=4,"), mux);
  403. size_t result = 0;
  404. for (byte i = 0; i < 2; i++) {
  405. int res = waitResponse(GF("+CIPRXGET: 4"), GFP(GSM_OK), GFP(GSM_ERROR));
  406. if (res == 1) {
  407. stream.readStringUntil(',');
  408. stream.readStringUntil(',');
  409. result = stream.readStringUntil('\n').toInt();
  410. } else if (res == 2) {
  411. } else {
  412. return result;
  413. }
  414. }
  415. if (!result) {
  416. sock_connected = modemGetConnected();
  417. }
  418. return result;
  419. }
  420. bool modemGetConnected() {
  421. sendAT(GF("+CIPSTATUS="), mux);
  422. int res = waitResponse(GF(",\"CONNECTED\""), GF(",\"CLOSED\""), GF(",\"CLOSING\""), GF(",\"INITIAL\""));
  423. waitResponse();
  424. return 1 == res;
  425. }
  426. /* Utilities */
  427. template<typename T>
  428. void streamWrite(T last) {
  429. stream.print(last);
  430. }
  431. template<typename T, typename... Args>
  432. void streamWrite(T head, Args... tail) {
  433. stream.print(head);
  434. streamWrite(tail...);
  435. }
  436. int streamRead() { return stream.read(); }
  437. void streamReadAll() { while(stream.available()) { stream.read(); } }
  438. template<typename... Args>
  439. void sendAT(Args... cmd) {
  440. streamWrite("AT", cmd..., GSM_NL);
  441. //DBG("### AT:", cmd...);
  442. }
  443. // TODO: Optimize this!
  444. uint8_t waitResponse(uint32_t timeout, String& data,
  445. GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  446. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  447. {
  448. data.reserve(64);
  449. bool gotNewData = false;
  450. int index = 0;
  451. for (unsigned long start = millis(); millis() - start < timeout; ) {
  452. while (stream.available() > 0) {
  453. int a = streamRead();
  454. if (a <= 0) continue;
  455. data += (char)a;
  456. if (r1 && data.indexOf(r1) >= 0) {
  457. index = 1;
  458. goto finish;
  459. } else if (r2 && data.indexOf(r2) >= 0) {
  460. index = 2;
  461. goto finish;
  462. } else if (r3 && data.indexOf(r3) >= 0) {
  463. index = 3;
  464. goto finish;
  465. } else if (r4 && data.indexOf(r4) >= 0) {
  466. index = 4;
  467. goto finish;
  468. } else if (r5 && data.indexOf(r5) >= 0) {
  469. index = 5;
  470. goto finish;
  471. } else if (data.indexOf(GF(GSM_NL "+CIPRXGET: 1,1" GSM_NL)) >= 0) { //TODO: use mux
  472. gotNewData = true;
  473. data = "";
  474. } else if (data.indexOf(GF(GSM_NL "1, CLOSED" GSM_NL)) >= 0) { //TODO: use mux
  475. sock_connected = false;
  476. data = "";
  477. }
  478. }
  479. }
  480. finish:
  481. if (!index) {
  482. if (data.length()) {
  483. DBG("### Unhandled:", data);
  484. }
  485. data = "";
  486. }
  487. if (gotNewData) {
  488. sock_available = modemGetAvailable();
  489. }
  490. return index;
  491. }
  492. uint8_t waitResponse(uint32_t timeout,
  493. GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  494. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  495. {
  496. String data;
  497. return waitResponse(timeout, data, r1, r2, r3, r4, r5);
  498. }
  499. uint8_t waitResponse(GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  500. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  501. {
  502. return waitResponse(1000, r1, r2, r3, r4, r5);
  503. }
  504. private:
  505. Stream& stream;
  506. const uint8_t mux;
  507. RxFifo rx;
  508. uint16_t sock_available;
  509. bool sock_connected;
  510. };
  511. #endif