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.

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