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.

580 lines
16 KiB

4 years ago
7 years ago
5 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 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 SRC_TINYGSMCLIENTA6_H_
  9. #define SRC_TINYGSMCLIENTA6_H_
  10. // #pragma message("TinyGSM: TinyGsmClientA6")
  11. // #define TINY_GSM_DEBUG Serial
  12. #define TINY_GSM_MUX_COUNT 8
  13. #define TINY_GSM_NO_MODEM_BUFFER
  14. #include "TinyGsmBattery.tpp"
  15. #include "TinyGsmCalling.tpp"
  16. #include "TinyGsmGPRS.tpp"
  17. #include "TinyGsmModem.tpp"
  18. #include "TinyGsmSMS.tpp"
  19. #include "TinyGsmTCP.tpp"
  20. #include "TinyGsmTime.tpp"
  21. #define GSM_NL "\r\n"
  22. static const char GSM_OK[] TINY_GSM_PROGMEM = "OK" GSM_NL;
  23. static const char GSM_ERROR[] TINY_GSM_PROGMEM = "ERROR" GSM_NL;
  24. #if defined TINY_GSM_DEBUG
  25. static const char GSM_CME_ERROR[] TINY_GSM_PROGMEM = GSM_NL "+CME ERROR:";
  26. static const char GSM_CMS_ERROR[] TINY_GSM_PROGMEM = GSM_NL "+CMS ERROR:";
  27. #endif
  28. enum RegStatus {
  29. REG_NO_RESULT = -1,
  30. REG_UNREGISTERED = 0,
  31. REG_SEARCHING = 2,
  32. REG_DENIED = 3,
  33. REG_OK_HOME = 1,
  34. REG_OK_ROAMING = 5,
  35. REG_UNKNOWN = 4,
  36. };
  37. class TinyGsmA6 : public TinyGsmModem<TinyGsmA6>,
  38. public TinyGsmGPRS<TinyGsmA6>,
  39. public TinyGsmTCP<TinyGsmA6, TINY_GSM_MUX_COUNT>,
  40. public TinyGsmCalling<TinyGsmA6>,
  41. public TinyGsmSMS<TinyGsmA6>,
  42. public TinyGsmTime<TinyGsmA6>,
  43. public TinyGsmBattery<TinyGsmA6> {
  44. friend class TinyGsmModem<TinyGsmA6>;
  45. friend class TinyGsmGPRS<TinyGsmA6>;
  46. friend class TinyGsmTCP<TinyGsmA6, TINY_GSM_MUX_COUNT>;
  47. friend class TinyGsmCalling<TinyGsmA6>;
  48. friend class TinyGsmSMS<TinyGsmA6>;
  49. friend class TinyGsmTime<TinyGsmA6>;
  50. friend class TinyGsmBattery<TinyGsmA6>;
  51. /*
  52. * Inner Client
  53. */
  54. public:
  55. class GsmClientA6 : public GsmClient {
  56. friend class TinyGsmA6;
  57. public:
  58. GsmClientA6() {}
  59. explicit GsmClientA6(TinyGsmA6& modem, uint8_t = 0) {
  60. init(&modem, -1);
  61. }
  62. bool init(TinyGsmA6* modem, uint8_t = 0) {
  63. this->at = modem;
  64. this->mux = -1;
  65. sock_connected = false;
  66. return true;
  67. }
  68. public:
  69. virtual int connect(const char* host, uint16_t port, int timeout_s) {
  70. stop();
  71. TINY_GSM_YIELD();
  72. rx.clear();
  73. uint8_t newMux = -1;
  74. sock_connected = at->modemConnect(host, port, &newMux, timeout_s);
  75. if (sock_connected) {
  76. mux = newMux;
  77. at->sockets[mux] = this;
  78. }
  79. return sock_connected;
  80. }
  81. TINY_GSM_CLIENT_CONNECT_OVERRIDES
  82. void stop(uint32_t maxWaitMs) {
  83. TINY_GSM_YIELD();
  84. at->sendAT(GF("+CIPCLOSE="), mux);
  85. sock_connected = false;
  86. at->waitResponse(maxWaitMs);
  87. rx.clear();
  88. }
  89. void stop() override {
  90. stop(1000L);
  91. }
  92. /*
  93. * Extended API
  94. */
  95. String remoteIP() TINY_GSM_ATTR_NOT_IMPLEMENTED;
  96. };
  97. /*
  98. * Inner Secure Client
  99. */
  100. // Doesn't support SSL
  101. /*
  102. * Constructor
  103. */
  104. public:
  105. explicit TinyGsmA6(Stream& stream) : stream(stream) {
  106. memset(sockets, 0, sizeof(sockets));
  107. }
  108. /*
  109. * Basic functions
  110. */
  111. protected:
  112. bool initImpl(const char* pin = NULL) {
  113. DBG(GF("### TinyGSM Version:"), TINYGSM_VERSION);
  114. DBG(GF("### TinyGSM Compiled Module: TinyGsmClientA6"));
  115. if (!testAT()) { return false; }
  116. // sendAT(GF("&FZ")); // Factory + Reset
  117. // waitResponse();
  118. sendAT(GF("E0")); // Echo Off
  119. if (waitResponse() != 1) { return false; }
  120. #ifdef TINY_GSM_DEBUG
  121. sendAT(GF("+CMEE=2")); // turn on verbose error codes
  122. #else
  123. sendAT(GF("+CMEE=0")); // turn off error codes
  124. #endif
  125. waitResponse();
  126. sendAT(
  127. GF("+CMER=3,0,0,2")); // Set unsolicited result code output destination
  128. waitResponse();
  129. DBG(GF("### Modem:"), getModemName());
  130. SimStatus ret = getSimStatus();
  131. // if the sim isn't ready and a pin has been provided, try to unlock the sim
  132. if (ret != SIM_READY && pin != NULL && strlen(pin) > 0) {
  133. simUnlock(pin);
  134. return (getSimStatus() == SIM_READY);
  135. } else {
  136. // if the sim is ready, or it's locked but no pin has been provided,
  137. // return true
  138. return (ret == SIM_READY || ret == SIM_LOCKED);
  139. }
  140. }
  141. bool factoryDefaultImpl() {
  142. sendAT(GF("&FZE0&W")); // Factory + Reset + Echo Off + Write
  143. waitResponse();
  144. sendAT(GF("&W")); // Write configuration
  145. return waitResponse() == 1;
  146. }
  147. /*
  148. * Power functions
  149. */
  150. protected:
  151. bool restartImpl(const char* pin = NULL) {
  152. if (!testAT()) { return false; }
  153. sendAT(GF("+RST=1"));
  154. delay(3000);
  155. return init(pin);
  156. }
  157. bool powerOffImpl() {
  158. sendAT(GF("+CPOF"));
  159. // +CPOF: MS OFF OK
  160. return waitResponse() == 1;
  161. }
  162. bool sleepEnableImpl(bool enable = true) TINY_GSM_ATTR_NOT_AVAILABLE;
  163. bool setPhoneFunctionalityImpl(uint8_t fun, bool reset = false)
  164. TINY_GSM_ATTR_NOT_IMPLEMENTED;
  165. /*
  166. * Generic network functions
  167. */
  168. public:
  169. RegStatus getRegistrationStatus() {
  170. return (RegStatus)getRegistrationStatusXREG("CREG");
  171. }
  172. protected:
  173. bool isNetworkConnectedImpl() {
  174. RegStatus s = getRegistrationStatus();
  175. return (s == REG_OK_HOME || s == REG_OK_ROAMING);
  176. }
  177. String getLocalIPImpl() {
  178. sendAT(GF("+CIFSR"));
  179. String res;
  180. if (waitResponse(10000L, res) != 1) { return ""; }
  181. res.replace(GSM_NL "OK" GSM_NL, "");
  182. res.replace(GSM_NL, "");
  183. res.trim();
  184. return res;
  185. }
  186. /*
  187. * GPRS functions
  188. */
  189. protected:
  190. bool gprsConnectImpl(const char* apn, const char* user = NULL,
  191. const char* pwd = NULL) {
  192. gprsDisconnect();
  193. sendAT(GF("+CGATT=1"));
  194. if (waitResponse(60000L) != 1) { return false; }
  195. // TODO(?): wait AT+CGATT?
  196. sendAT(GF("+CGDCONT=1,\"IP\",\""), apn, '"');
  197. waitResponse();
  198. if (!user) user = "";
  199. if (!pwd) pwd = "";
  200. sendAT(GF("+CSTT=\""), apn, GF("\",\""), user, GF("\",\""), pwd, GF("\""));
  201. if (waitResponse(60000L) != 1) { return false; }
  202. sendAT(GF("+CGACT=1,1"));
  203. waitResponse(60000L);
  204. sendAT(GF("+CIPMUX=1"));
  205. if (waitResponse() != 1) { return false; }
  206. return true;
  207. }
  208. bool gprsDisconnectImpl() {
  209. // Shut the TCP/IP connection
  210. sendAT(GF("+CIPSHUT"));
  211. if (waitResponse(60000L) != 1) { return false; }
  212. for (int i = 0; i < 3; i++) {
  213. sendAT(GF("+CGATT=0"));
  214. if (waitResponse(5000L) == 1) { return true; }
  215. }
  216. return false;
  217. }
  218. String getOperatorImpl() {
  219. sendAT(GF("+COPS=3,0")); // Set format
  220. waitResponse();
  221. sendAT(GF("+COPS?"));
  222. if (waitResponse(GF(GSM_NL "+COPS:")) != 1) { return ""; }
  223. streamSkipUntil('"'); // Skip mode and format
  224. String res = stream.readStringUntil('"');
  225. waitResponse();
  226. return res;
  227. }
  228. /*
  229. * SIM card functions
  230. */
  231. protected:
  232. String getSimCCIDImpl() {
  233. sendAT(GF("+CCID"));
  234. if (waitResponse(GF(GSM_NL "+SCID: SIM Card ID:")) != 1) { return ""; }
  235. String res = stream.readStringUntil('\n');
  236. waitResponse();
  237. res.trim();
  238. return res;
  239. }
  240. /*
  241. * Phone Call functions
  242. */
  243. protected:
  244. // Returns true on pick-up, false on error/busy
  245. bool callNumberImpl(const String& number) {
  246. if (number == GF("last")) {
  247. sendAT(GF("DLST"));
  248. } else {
  249. sendAT(GF("D\""), number, "\";");
  250. }
  251. if (waitResponse(5000L) != 1) { return false; }
  252. if (waitResponse(60000L, GF(GSM_NL "+CIEV: \"CALL\",1"),
  253. GF(GSM_NL "+CIEV: \"CALL\",0"), GFP(GSM_ERROR)) != 1) {
  254. return false;
  255. }
  256. int8_t rsp = waitResponse(60000L, GF(GSM_NL "+CIEV: \"SOUNDER\",0"),
  257. GF(GSM_NL "+CIEV: \"CALL\",0"));
  258. int8_t rsp2 = waitResponse(300L, GF(GSM_NL "BUSY" GSM_NL),
  259. GF(GSM_NL "NO ANSWER" GSM_NL));
  260. return rsp == 1 && rsp2 == 0;
  261. }
  262. // 0-9,*,#,A,B,C,D
  263. bool dtmfSendImpl(char cmd, uint8_t duration_ms = 100) {
  264. duration_ms = constrain(duration_ms, 100, 1000);
  265. // The duration parameter is not working, so we simulate it using delay..
  266. // TODO(?): Maybe there's another way...
  267. // sendAT(GF("+VTD="), duration_ms / 100);
  268. // waitResponse();
  269. sendAT(GF("+VTS="), cmd);
  270. if (waitResponse(10000L) == 1) {
  271. delay(duration_ms);
  272. return true;
  273. }
  274. return false;
  275. }
  276. /*
  277. * Audio functions
  278. */
  279. public:
  280. bool audioSetHeadphones() {
  281. sendAT(GF("+SNFS=0"));
  282. return waitResponse() == 1;
  283. }
  284. bool audioSetSpeaker() {
  285. sendAT(GF("+SNFS=1"));
  286. return waitResponse() == 1;
  287. }
  288. bool audioMuteMic(bool mute) {
  289. sendAT(GF("+CMUT="), mute);
  290. return waitResponse() == 1;
  291. }
  292. /*
  293. * Messaging functions
  294. */
  295. protected:
  296. String sendUSSDImpl(const String& code) {
  297. sendAT(GF("+CMGF=1"));
  298. waitResponse();
  299. sendAT(GF("+CSCS=\"HEX\""));
  300. waitResponse();
  301. sendAT(GF("+CUSD=1,\""), code, GF("\",15"));
  302. if (waitResponse(10000L) != 1) { return ""; }
  303. if (waitResponse(GF(GSM_NL "+CUSD:")) != 1) { return ""; }
  304. streamSkipUntil('"');
  305. String hex = stream.readStringUntil('"');
  306. streamSkipUntil(',');
  307. int8_t dcs = streamGetIntBefore('\n');
  308. if (dcs == 15) {
  309. return TinyGsmDecodeHex7bit(hex);
  310. } else if (dcs == 72) {
  311. return TinyGsmDecodeHex16bit(hex);
  312. } else {
  313. return hex;
  314. }
  315. }
  316. /*
  317. * Time functions
  318. */
  319. protected:
  320. // Can follow the standard CCLK function in the template
  321. // Note - the clock probably has to be set manaually first
  322. /*
  323. * Battery functions
  324. */
  325. protected:
  326. uint16_t getBattVoltageImpl() TINY_GSM_ATTR_NOT_AVAILABLE;
  327. // Needs a '?' after CBC, unlike most
  328. int8_t getBattPercentImpl() {
  329. sendAT(GF("+CBC?"));
  330. if (waitResponse(GF(GSM_NL "+CBC:")) != 1) { return false; }
  331. streamSkipUntil(','); // Skip battery charge status
  332. // Read battery charge level
  333. int8_t res = streamGetIntBefore('\n');
  334. // Wait for final OK
  335. waitResponse();
  336. return res;
  337. }
  338. // Needs a '?' after CBC, unlike most
  339. bool getBattStatsImpl(uint8_t& chargeState, int8_t& percent,
  340. uint16_t& milliVolts) {
  341. sendAT(GF("+CBC?"));
  342. if (waitResponse(GF(GSM_NL "+CBC:")) != 1) { return false; }
  343. chargeState = streamGetIntBefore(',');
  344. percent = streamGetIntBefore('\n');
  345. milliVolts = 0;
  346. // Wait for final OK
  347. waitResponse();
  348. return true;
  349. }
  350. /*
  351. * Client related functions
  352. */
  353. protected:
  354. bool modemConnect(const char* host, uint16_t port, uint8_t* mux,
  355. int timeout_s = 75) {
  356. uint32_t startMillis = millis();
  357. uint32_t timeout_ms = ((uint32_t)timeout_s) * 1000;
  358. sendAT(GF("+CIPSTART="), GF("\"TCP"), GF("\",\""), host, GF("\","), port);
  359. if (waitResponse(timeout_ms, GF(GSM_NL "+CIPNUM:")) != 1) { return false; }
  360. int8_t newMux = streamGetIntBefore('\n');
  361. int8_t rsp = waitResponse(
  362. (timeout_ms - (millis() - startMillis)), GF("CONNECT OK" GSM_NL),
  363. GF("CONNECT FAIL" GSM_NL), GF("ALREADY CONNECT" GSM_NL));
  364. if (waitResponse() != 1) { return false; }
  365. *mux = newMux;
  366. return (1 == rsp);
  367. }
  368. int16_t modemSend(const void* buff, size_t len, uint8_t mux) {
  369. sendAT(GF("+CIPSEND="), mux, ',', (uint16_t)len);
  370. if (waitResponse(2000L, GF(GSM_NL ">")) != 1) { return 0; }
  371. stream.write(reinterpret_cast<const uint8_t*>(buff), len);
  372. stream.flush();
  373. if (waitResponse(10000L, GFP(GSM_OK), GF(GSM_NL "FAIL")) != 1) { return 0; }
  374. return len;
  375. }
  376. bool modemGetConnected(uint8_t) {
  377. sendAT(GF("+CIPSTATUS")); // TODO(?) mux?
  378. int8_t res = waitResponse(GF(",\"CONNECTED\""), GF(",\"CLOSED\""),
  379. GF(",\"CLOSING\""), GF(",\"INITIAL\""));
  380. waitResponse();
  381. return 1 == res;
  382. }
  383. /*
  384. * Utilities
  385. */
  386. public:
  387. // TODO(vshymanskyy): Optimize this!
  388. int8_t waitResponse(uint32_t timeout_ms, String& data,
  389. GsmConstStr r1 = GFP(GSM_OK),
  390. GsmConstStr r2 = GFP(GSM_ERROR),
  391. #if defined TINY_GSM_DEBUG
  392. GsmConstStr r3 = GFP(GSM_CME_ERROR),
  393. GsmConstStr r4 = GFP(GSM_CMS_ERROR),
  394. #else
  395. GsmConstStr r3 = NULL, GsmConstStr r4 = NULL,
  396. #endif
  397. GsmConstStr r5 = NULL) {
  398. /*String r1s(r1); r1s.trim();
  399. String r2s(r2); r2s.trim();
  400. String r3s(r3); r3s.trim();
  401. String r4s(r4); r4s.trim();
  402. String r5s(r5); r5s.trim();
  403. DBG("### ..:", r1s, ",", r2s, ",", r3s, ",", r4s, ",", r5s);*/
  404. data.reserve(64);
  405. uint8_t index = 0;
  406. uint32_t startMillis = millis();
  407. do {
  408. TINY_GSM_YIELD();
  409. while (stream.available() > 0) {
  410. TINY_GSM_YIELD();
  411. int8_t a = stream.read();
  412. if (a <= 0) continue; // Skip 0x00 bytes, just in case
  413. data += static_cast<char>(a);
  414. if (r1 && data.endsWith(r1)) {
  415. index = 1;
  416. goto finish;
  417. } else if (r2 && data.endsWith(r2)) {
  418. index = 2;
  419. goto finish;
  420. } else if (r3 && data.endsWith(r3)) {
  421. #if defined TINY_GSM_DEBUG
  422. if (r3 == GFP(GSM_CME_ERROR)) {
  423. streamSkipUntil('\n'); // Read out the error
  424. }
  425. #endif
  426. index = 3;
  427. goto finish;
  428. } else if (r4 && data.endsWith(r4)) {
  429. index = 4;
  430. goto finish;
  431. } else if (r5 && data.endsWith(r5)) {
  432. index = 5;
  433. goto finish;
  434. } else if (data.endsWith(GF("+CIPRCV:"))) {
  435. int8_t mux = streamGetIntBefore(',');
  436. int16_t len = streamGetIntBefore(',');
  437. int16_t len_orig = len;
  438. if (mux >= 0 && mux < TINY_GSM_MUX_COUNT && sockets[mux]) {
  439. if (len > sockets[mux]->rx.free()) {
  440. DBG("### Buffer overflow: ", len, "->", sockets[mux]->rx.free());
  441. } else {
  442. DBG("### Got: ", len, "->", sockets[mux]->rx.free());
  443. }
  444. while (len--) { moveCharFromStreamToFifo(mux); }
  445. // TODO(?) Deal with missing characters
  446. if (len_orig > sockets[mux]->available()) {
  447. DBG("### Fewer characters received than expected: ",
  448. sockets[mux]->available(), " vs ", len_orig);
  449. }
  450. }
  451. data = "";
  452. } else if (data.endsWith(GF("+TCPCLOSED:"))) {
  453. int8_t mux = streamGetIntBefore('\n');
  454. if (mux >= 0 && mux < TINY_GSM_MUX_COUNT && sockets[mux]) {
  455. sockets[mux]->sock_connected = false;
  456. }
  457. data = "";
  458. DBG("### Closed: ", mux);
  459. }
  460. }
  461. } while (millis() - startMillis < timeout_ms);
  462. finish:
  463. if (!index) {
  464. data.trim();
  465. if (data.length()) { DBG("### Unhandled:", data); }
  466. data = "";
  467. }
  468. // data.replace(GSM_NL, "/");
  469. // DBG('<', index, '>', data);
  470. return index;
  471. }
  472. int8_t waitResponse(uint32_t timeout_ms, GsmConstStr r1 = GFP(GSM_OK),
  473. GsmConstStr r2 = GFP(GSM_ERROR),
  474. #if defined TINY_GSM_DEBUG
  475. GsmConstStr r3 = GFP(GSM_CME_ERROR),
  476. GsmConstStr r4 = GFP(GSM_CMS_ERROR),
  477. #else
  478. GsmConstStr r3 = NULL, GsmConstStr r4 = NULL,
  479. #endif
  480. GsmConstStr r5 = NULL) {
  481. String data;
  482. return waitResponse(timeout_ms, data, r1, r2, r3, r4, r5);
  483. }
  484. int8_t waitResponse(GsmConstStr r1 = GFP(GSM_OK),
  485. GsmConstStr r2 = GFP(GSM_ERROR),
  486. #if defined TINY_GSM_DEBUG
  487. GsmConstStr r3 = GFP(GSM_CME_ERROR),
  488. GsmConstStr r4 = GFP(GSM_CMS_ERROR),
  489. #else
  490. GsmConstStr r3 = NULL, GsmConstStr r4 = NULL,
  491. #endif
  492. GsmConstStr r5 = NULL) {
  493. return waitResponse(1000, r1, r2, r3, r4, r5);
  494. }
  495. public:
  496. Stream& stream;
  497. protected:
  498. GsmClientA6* sockets[TINY_GSM_MUX_COUNT];
  499. const char* gsmNL = GSM_NL;
  500. };
  501. #endif // SRC_TINYGSMCLIENTA6_H_