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.

550 lines
12 KiB

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 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 = 0) {
  45. init(&modem, mux);
  46. }
  47. bool init(TinyGsm* modem, uint8_t mux = 0) {
  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 = min(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 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. SimStatus getSimStatus(unsigned long timeout = 10000L) {
  217. for (unsigned long start = millis(); millis() - start < timeout; ) {
  218. sendAT(GF("+CPIN?"));
  219. if (waitResponse(GF(GSM_NL "+CPIN:")) != 1) {
  220. delay(1000);
  221. continue;
  222. }
  223. int status = waitResponse(GF("READY"), GF("SIM PIN"), GF("SIM PUK"));
  224. waitResponse();
  225. switch (status) {
  226. case 2:
  227. case 3: return SIM_LOCKED;
  228. case 1: return SIM_READY;
  229. default: return SIM_ERROR;
  230. }
  231. }
  232. return SIM_ERROR;
  233. }
  234. RegStatus getRegistrationStatus() {
  235. sendAT(GF("+CREG?"));
  236. if (waitResponse(GF(GSM_NL "+CREG:")) != 1) {
  237. return REG_UNKNOWN;
  238. }
  239. streamSkipUntil(','); // Skip format (0)
  240. int status = stream.readStringUntil('\n').toInt();
  241. waitResponse();
  242. return (RegStatus)status;
  243. }
  244. String getOperator() {
  245. sendAT(GF("+COPS?"));
  246. if (waitResponse(GF(GSM_NL "+COPS:")) != 1) {
  247. return "";
  248. }
  249. streamSkipUntil('"'); // Skip mode and format
  250. String res = stream.readStringUntil('"');
  251. waitResponse();
  252. return res;
  253. }
  254. bool waitForNetwork(unsigned long timeout = 60000L) {
  255. for (unsigned long start = millis(); millis() - start < timeout; ) {
  256. RegStatus s = getRegistrationStatus();
  257. if (s == REG_OK_HOME || s == REG_OK_ROAMING) {
  258. return true;
  259. } else if (s == REG_UNREGISTERED) {
  260. return false;
  261. }
  262. delay(1000);
  263. }
  264. return false;
  265. }
  266. /*
  267. * GPRS functions
  268. */
  269. bool gprsConnect(const char* apn, const char* user, const char* pwd) {
  270. gprsDisconnect();
  271. sendAT(GF("+XISP=0"));
  272. waitResponse();
  273. sendAT(GF("+CGDCONT=1,\"IP\",\""), apn, '"');
  274. waitResponse();
  275. if (!user) user = "";
  276. if (!pwd) pwd = "";
  277. sendAT(GF("+XGAUTH=1,1,\""), user, GF("\",\""), pwd, GF("\""));
  278. waitResponse();
  279. sendAT(GF("+XIIC=1"));
  280. waitResponse();
  281. delay(10000L); // TODO
  282. sendAT(GF("+XIIC?"));
  283. waitResponse();
  284. /*sendAT(GF("+DNSSERVER=1,8.8.8.8"));
  285. waitResponse();
  286. sendAT(GF("+DNSSERVER=2,8.8.4.4"));
  287. if (waitResponse() != 1) {
  288. return false;
  289. }*/
  290. return true;
  291. }
  292. bool gprsDisconnect() {
  293. sendAT(GF("+XIIC=0"));
  294. return waitResponse(60000L) == 1;
  295. }
  296. /*
  297. * Phone Call functions
  298. */
  299. /*
  300. * Messaging functions
  301. */
  302. void sendUSSD() {
  303. }
  304. void sendSMS() {
  305. }
  306. /*
  307. * Location functions
  308. */
  309. void getLocation() {
  310. }
  311. /*
  312. * Battery functions
  313. */
  314. private:
  315. String dnsIpQuery(const char* host) {
  316. sendAT(GF("+DNS=\""), host, GF("\""));
  317. if (waitResponse(10000L, GF(GSM_NL "+DNS:")) != 1) {
  318. return "";
  319. }
  320. String res = stream.readStringUntil('\n');
  321. waitResponse(GF("+DNS:OK" GSM_NL));
  322. res.trim();
  323. return res;
  324. }
  325. int modemConnect(const char* host, uint16_t port, uint8_t mux) {
  326. int rsp = 0;
  327. for (int i=0; i<3; i++) {
  328. String ip = dnsIpQuery(host);
  329. sendAT(GF("+TCPSETUP="), mux, GF(","), ip, GF(","), port);
  330. int rsp = waitResponse(75000L,
  331. GF(",OK" GSM_NL),
  332. GF(",FAIL" GSM_NL),
  333. GF("+TCPSETUP:Error" GSM_NL));
  334. if (1 == rsp) {
  335. return true;
  336. } else if (3 == rsp) {
  337. sendAT(GF("+TCPCLOSE="), mux);
  338. waitResponse();
  339. }
  340. delay(1000);
  341. }
  342. return false;
  343. }
  344. int modemSend(const void* buff, size_t len, uint8_t mux) {
  345. sendAT(GF("+TCPSEND="), mux, ',', len);
  346. if (waitResponse(GF(">")) != 1) {
  347. return 0;
  348. }
  349. stream.write((uint8_t*)buff, len);
  350. stream.write((char)0x0D);
  351. if (waitResponse(30000L, GF(GSM_NL "+TCPSEND:")) != 1) {
  352. return 0;
  353. }
  354. stream.readStringUntil('\n');
  355. return len;
  356. }
  357. bool modemGetConnected(uint8_t mux) {
  358. sendAT(GF("+CIPSTATUS="), mux);
  359. int res = waitResponse(GF(",\"CONNECTED\""), GF(",\"CLOSED\""), GF(",\"CLOSING\""), GF(",\"INITIAL\""));
  360. waitResponse();
  361. return 1 == res;
  362. }
  363. /* Utilities */
  364. template<typename T>
  365. void streamWrite(T last) {
  366. stream.print(last);
  367. }
  368. template<typename T, typename... Args>
  369. void streamWrite(T head, Args... tail) {
  370. stream.print(head);
  371. streamWrite(tail...);
  372. }
  373. int streamRead() { return stream.read(); }
  374. bool streamSkipUntil(char c) { //TODO: timeout
  375. while (true) {
  376. while (!stream.available()) {}
  377. if (stream.read() == c)
  378. return true;
  379. }
  380. return false;
  381. }
  382. template<typename... Args>
  383. void sendAT(Args... cmd) {
  384. streamWrite("AT", cmd..., GSM_NL);
  385. stream.flush();
  386. TINY_GSM_YIELD();
  387. //DBG("### AT:", cmd...);
  388. }
  389. // TODO: Optimize this!
  390. uint8_t waitResponse(uint32_t timeout, String& data,
  391. GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  392. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  393. {
  394. /*String r1s(r1); r1s.trim();
  395. String r2s(r2); r2s.trim();
  396. String r3s(r3); r3s.trim();
  397. String r4s(r4); r4s.trim();
  398. String r5s(r5); r5s.trim();
  399. DBG("### ..:", r1s, ",", r2s, ",", r3s, ",", r4s, ",", r5s);*/
  400. data.reserve(64);
  401. int index = 0;
  402. unsigned long startMillis = millis();
  403. do {
  404. TINY_GSM_YIELD();
  405. while (stream.available() > 0) {
  406. int a = streamRead();
  407. if (a <= 0) continue; // Skip 0x00 bytes, just in case
  408. data += (char)a;
  409. if (r1 && data.endsWith(r1)) {
  410. index = 1;
  411. goto finish;
  412. } else if (r2 && data.endsWith(r2)) {
  413. index = 2;
  414. goto finish;
  415. } else if (r3 && data.endsWith(r3)) {
  416. index = 3;
  417. goto finish;
  418. } else if (r4 && data.endsWith(r4)) {
  419. index = 4;
  420. goto finish;
  421. } else if (r5 && data.endsWith(r5)) {
  422. index = 5;
  423. goto finish;
  424. } else if (data.endsWith(GF("+TCPRECV:"))) {
  425. int mux = stream.readStringUntil(',').toInt();
  426. int len = stream.readStringUntil(',').toInt();
  427. if (len > sockets[mux]->rx.free()) {
  428. DBG("### Buffer overflow: ", len, "->", sockets[mux]->rx.free());
  429. } else {
  430. DBG("### Got: ", len, "->", sockets[mux]->rx.free());
  431. }
  432. while (len--) {
  433. while (!stream.available()) {}
  434. sockets[mux]->rx.put(stream.read());
  435. }
  436. data = "";
  437. return index;
  438. } else if (data.endsWith(GF("+TCPCLOSE:"))) {
  439. int mux = stream.readStringUntil(',').toInt();
  440. stream.readStringUntil('\n');
  441. sockets[mux]->sock_connected = false;
  442. data = "";
  443. }
  444. }
  445. } while (millis() - startMillis < timeout);
  446. finish:
  447. if (!index) {
  448. if (data.length()) {
  449. DBG("### Unhandled:", data);
  450. }
  451. data = "";
  452. }
  453. return index;
  454. }
  455. uint8_t waitResponse(uint32_t timeout,
  456. GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  457. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  458. {
  459. String data;
  460. return waitResponse(timeout, data, r1, r2, r3, r4, r5);
  461. }
  462. uint8_t waitResponse(GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  463. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  464. {
  465. return waitResponse(1000, r1, r2, r3, r4, r5);
  466. }
  467. private:
  468. Stream& stream;
  469. GsmClient* sockets[2];
  470. };
  471. typedef TinyGsm::GsmClient TinyGsmClient;
  472. #endif