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.

684 lines
15 KiB

7 years ago
5 years ago
7 years ago
7 years ago
7 years ago
7 years ago
5 years ago
7 years ago
7 years ago
  1. /**
  2. * @file TinyGsmClientA6.h
  3. * @author Volodymyr Shymanskyy
  4. * @license LGPL-3.0
  5. * @copyright Copyright (c) 2016 Volodymyr Shymanskyy
  6. * @date Nov 2016
  7. */
  8. #ifndef TinyGsmClientA6_h
  9. #define TinyGsmClientA6_h
  10. //#pragma message("TinyGSM: TinyGsmClientA6")
  11. //#define TINY_GSM_DEBUG Serial
  12. #if !defined(TINY_GSM_RX_BUFFER)
  13. #define TINY_GSM_RX_BUFFER 256
  14. #endif
  15. #define TINY_GSM_MUX_COUNT 8
  16. #include <TinyGsmCommon.h>
  17. #define GSM_NL "\r\n"
  18. static const char GSM_OK[] TINY_GSM_PROGMEM = "OK" GSM_NL;
  19. static const char GSM_ERROR[] TINY_GSM_PROGMEM = "ERROR" GSM_NL;
  20. enum SimStatus {
  21. SIM_ERROR = 0,
  22. SIM_READY = 1,
  23. SIM_LOCKED = 2,
  24. };
  25. enum RegStatus {
  26. REG_UNREGISTERED = 0,
  27. REG_SEARCHING = 2,
  28. REG_DENIED = 3,
  29. REG_OK_HOME = 1,
  30. REG_OK_ROAMING = 5,
  31. REG_UNKNOWN = 4,
  32. };
  33. class TinyGsmA6
  34. {
  35. public:
  36. class GsmClient : public Client
  37. {
  38. friend class TinyGsmA6;
  39. typedef TinyGsmFifo<uint8_t, TINY_GSM_RX_BUFFER> RxFifo;
  40. public:
  41. GsmClient() {}
  42. GsmClient(TinyGsmA6& modem) {
  43. init(&modem);
  44. }
  45. bool init(TinyGsmA6* modem) {
  46. this->at = modem;
  47. this->mux = -1;
  48. sock_connected = false;
  49. return true;
  50. }
  51. public:
  52. virtual int connect(const char *host, uint16_t port, int timeout_s) {
  53. stop();
  54. TINY_GSM_YIELD();
  55. rx.clear();
  56. uint8_t newMux = -1;
  57. sock_connected = at->modemConnect(host, port, &newMux, timeout_s);
  58. if (sock_connected) {
  59. mux = newMux;
  60. at->sockets[mux] = this;
  61. }
  62. return sock_connected;
  63. }
  64. TINY_GSM_CLIENT_CONNECT_OVERLOADS()
  65. virtual void stop(uint32_t maxWaitMs) {
  66. TINY_GSM_YIELD();
  67. at->sendAT(GF("+CIPCLOSE="), mux);
  68. sock_connected = false;
  69. at->waitResponse(maxWaitMs);
  70. rx.clear();
  71. }
  72. virtual void stop() { stop(1000L); }
  73. TINY_GSM_CLIENT_WRITE()
  74. TINY_GSM_CLIENT_AVAILABLE_NO_MODEM_FIFO()
  75. TINY_GSM_CLIENT_READ_NO_MODEM_FIFO()
  76. TINY_GSM_CLIENT_PEEK_FLUSH_CONNECTED()
  77. /*
  78. * Extended API
  79. */
  80. String remoteIP() TINY_GSM_ATTR_NOT_IMPLEMENTED;
  81. private:
  82. TinyGsmA6* at;
  83. uint8_t mux;
  84. bool sock_connected;
  85. RxFifo rx;
  86. };
  87. public:
  88. TinyGsmA6(Stream& stream)
  89. : stream(stream)
  90. {
  91. memset(sockets, 0, sizeof(sockets));
  92. }
  93. /*
  94. * Basic functions
  95. */
  96. bool begin(const char* pin = NULL) {
  97. return init(pin);
  98. }
  99. bool init(const char* pin = NULL) {
  100. DBG(GF("### TinyGSM Version:"), TINYGSM_VERSION);
  101. if (!testAT()) {
  102. return false;
  103. }
  104. sendAT(GF("&FZE0")); // Factory + Reset + Echo Off
  105. if (waitResponse() != 1) {
  106. return false;
  107. }
  108. sendAT(GF("+CMEE=0")); // Turn off verbose errors
  109. waitResponse();
  110. sendAT(GF("+CMER=3,0,0,2")); // Set unsolicited result code output destination
  111. waitResponse();
  112. DBG(GF("### Modem:"), getModemName());
  113. getSimStatus();
  114. return true;
  115. }
  116. String getModemName() {
  117. #if defined(TINY_GSM_MODEM_A6)
  118. return "AI-Thinker A6";
  119. #elif defined(TINY_GSM_MODEM_A7)
  120. return "AI-Thinker A7";
  121. #endif
  122. return "AI-Thinker A6";
  123. }
  124. TINY_GSM_MODEM_SET_BAUD_IPR()
  125. TINY_GSM_MODEM_TEST_AT()
  126. TINY_GSM_MODEM_MAINTAIN_LISTEN()
  127. bool factoryDefault() {
  128. sendAT(GF("&FZE0&W")); // Factory + Reset + Echo Off + Write
  129. waitResponse();
  130. sendAT(GF("&W")); // Write configuration
  131. return waitResponse() == 1;
  132. }
  133. TINY_GSM_MODEM_GET_INFO_ATI()
  134. bool hasSSL() {
  135. return false;
  136. }
  137. bool hasWifi() {
  138. return false;
  139. }
  140. bool hasGPRS() {
  141. return true;
  142. }
  143. /*
  144. * Power functions
  145. */
  146. bool restart() {
  147. if (!testAT()) {
  148. return false;
  149. }
  150. sendAT(GF("+RST=1"));
  151. delay(3000);
  152. return init();
  153. }
  154. bool poweroff() {
  155. sendAT(GF("+CPOF"));
  156. return waitResponse() == 1;
  157. }
  158. bool radioOff() TINY_GSM_ATTR_NOT_IMPLEMENTED;
  159. bool sleepEnable(bool enable = true) TINY_GSM_ATTR_NOT_IMPLEMENTED;
  160. /*
  161. * SIM card functions
  162. */
  163. TINY_GSM_MODEM_SIM_UNLOCK_CPIN()
  164. String getSimCCID() {
  165. sendAT(GF("+CCID"));
  166. if (waitResponse(GF(GSM_NL "+SCID: SIM Card ID:")) != 1) {
  167. return "";
  168. }
  169. String res = stream.readStringUntil('\n');
  170. waitResponse();
  171. res.trim();
  172. return res;
  173. }
  174. TINY_GSM_MODEM_GET_IMEI_GSN()
  175. SimStatus getSimStatus(unsigned long timeout_ms = 10000L) {
  176. for (unsigned long start = millis(); millis() - start < timeout_ms; ) {
  177. sendAT(GF("+CPIN?"));
  178. if (waitResponse(GF(GSM_NL "+CPIN:")) != 1) {
  179. delay(1000);
  180. continue;
  181. }
  182. int status = waitResponse(GF("READY"), GF("SIM PIN"), GF("SIM PUK"));
  183. waitResponse();
  184. switch (status) {
  185. case 2:
  186. case 3: return SIM_LOCKED;
  187. case 1: return SIM_READY;
  188. default: return SIM_ERROR;
  189. }
  190. }
  191. return SIM_ERROR;
  192. }
  193. TINY_GSM_MODEM_GET_REGISTRATION_XREG(CREG)
  194. String getOperator() {
  195. sendAT(GF("+COPS=3,0")); // Set format
  196. waitResponse();
  197. sendAT(GF("+COPS?"));
  198. if (waitResponse(GF(GSM_NL "+COPS:")) != 1) {
  199. return "";
  200. }
  201. streamSkipUntil('"'); // Skip mode and format
  202. String res = stream.readStringUntil('"');
  203. waitResponse();
  204. return res;
  205. }
  206. /*
  207. * Generic network functions
  208. */
  209. TINY_GSM_MODEM_GET_CSQ()
  210. bool isNetworkConnected() {
  211. RegStatus s = getRegistrationStatus();
  212. return (s == REG_OK_HOME || s == REG_OK_ROAMING);
  213. }
  214. TINY_GSM_MODEM_WAIT_FOR_NETWORK()
  215. /*
  216. * GPRS functions
  217. */
  218. bool gprsConnect(const char* apn, const char* user = NULL, const char* pwd = NULL) {
  219. gprsDisconnect();
  220. sendAT(GF("+CGATT=1"));
  221. if (waitResponse(60000L) != 1)
  222. return false;
  223. // TODO: wait AT+CGATT?
  224. sendAT(GF("+CGDCONT=1,\"IP\",\""), apn, '"');
  225. waitResponse();
  226. if (!user) user = "";
  227. if (!pwd) pwd = "";
  228. sendAT(GF("+CSTT=\""), apn, GF("\",\""), user, GF("\",\""), pwd, GF("\""));
  229. if (waitResponse(60000L) != 1) {
  230. return false;
  231. }
  232. sendAT(GF("+CGACT=1,1"));
  233. waitResponse(60000L);
  234. sendAT(GF("+CIPMUX=1"));
  235. if (waitResponse() != 1) {
  236. return false;
  237. }
  238. return true;
  239. }
  240. bool gprsDisconnect() {
  241. // Shut the TCP/IP connection
  242. sendAT(GF("+CIPSHUT"));
  243. if (waitResponse(60000L) != 1)
  244. return false;
  245. for (int i = 0; i<3; i++) {
  246. sendAT(GF("+CGATT=0"));
  247. if (waitResponse(5000L) == 1)
  248. return true;
  249. }
  250. return false;
  251. }
  252. bool isGprsConnected() {
  253. sendAT(GF("+CGATT?"));
  254. if (waitResponse(GF(GSM_NL "+CGATT:")) != 1) {
  255. return false;
  256. }
  257. int res = stream.readStringUntil('\n').toInt();
  258. waitResponse();
  259. return (res == 1);
  260. }
  261. /*
  262. * IP Address functions
  263. */
  264. String getLocalIP() {
  265. sendAT(GF("+CIFSR"));
  266. String res;
  267. if (waitResponse(10000L, res) != 1) {
  268. return "";
  269. }
  270. res.replace(GSM_NL "OK" GSM_NL, "");
  271. res.replace(GSM_NL, "");
  272. res.trim();
  273. return res;
  274. }
  275. IPAddress localIP() {
  276. return TinyGsmIpFromString(getLocalIP());
  277. }
  278. /*
  279. * Phone Call functions
  280. */
  281. bool setGsmBusy(bool busy = true) TINY_GSM_ATTR_NOT_AVAILABLE;
  282. bool callAnswer() {
  283. sendAT(GF("A"));
  284. return waitResponse() == 1;
  285. }
  286. // Returns true on pick-up, false on error/busy
  287. bool callNumber(const String& number) {
  288. if (number == GF("last")) {
  289. sendAT(GF("DLST"));
  290. } else {
  291. sendAT(GF("D\""), number, "\";");
  292. }
  293. if (waitResponse(5000L) != 1) {
  294. return false;
  295. }
  296. if (waitResponse(60000L,
  297. GF(GSM_NL "+CIEV: \"CALL\",1"),
  298. GF(GSM_NL "+CIEV: \"CALL\",0"),
  299. GFP(GSM_ERROR)) != 1)
  300. {
  301. return false;
  302. }
  303. int rsp = waitResponse(60000L,
  304. GF(GSM_NL "+CIEV: \"SOUNDER\",0"),
  305. GF(GSM_NL "+CIEV: \"CALL\",0"));
  306. int rsp2 = waitResponse(300L, GF(GSM_NL "BUSY" GSM_NL), GF(GSM_NL "NO ANSWER" GSM_NL));
  307. return rsp == 1 && rsp2 == 0;
  308. }
  309. bool callHangup() {
  310. sendAT(GF("H"));
  311. return waitResponse() == 1;
  312. }
  313. // 0-9,*,#,A,B,C,D
  314. bool dtmfSend(char cmd, unsigned duration_ms = 100) {
  315. duration_ms = constrain(duration_ms, 100, 1000);
  316. // The duration parameter is not working, so we simulate it using delay..
  317. // TODO: Maybe there's another way...
  318. //sendAT(GF("+VTD="), duration_ms / 100);
  319. //waitResponse();
  320. sendAT(GF("+VTS="), cmd);
  321. if (waitResponse(10000L) == 1) {
  322. delay(duration_ms);
  323. return true;
  324. }
  325. return false;
  326. }
  327. /*
  328. * Audio functions
  329. */
  330. bool audioSetHeadphones() {
  331. sendAT(GF("+SNFS=0"));
  332. return waitResponse() == 1;
  333. }
  334. bool audioSetSpeaker() {
  335. sendAT(GF("+SNFS=1"));
  336. return waitResponse() == 1;
  337. }
  338. bool audioMuteMic(bool mute) {
  339. sendAT(GF("+CMUT="), mute);
  340. return waitResponse() == 1;
  341. }
  342. /*
  343. * Messaging functions
  344. */
  345. String sendUSSD(const String& code) {
  346. sendAT(GF("+CMGF=1"));
  347. waitResponse();
  348. sendAT(GF("+CSCS=\"HEX\""));
  349. waitResponse();
  350. sendAT(GF("+CUSD=1,\""), code, GF("\",15"));
  351. if (waitResponse(10000L) != 1) {
  352. return "";
  353. }
  354. if (waitResponse(GF(GSM_NL "+CUSD:")) != 1) {
  355. return "";
  356. }
  357. stream.readStringUntil('"');
  358. String hex = stream.readStringUntil('"');
  359. stream.readStringUntil(',');
  360. int dcs = stream.readStringUntil('\n').toInt();
  361. if (dcs == 15) {
  362. return TinyGsmDecodeHex7bit(hex);
  363. } else if (dcs == 72) {
  364. return TinyGsmDecodeHex16bit(hex);
  365. } else {
  366. return hex;
  367. }
  368. }
  369. bool sendSMS(const String& number, const String& text) {
  370. sendAT(GF("+CMGF=1"));
  371. waitResponse();
  372. sendAT(GF("+CMGS=\""), number, GF("\""));
  373. if (waitResponse(GF(">")) != 1) {
  374. return false;
  375. }
  376. stream.print(text);
  377. stream.write((char)0x1A);
  378. stream.flush();
  379. return waitResponse(60000L) == 1;
  380. }
  381. /*
  382. * Location functions
  383. */
  384. String getGsmLocation() TINY_GSM_ATTR_NOT_AVAILABLE;
  385. /*
  386. * Battery & temperature functions
  387. */
  388. uint16_t getBattVoltage() TINY_GSM_ATTR_NOT_AVAILABLE;
  389. int8_t getBattPercent() {
  390. sendAT(GF("+CBC?"));
  391. if (waitResponse(GF(GSM_NL "+CBC:")) != 1) {
  392. return false;
  393. }
  394. streamSkipUntil(','); // Skip battery charge status
  395. // Read battery charge level
  396. int res = stream.readStringUntil('\n').toInt();
  397. // Wait for final OK
  398. waitResponse();
  399. return res;
  400. }
  401. uint8_t getBattChargeState() {
  402. sendAT(GF("+CBC?"));
  403. if (waitResponse(GF(GSM_NL "+CBC:")) != 1) {
  404. return false;
  405. }
  406. // Read battery charge status
  407. int res = stream.readStringUntil(',').toInt();
  408. // Wait for final OK
  409. waitResponse();
  410. return res;
  411. }
  412. bool getBattStats(uint8_t &chargeState, int8_t &percent, uint16_t &milliVolts) {
  413. sendAT(GF("+CBC?"));
  414. if (waitResponse(GF(GSM_NL "+CBC:")) != 1) {
  415. return false;
  416. }
  417. chargeState = stream.readStringUntil(',').toInt();
  418. percent = stream.readStringUntil('\n').toInt();
  419. // Wait for final OK
  420. waitResponse();
  421. return true;
  422. }
  423. float getTemperature() TINY_GSM_ATTR_NOT_AVAILABLE;
  424. /*
  425. * Client related functions
  426. */
  427. protected:
  428. bool modemConnect(const char* host, uint16_t port, uint8_t* mux, int timeout_s = 75) {
  429. unsigned long startMillis = millis();
  430. uint32_t timeout_ms = ((uint32_t)timeout_s)*1000;
  431. sendAT(GF("+CIPSTART="), GF("\"TCP"), GF("\",\""), host, GF("\","), port);
  432. if (waitResponse(timeout_ms, GF(GSM_NL "+CIPNUM:")) != 1) {
  433. return false;
  434. }
  435. int newMux = stream.readStringUntil('\n').toInt();
  436. int rsp = waitResponse((timeout_ms- (millis() - startMillis)),
  437. GF("CONNECT OK" GSM_NL),
  438. GF("CONNECT FAIL" GSM_NL),
  439. GF("ALREADY CONNECT" GSM_NL));
  440. if (waitResponse() != 1) {
  441. return false;
  442. }
  443. *mux = newMux;
  444. return (1 == rsp);
  445. }
  446. int16_t modemSend(const void* buff, size_t len, uint8_t mux) {
  447. sendAT(GF("+CIPSEND="), mux, ',', len);
  448. if (waitResponse(2000L, GF(GSM_NL ">")) != 1) {
  449. return 0;
  450. }
  451. stream.write((uint8_t*)buff, len);
  452. stream.flush();
  453. if (waitResponse(10000L, GFP(GSM_OK), GF(GSM_NL "FAIL")) != 1) {
  454. return 0;
  455. }
  456. return len;
  457. }
  458. bool modemGetConnected(uint8_t mux) {
  459. sendAT(GF("+CIPSTATUS")); //TODO mux?
  460. int res = waitResponse(GF(",\"CONNECTED\""), GF(",\"CLOSED\""), GF(",\"CLOSING\""), GF(",\"INITIAL\""));
  461. waitResponse();
  462. return 1 == res;
  463. }
  464. public:
  465. /*
  466. Utilities
  467. */
  468. TINY_GSM_MODEM_STREAM_UTILITIES()
  469. // TODO: Optimize this!
  470. uint8_t waitResponse(uint32_t timeout_ms, String& data,
  471. GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  472. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  473. {
  474. /*String r1s(r1); r1s.trim();
  475. String r2s(r2); r2s.trim();
  476. String r3s(r3); r3s.trim();
  477. String r4s(r4); r4s.trim();
  478. String r5s(r5); r5s.trim();
  479. DBG("### ..:", r1s, ",", r2s, ",", r3s, ",", r4s, ",", r5s);*/
  480. data.reserve(64);
  481. int index = 0;
  482. unsigned long startMillis = millis();
  483. do {
  484. TINY_GSM_YIELD();
  485. while (stream.available() > 0) {
  486. TINY_GSM_YIELD();
  487. int a = stream.read();
  488. if (a <= 0) continue; // Skip 0x00 bytes, just in case
  489. data += (char)a;
  490. if (r1 && data.endsWith(r1)) {
  491. index = 1;
  492. goto finish;
  493. } else if (r2 && data.endsWith(r2)) {
  494. index = 2;
  495. goto finish;
  496. } else if (r3 && data.endsWith(r3)) {
  497. index = 3;
  498. goto finish;
  499. } else if (r4 && data.endsWith(r4)) {
  500. index = 4;
  501. goto finish;
  502. } else if (r5 && data.endsWith(r5)) {
  503. index = 5;
  504. goto finish;
  505. } else if (data.endsWith(GF("+CIPRCV:"))) {
  506. int mux = stream.readStringUntil(',').toInt();
  507. int len = stream.readStringUntil(',').toInt();
  508. int len_orig = len;
  509. if (len > sockets[mux]->rx.free()) {
  510. DBG("### Buffer overflow: ", len, "->", sockets[mux]->rx.free());
  511. } else {
  512. DBG("### Got: ", len, "->", sockets[mux]->rx.free());
  513. }
  514. while (len--) {
  515. TINY_GSM_MODEM_STREAM_TO_MUX_FIFO_WITH_DOUBLE_TIMEOUT
  516. }
  517. if (len_orig > sockets[mux]->available()) { // TODO
  518. DBG("### Fewer characters received than expected: ", sockets[mux]->available(), " vs ", len_orig);
  519. }
  520. data = "";
  521. } else if (data.endsWith(GF("+TCPCLOSED:"))) {
  522. int mux = stream.readStringUntil('\n').toInt();
  523. if (mux >= 0 && mux < TINY_GSM_MUX_COUNT) {
  524. sockets[mux]->sock_connected = false;
  525. }
  526. data = "";
  527. DBG("### Closed: ", mux);
  528. }
  529. }
  530. } while (millis() - startMillis < timeout_ms);
  531. finish:
  532. if (!index) {
  533. data.trim();
  534. if (data.length()) {
  535. DBG("### Unhandled:", data);
  536. }
  537. data = "";
  538. }
  539. //data.replace(GSM_NL, "/");
  540. //DBG('<', index, '>', data);
  541. return index;
  542. }
  543. uint8_t waitResponse(uint32_t timeout_ms,
  544. GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  545. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  546. {
  547. String data;
  548. return waitResponse(timeout_ms, data, r1, r2, r3, r4, r5);
  549. }
  550. uint8_t waitResponse(GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  551. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  552. {
  553. return waitResponse(1000, r1, r2, r3, r4, r5);
  554. }
  555. public:
  556. Stream& stream;
  557. protected:
  558. GsmClient* sockets[TINY_GSM_MUX_COUNT];
  559. };
  560. #endif