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.

604 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
  1. /**
  2. * @file TinyGsmClientM590.h
  3. * @author Volodymyr Shymanskyy
  4. * @license LGPL-3.0
  5. * @copyright Copyright (c) 2016 Volodymyr Shymanskyy
  6. * @date Nov 2016
  7. */
  8. #ifndef TinyGsmClientM590_h
  9. #define TinyGsmClientM590_h
  10. //#define TINY_GSM_DEBUG Serial
  11. #if !defined(TINY_GSM_RX_BUFFER)
  12. #define TINY_GSM_RX_BUFFER 256
  13. #endif
  14. #define TINY_GSM_MUX_COUNT 2
  15. #include <TinyGsmCommon.h>
  16. #define GSM_NL "\r\n"
  17. static const char GSM_OK[] TINY_GSM_PROGMEM = "OK" GSM_NL;
  18. static const char GSM_ERROR[] TINY_GSM_PROGMEM = "ERROR" GSM_NL;
  19. enum SimStatus {
  20. SIM_ERROR = 0,
  21. SIM_READY = 1,
  22. SIM_LOCKED = 2,
  23. };
  24. enum RegStatus {
  25. REG_UNREGISTERED = 0,
  26. REG_SEARCHING = 3,
  27. REG_DENIED = 2,
  28. REG_OK_HOME = 1,
  29. REG_OK_ROAMING = 5,
  30. REG_UNKNOWN = 4,
  31. };
  32. class TinyGsm
  33. {
  34. public:
  35. TinyGsm(Stream& stream)
  36. : stream(stream)
  37. {}
  38. public:
  39. class GsmClient : public Client
  40. {
  41. friend class TinyGsm;
  42. typedef TinyGsmFifo<uint8_t, TINY_GSM_RX_BUFFER> RxFifo;
  43. public:
  44. GsmClient() {}
  45. GsmClient(TinyGsm& modem, uint8_t mux = 1) {
  46. init(&modem, mux);
  47. }
  48. bool init(TinyGsm* modem, uint8_t mux = 1) {
  49. this->at = modem;
  50. this->mux = mux;
  51. sock_connected = false;
  52. at->sockets[mux] = this;
  53. return true;
  54. }
  55. public:
  56. virtual int connect(const char *host, uint16_t port) {
  57. TINY_GSM_YIELD();
  58. rx.clear();
  59. sock_connected = at->modemConnect(host, port, mux);
  60. return sock_connected;
  61. }
  62. virtual int connect(IPAddress ip, uint16_t port) {
  63. String host; host.reserve(16);
  64. host += ip[0];
  65. host += ".";
  66. host += ip[1];
  67. host += ".";
  68. host += ip[2];
  69. host += ".";
  70. host += ip[3];
  71. return connect(host.c_str(), port);
  72. }
  73. virtual void stop() {
  74. TINY_GSM_YIELD();
  75. at->sendAT(GF("+TCPCLOSE="), mux);
  76. sock_connected = false;
  77. at->waitResponse();
  78. }
  79. virtual size_t write(const uint8_t *buf, size_t size) {
  80. TINY_GSM_YIELD();
  81. //at->maintain();
  82. return at->modemSend(buf, size, mux);
  83. }
  84. virtual size_t write(uint8_t c) {
  85. return write(&c, 1);
  86. }
  87. virtual int available() {
  88. TINY_GSM_YIELD();
  89. if (!rx.size()) {
  90. at->maintain();
  91. }
  92. return rx.size();
  93. }
  94. virtual int read(uint8_t *buf, size_t size) {
  95. TINY_GSM_YIELD();
  96. size_t cnt = 0;
  97. while (cnt < size) {
  98. size_t chunk = TinyGsmMin(size-cnt, rx.size());
  99. if (chunk > 0) {
  100. rx.get(buf, chunk);
  101. buf += chunk;
  102. cnt += chunk;
  103. continue;
  104. }
  105. // TODO: Read directly into user buffer?
  106. if (!rx.size()) {
  107. at->maintain();
  108. //break;
  109. }
  110. }
  111. return cnt;
  112. }
  113. virtual int read() {
  114. uint8_t c;
  115. if (read(&c, 1) == 1) {
  116. return c;
  117. }
  118. return -1;
  119. }
  120. virtual int peek() { return -1; } //TODO
  121. virtual void flush() { at->stream.flush(); }
  122. virtual uint8_t connected() {
  123. if (available()) {
  124. return true;
  125. }
  126. return sock_connected;
  127. }
  128. virtual operator bool() { return connected(); }
  129. private:
  130. TinyGsm* at;
  131. uint8_t mux;
  132. bool sock_connected;
  133. RxFifo rx;
  134. };
  135. public:
  136. /*
  137. * Basic functions
  138. */
  139. bool begin() {
  140. return init();
  141. }
  142. bool init() {
  143. if (!autoBaud()) {
  144. return false;
  145. }
  146. sendAT(GF("&FZE0")); // Factory + Reset + Echo Off
  147. if (waitResponse() != 1) {
  148. return false;
  149. }
  150. #ifdef TINY_GSM_DEBUG
  151. sendAT(GF("+CMEE=2"));
  152. waitResponse();
  153. #endif
  154. getSimStatus();
  155. return true;
  156. }
  157. bool autoBaud(unsigned long timeout = 10000L) {
  158. for (unsigned long start = millis(); millis() - start < timeout; ) {
  159. sendAT(GF("E0"));
  160. if (waitResponse(200) == 1) {
  161. delay(100);
  162. return true;
  163. }
  164. delay(100);
  165. }
  166. return false;
  167. }
  168. void maintain() {
  169. //while (stream.available()) {
  170. waitResponse(10, NULL, NULL);
  171. //}
  172. }
  173. bool factoryDefault() {
  174. sendAT(GF("&FZE0&W")); // Factory + Reset + Echo Off + Write
  175. waitResponse();
  176. sendAT(GF("+ICF=3,1")); // 8 data 0 parity 1 stop
  177. waitResponse();
  178. sendAT(GF("+enpwrsave=0")); // Disable PWR save
  179. waitResponse();
  180. sendAT(GF("+XISP=0")); // Use internal stack
  181. waitResponse();
  182. sendAT(GF("&W")); // Write configuration
  183. return waitResponse() == 1;
  184. }
  185. /*
  186. * Power functions
  187. */
  188. bool restart() {
  189. if (!autoBaud()) {
  190. return false;
  191. }
  192. sendAT(GF("+CFUN=15"));
  193. if (waitResponse(10000L) != 1) {
  194. return false;
  195. }
  196. //MODEM:STARTUP
  197. waitResponse(60000L, GF(GSM_NL "+PBREADY" GSM_NL));
  198. return init();
  199. }
  200. /*
  201. * SIM card functions
  202. */
  203. bool simUnlock(const char *pin) {
  204. sendAT(GF("+CPIN=\""), pin, GF("\""));
  205. return waitResponse() == 1;
  206. }
  207. String getSimCCID() {
  208. sendAT(GF("+CCID"));
  209. if (waitResponse(GF(GSM_NL "+CCID:")) != 1) {
  210. return "";
  211. }
  212. String res = stream.readStringUntil('\n');
  213. waitResponse();
  214. res.trim();
  215. return res;
  216. }
  217. String getIMEI() {
  218. sendAT(GF("+GSN"));
  219. if (waitResponse(GF(GSM_NL)) != 1) {
  220. return "";
  221. }
  222. String res = stream.readStringUntil('\n');
  223. waitResponse();
  224. res.trim();
  225. return res;
  226. }
  227. SimStatus getSimStatus(unsigned long timeout = 10000L) {
  228. for (unsigned long start = millis(); millis() - start < timeout; ) {
  229. sendAT(GF("+CPIN?"));
  230. if (waitResponse(GF(GSM_NL "+CPIN:")) != 1) {
  231. delay(1000);
  232. continue;
  233. }
  234. int status = waitResponse(GF("READY"), GF("SIM PIN"), GF("SIM PUK"));
  235. waitResponse();
  236. switch (status) {
  237. case 2:
  238. case 3: return SIM_LOCKED;
  239. case 1: return SIM_READY;
  240. default: return SIM_ERROR;
  241. }
  242. }
  243. return SIM_ERROR;
  244. }
  245. RegStatus getRegistrationStatus() {
  246. sendAT(GF("+CREG?"));
  247. if (waitResponse(GF(GSM_NL "+CREG:")) != 1) {
  248. return REG_UNKNOWN;
  249. }
  250. streamSkipUntil(','); // Skip format (0)
  251. int status = stream.readStringUntil('\n').toInt();
  252. waitResponse();
  253. return (RegStatus)status;
  254. }
  255. String getOperator() {
  256. sendAT(GF("+COPS?"));
  257. if (waitResponse(GF(GSM_NL "+COPS:")) != 1) {
  258. return "";
  259. }
  260. streamSkipUntil('"'); // Skip mode and format
  261. String res = stream.readStringUntil('"');
  262. waitResponse();
  263. return res;
  264. }
  265. /*
  266. * Generic network functions
  267. */
  268. int getSignalQuality() {
  269. sendAT(GF("+CSQ"));
  270. if (waitResponse(GF(GSM_NL "+CSQ:")) != 1) {
  271. return 99;
  272. }
  273. int res = stream.readStringUntil(',').toInt();
  274. waitResponse();
  275. return res;
  276. }
  277. bool waitForNetwork(unsigned long timeout = 60000L) {
  278. for (unsigned long start = millis(); millis() - start < timeout; ) {
  279. RegStatus s = getRegistrationStatus();
  280. if (s == REG_OK_HOME || s == REG_OK_ROAMING) {
  281. return true;
  282. }
  283. delay(1000);
  284. }
  285. return false;
  286. }
  287. /*
  288. * GPRS functions
  289. */
  290. bool gprsConnect(const char* apn, const char* user, const char* pwd) {
  291. gprsDisconnect();
  292. sendAT(GF("+XISP=0"));
  293. waitResponse();
  294. sendAT(GF("+CGDCONT=1,\"IP\",\""), apn, '"');
  295. waitResponse();
  296. if (!user) user = "";
  297. if (!pwd) pwd = "";
  298. sendAT(GF("+XGAUTH=1,1,\""), user, GF("\",\""), pwd, GF("\""));
  299. waitResponse();
  300. sendAT(GF("+XIIC=1"));
  301. waitResponse();
  302. delay(10000L); // TODO
  303. sendAT(GF("+XIIC?"));
  304. waitResponse();
  305. /*sendAT(GF("+DNSSERVER=1,8.8.8.8"));
  306. waitResponse();
  307. sendAT(GF("+DNSSERVER=2,8.8.4.4"));
  308. if (waitResponse() != 1) {
  309. return false;
  310. }*/
  311. return true;
  312. }
  313. bool gprsDisconnect() {
  314. sendAT(GF("+XIIC=0"));
  315. return waitResponse(60000L) == 1;
  316. }
  317. /*
  318. * Phone Call functions
  319. */
  320. bool callAnswer() {
  321. sendAT(GF("A"));
  322. return waitResponse() == 1;
  323. }
  324. bool callNumber(const String& number) {
  325. sendAT(GF("D"), number);
  326. return waitResponse() == 1;
  327. }
  328. bool callHangup(const String& number) {
  329. sendAT(GF("H"), number);
  330. return waitResponse() == 1;
  331. }
  332. /*
  333. * Messaging functions
  334. */
  335. // TODO
  336. void sendUSSD() {
  337. }
  338. bool sendSMS(const String& number, const String& text) {
  339. sendAT(GF("+CSCS=\"gsm\""));
  340. waitResponse();
  341. sendAT(GF("+CMGF=1"));
  342. waitResponse();
  343. sendAT(GF("+CMGS=\""), number, GF("\""));
  344. if (waitResponse(GF(">")) != 1) {
  345. return false;
  346. }
  347. stream.print(text);
  348. stream.write((char)0x1A);
  349. stream.flush();
  350. return waitResponse(60000L) == 1;
  351. }
  352. /*
  353. * Location functions
  354. */
  355. void getGsmLocation() {
  356. }
  357. /*
  358. * Battery functions
  359. */
  360. private:
  361. String dnsIpQuery(const char* host) {
  362. sendAT(GF("+DNS=\""), host, GF("\""));
  363. if (waitResponse(10000L, GF(GSM_NL "+DNS:")) != 1) {
  364. return "";
  365. }
  366. String res = stream.readStringUntil('\n');
  367. waitResponse(GF("+DNS:OK" GSM_NL));
  368. res.trim();
  369. return res;
  370. }
  371. int modemConnect(const char* host, uint16_t port, uint8_t mux) {
  372. for (int i=0; i<3; i++) {
  373. String ip = dnsIpQuery(host);
  374. sendAT(GF("+TCPSETUP="), mux, GF(","), ip, GF(","), port);
  375. int rsp = waitResponse(75000L,
  376. GF(",OK" GSM_NL),
  377. GF(",FAIL" GSM_NL),
  378. GF("+TCPSETUP:Error" GSM_NL));
  379. if (1 == rsp) {
  380. return true;
  381. } else if (3 == rsp) {
  382. sendAT(GF("+TCPCLOSE="), mux);
  383. waitResponse();
  384. }
  385. delay(1000);
  386. }
  387. return false;
  388. }
  389. int modemSend(const void* buff, size_t len, uint8_t mux) {
  390. sendAT(GF("+TCPSEND="), mux, ',', len);
  391. if (waitResponse(GF(">")) != 1) {
  392. return 0;
  393. }
  394. stream.write((uint8_t*)buff, len);
  395. stream.write((char)0x0D);
  396. stream.flush();
  397. if (waitResponse(30000L, GF(GSM_NL "+TCPSEND:")) != 1) {
  398. return 0;
  399. }
  400. stream.readStringUntil('\n');
  401. return len;
  402. }
  403. bool modemGetConnected(uint8_t mux) {
  404. sendAT(GF("+CIPSTATUS="), mux);
  405. int res = waitResponse(GF(",\"CONNECTED\""), GF(",\"CLOSED\""), GF(",\"CLOSING\""), GF(",\"INITIAL\""));
  406. waitResponse();
  407. return 1 == res;
  408. }
  409. /* Utilities */
  410. template<typename T>
  411. void streamWrite(T last) {
  412. stream.print(last);
  413. }
  414. template<typename T, typename... Args>
  415. void streamWrite(T head, Args... tail) {
  416. stream.print(head);
  417. streamWrite(tail...);
  418. }
  419. int streamRead() { return stream.read(); }
  420. bool streamSkipUntil(char c) { //TODO: timeout
  421. while (true) {
  422. while (!stream.available()) { TINY_GSM_YIELD(); }
  423. if (stream.read() == c)
  424. return true;
  425. }
  426. return false;
  427. }
  428. template<typename... Args>
  429. void sendAT(Args... cmd) {
  430. streamWrite("AT", cmd..., GSM_NL);
  431. stream.flush();
  432. TINY_GSM_YIELD();
  433. //DBG("### AT:", cmd...);
  434. }
  435. // TODO: Optimize this!
  436. uint8_t waitResponse(uint32_t timeout, String& data,
  437. GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  438. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  439. {
  440. /*String r1s(r1); r1s.trim();
  441. String r2s(r2); r2s.trim();
  442. String r3s(r3); r3s.trim();
  443. String r4s(r4); r4s.trim();
  444. String r5s(r5); r5s.trim();
  445. DBG("### ..:", r1s, ",", r2s, ",", r3s, ",", r4s, ",", r5s);*/
  446. data.reserve(64);
  447. int index = 0;
  448. unsigned long startMillis = millis();
  449. do {
  450. TINY_GSM_YIELD();
  451. while (stream.available() > 0) {
  452. int a = streamRead();
  453. if (a <= 0) continue; // Skip 0x00 bytes, just in case
  454. data += (char)a;
  455. if (r1 && data.endsWith(r1)) {
  456. index = 1;
  457. goto finish;
  458. } else if (r2 && data.endsWith(r2)) {
  459. index = 2;
  460. goto finish;
  461. } else if (r3 && data.endsWith(r3)) {
  462. index = 3;
  463. goto finish;
  464. } else if (r4 && data.endsWith(r4)) {
  465. index = 4;
  466. goto finish;
  467. } else if (r5 && data.endsWith(r5)) {
  468. index = 5;
  469. goto finish;
  470. } else if (data.endsWith(GF("+TCPRECV:"))) {
  471. int mux = stream.readStringUntil(',').toInt();
  472. int len = stream.readStringUntil(',').toInt();
  473. if (len > sockets[mux]->rx.free()) {
  474. DBG("### Buffer overflow: ", len, "->", sockets[mux]->rx.free());
  475. } else {
  476. DBG("### Got: ", len, "->", sockets[mux]->rx.free());
  477. }
  478. while (len--) {
  479. while (!stream.available()) { TINY_GSM_YIELD(); }
  480. sockets[mux]->rx.put(stream.read());
  481. }
  482. data = "";
  483. return index;
  484. } else if (data.endsWith(GF("+TCPCLOSE:"))) {
  485. int mux = stream.readStringUntil(',').toInt();
  486. stream.readStringUntil('\n');
  487. sockets[mux]->sock_connected = false;
  488. data = "";
  489. }
  490. }
  491. } while (millis() - startMillis < timeout);
  492. finish:
  493. if (!index) {
  494. data.trim();
  495. if (data.length()) {
  496. DBG("### Unhandled:", data);
  497. }
  498. data = "";
  499. }
  500. return index;
  501. }
  502. uint8_t waitResponse(uint32_t timeout,
  503. GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  504. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  505. {
  506. String data;
  507. return waitResponse(timeout, data, r1, r2, r3, r4, r5);
  508. }
  509. uint8_t waitResponse(GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  510. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  511. {
  512. return waitResponse(1000, r1, r2, r3, r4, r5);
  513. }
  514. private:
  515. Stream& stream;
  516. GsmClient* sockets[TINY_GSM_MUX_COUNT];
  517. };
  518. typedef TinyGsm::GsmClient TinyGsmClient;
  519. #endif