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.

565 lines
12 KiB

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