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.

633 lines
15 KiB

7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
  1. /**
  2. * @file TinyWiFiClientESP8266.h
  3. * @author Volodymyr Shymanskyy
  4. * @license LGPL-3.0
  5. * @copyright Copyright (c) 2016 Volodymyr Shymanskyy
  6. * @date Nov 2016
  7. */
  8. #ifndef TinyGsmClientXBee_h
  9. #define TinyGsmClientXBee_h
  10. // #define TINY_GSM_DEBUG Serial
  11. #if !defined(TINY_GSM_RX_BUFFER)
  12. #define TINY_GSM_RX_BUFFER 256
  13. #endif
  14. #define TINY_GSM_MUX_COUNT 1 // Multi-plexing isn't supported using command mode
  15. #include <TinyGsmCommon.h>
  16. #define GSM_NL "\r"
  17. static const char GSM_OK[] TINY_GSM_PROGMEM = "OK" GSM_NL;
  18. static const char GSM_ERROR[] TINY_GSM_PROGMEM = "ERROR" GSM_NL;
  19. enum SimStatus {
  20. SIM_ERROR = 0,
  21. SIM_READY = 1,
  22. SIM_LOCKED = 2,
  23. };
  24. enum XBeeType {
  25. S6B = 0,
  26. LTEC1 = 1,
  27. };
  28. enum RegStatus {
  29. REG_UNREGISTERED = 0,
  30. REG_SEARCHING = 2,
  31. REG_DENIED = 3,
  32. REG_OK_HOME = 1,
  33. REG_OK_ROAMING = 5,
  34. REG_UNKNOWN = 4,
  35. };
  36. class TinyGsm
  37. {
  38. public:
  39. TinyGsm(Stream& stream)
  40. : stream(stream)
  41. {}
  42. public:
  43. class GsmClient : public Client
  44. {
  45. friend class TinyGsm;
  46. public:
  47. GsmClient() {}
  48. GsmClient(TinyGsm& modem, uint8_t mux = 0) {
  49. init(&modem, mux);
  50. }
  51. bool init(TinyGsm* modem, uint8_t mux = 0) {
  52. this->at = modem;
  53. this->mux = mux;
  54. sock_connected = false;
  55. at->sockets[mux] = this;
  56. return true;
  57. }
  58. public:
  59. virtual int connect(const char *host, uint16_t port) {
  60. at->streamClear(); // Empty anything remaining in the buffer;
  61. at->commandMode();
  62. sock_connected = at->modemConnect(host, port, mux);
  63. at->writeChanges();
  64. at->exitCommand();
  65. return sock_connected;
  66. }
  67. virtual int connect(IPAddress ip, uint16_t port) {
  68. at->streamClear(); // Empty anything remaining in the buffer;
  69. at->commandMode();
  70. sock_connected = at->modemConnect(ip, port, mux);
  71. at->writeChanges();
  72. at->exitCommand();
  73. return sock_connected;
  74. }
  75. // This is a hack to shut the socket by setting the timeout to zero and
  76. // then sending an empty line to the server.
  77. virtual void stop() {
  78. at->commandMode();
  79. at->sendAT(GF("TM0")); // Set socket timeout to 0;
  80. at->waitResponse();
  81. at->writeChanges();
  82. at->exitCommand();
  83. at->modemSend("", 1, mux);
  84. at->streamClear(); // Empty anything remaining in the buffer;
  85. at->commandMode();
  86. at->sendAT(GF("TM64")); // Set socket timeout back to 10seconds;
  87. at->waitResponse();
  88. at->writeChanges();
  89. at->exitCommand();
  90. at->streamClear(); // Empty anything remaining in the buffer;
  91. sock_connected = false;
  92. }
  93. virtual size_t write(const uint8_t *buf, size_t size) {
  94. return at->modemSend(buf, size, mux);
  95. }
  96. virtual size_t write(uint8_t c) {
  97. return write(&c, 1);
  98. }
  99. virtual int available() {
  100. return at->stream.available();
  101. }
  102. virtual int read(uint8_t *buf, size_t size) {
  103. return available();
  104. }
  105. virtual int read() {
  106. TINY_GSM_YIELD();
  107. return at->stream.read();
  108. }
  109. virtual int peek() { return at->stream.peek(); }
  110. virtual void flush() { at->stream.flush(); }
  111. virtual uint8_t connected() {
  112. if (available()) {
  113. return true;
  114. }
  115. return sock_connected;
  116. }
  117. virtual operator bool() { return connected(); }
  118. private:
  119. TinyGsm* at;
  120. uint8_t mux;
  121. bool sock_connected;
  122. };
  123. public:
  124. /*
  125. * Basic functions
  126. */
  127. bool begin() {
  128. return init();
  129. }
  130. bool init() {
  131. guardTime = 1100;
  132. commandMode();
  133. sendAT(GF("AP0")); // Put in transparent mode
  134. waitResponse();
  135. sendAT(GF("GT64")); // shorten the guard time to 100ms
  136. waitResponse();
  137. writeChanges();
  138. sendAT(GF("HS")); // Get the "Hardware Series"; 0x601 for S6B (Wifi)
  139. // wait for the response
  140. unsigned long startMillis = millis();
  141. while (!stream.available() && millis() - startMillis < 1000) {};
  142. String res = streamReadUntil('\r'); // Does not send an OK, just the result
  143. exitCommand();
  144. if (res == "601") beeType = S6B;
  145. else beeType = LTEC1;
  146. guardTime = 125;
  147. return true;
  148. }
  149. bool autoBaud(unsigned long timeout = 10000L) { // not supported
  150. return false;
  151. }
  152. void maintain() {}
  153. bool factoryDefault() {
  154. commandMode();
  155. sendAT(GF("RE"));
  156. bool ret_val = waitResponse() == 1;
  157. writeChanges();
  158. exitCommand();
  159. return ret_val;
  160. }
  161. /*
  162. * Power functions
  163. */
  164. bool restart() {
  165. commandMode();
  166. sendAT(GF("FR"));
  167. if (waitResponse() != 1) {
  168. return false;
  169. }
  170. delay (2000); // Actually resets about 2 seconds later
  171. for (unsigned long start = millis(); millis() - start < 60000L; ) {
  172. if (commandMode()) {
  173. exitCommand();
  174. return true;
  175. }
  176. }
  177. exitCommand();
  178. return false;;
  179. }
  180. void setupPinSleep() {
  181. commandMode();
  182. sendAT(GF("SM"),1);
  183. waitResponse();
  184. sendAT(GF("SO"),200);
  185. waitResponse();
  186. writeChanges();
  187. exitCommand();
  188. }
  189. /*
  190. * SIM card functions
  191. */
  192. bool simUnlock(const char *pin) { // Not supported
  193. return false;
  194. }
  195. String getSimCCID() {
  196. commandMode();
  197. sendAT(GF("S#"));
  198. // wait for the response
  199. unsigned long startMillis = millis();
  200. while (!stream.available() && millis() - startMillis < 1000) {};
  201. String res = streamReadUntil('\r'); // Does not send an OK, just the result
  202. exitCommand();
  203. return res;
  204. }
  205. String getIMEI() {
  206. commandMode();
  207. sendAT(GF("IM"));
  208. // wait for the response
  209. unsigned long startMillis = millis();
  210. while (!stream.available() && millis() - startMillis < 1000) {};
  211. String res = streamReadUntil('\r'); // Does not send an OK, just the result
  212. exitCommand();
  213. return res;
  214. }
  215. SimStatus getSimStatus(unsigned long timeout = 10000L) {
  216. return SIM_READY; // unsupported
  217. }
  218. RegStatus getRegistrationStatus() {
  219. commandMode();
  220. if (beeType == S6B) sendAT(GF("AI"));
  221. else sendAT(GF("CI"));
  222. // wait for the response
  223. unsigned long startMillis = millis();
  224. while (!stream.available() && millis() - startMillis < 1000) {};
  225. String res = streamReadUntil('\r'); // Does not send an OK, just the result
  226. exitCommand();
  227. if(res == GF("0"))
  228. return REG_OK_HOME;
  229. else if(res == GF("13") || res == GF("2A"))
  230. return REG_UNREGISTERED;
  231. else if(res == GF("FF") || res == GF("22") || res == GF("23") ||
  232. res == GF("40") || res == GF("41") || res == GF("42"))
  233. return REG_SEARCHING;
  234. else if(res == GF("24"))
  235. return REG_DENIED;
  236. else return REG_UNKNOWN;
  237. }
  238. String getOperator() {
  239. commandMode();
  240. sendAT(GF("MN"));
  241. // wait for the response
  242. unsigned long startMillis = millis();
  243. while (!stream.available() && millis() - startMillis < 1000) {};
  244. String res = streamReadUntil('\r'); // Does not send an OK, just the result
  245. exitCommand();
  246. return res;
  247. }
  248. /*
  249. * Generic network functions
  250. */
  251. int getSignalQuality() {
  252. commandMode();
  253. if (beeType == S6B) sendAT(GF("LM")); // ask for the "link margin" - the dB above sensitivity
  254. else sendAT(GF("DB")); // ask for the cell strenght in dBm
  255. // wait for the response
  256. unsigned long startMillis = millis();
  257. while (!stream.available() && millis() - startMillis < 1000) {};
  258. char buf[2] = {0}; // Set up buffer for response
  259. buf[0] = streamRead();
  260. buf[1] = streamRead();
  261. DBG(buf[0], buf[1], "\n");
  262. exitCommand();
  263. int intr = strtol(buf, 0, 16);
  264. if (beeType == S6B) return -93 + intr; // the maximum sensitivity is -93dBm
  265. else return -1*intr; // need to convert to negative number
  266. }
  267. bool waitForNetwork(unsigned long timeout = 60000L) {
  268. for (unsigned long start = millis(); millis() - start < timeout; ) {
  269. commandMode();
  270. if (beeType == S6B) sendAT(GF("AI"));
  271. else sendAT(GF("CI"));
  272. // wait for the response
  273. unsigned long startMillis = millis();
  274. while (!stream.available() && millis() - startMillis < 1000) {};
  275. String res = streamReadUntil('\r'); // Does not send an OK, just the result
  276. exitCommand();
  277. if (res == GF("0")) {
  278. return true;
  279. }
  280. delay(1000);
  281. }
  282. return false;
  283. }
  284. /*
  285. * WiFi functions
  286. */
  287. bool networkConnect(const char* ssid, const char* pwd) {
  288. commandMode();
  289. sendAT(GF("EE"), 2); // Set security to WPA2
  290. waitResponse();
  291. sendAT(GF("ID"), ssid);
  292. if (waitResponse() != 1) {
  293. goto fail;
  294. }
  295. sendAT(GF("PK"), pwd);
  296. if (waitResponse() != 1) {
  297. goto fail;
  298. }
  299. writeChanges();
  300. exitCommand();
  301. return true;
  302. fail:
  303. exitCommand();
  304. return false;
  305. }
  306. bool networkDisconnect() {
  307. return false; // Doesn't support disconnecting
  308. }
  309. String getLocalIP() {
  310. commandMode();
  311. sendAT(GF("MY"));
  312. String IPaddr; IPaddr.reserve(16);
  313. // wait for the response
  314. unsigned long startMillis = millis();
  315. while (stream.available() < 8 && millis() - startMillis < 30000) {};
  316. IPaddr = streamReadUntil('\r'); // read result
  317. return IPaddr;
  318. }
  319. IPAddress localIP() {
  320. String strIP = getLocalIP();
  321. int Parts[4] = {0,0,0,0};
  322. int Part = 0;
  323. for (uint8_t i=0; i<strIP.length(); i++) {
  324. char c = strIP[i];
  325. if (c == '.') {
  326. Part++;
  327. continue;
  328. }
  329. Parts[Part] *= 10;
  330. Parts[Part] += c - '0';
  331. }
  332. IPAddress res(Parts[0], Parts[1], Parts[2], Parts[3]);
  333. return res;
  334. }
  335. /*
  336. * GPRS functions
  337. */
  338. bool gprsConnect(const char* apn, const char* user = "", const char* pw = "") {
  339. commandMode();
  340. sendAT(GF("AN"), apn); // Set the APN
  341. waitResponse();
  342. writeChanges();
  343. exitCommand();
  344. return true;
  345. }
  346. bool gprsDisconnect() { // TODO
  347. return false;
  348. }
  349. /*
  350. * Messaging functions
  351. */
  352. void sendUSSD() {
  353. }
  354. void sendSMS() {
  355. }
  356. bool sendSMS(const String& number, const String& text) {
  357. commandMode();
  358. sendAT(GF("IP"), 2); // Put in text messaging mode
  359. waitResponse();
  360. sendAT(GF("PH"), number); // Set the phone number
  361. waitResponse();
  362. sendAT(GF("TDD")); // Set the text delimiter to the standard 0x0D (carriabe return)
  363. waitResponse();
  364. writeChanges();
  365. exitCommand();
  366. stream.print(text);
  367. stream.write((char)0x0D); // close off with the carriage return
  368. return true;
  369. }
  370. private:
  371. int modemConnect(const char* host, uint16_t port, uint8_t mux = 0) {
  372. sendAT(GF("LA"), host);
  373. String strIP; strIP.reserve(16);
  374. // wait for the response
  375. unsigned long startMillis = millis();
  376. while (stream.available() < 8 && millis() - startMillis < 30000) {};
  377. strIP = streamReadUntil('\r'); // read result
  378. int Parts[4] = {0,0,0,0};
  379. int Part = 0;
  380. for (uint8_t i=0; i<strIP.length(); i++) {
  381. char c = strIP[i];
  382. if (c == '.') {
  383. Part++;
  384. continue;
  385. }
  386. Parts[Part] *= 10;
  387. Parts[Part] += c - '0';
  388. }
  389. IPAddress res(Parts[0], Parts[1], Parts[2], Parts[3]);
  390. return modemConnect(res, port);
  391. }
  392. int modemConnect(IPAddress ip, uint16_t port, uint8_t mux = 0) {
  393. String host; host.reserve(16);
  394. host += ip[0];
  395. host += ".";
  396. host += ip[1];
  397. host += ".";
  398. host += ip[2];
  399. host += ".";
  400. host += ip[3];
  401. sendAT(GF("IP"), 1); // Put in TCP mode
  402. waitResponse();
  403. sendAT(GF("DL"), host); // Set the "Destination Address Low"
  404. waitResponse();
  405. sendAT(GF("DE"), String(port, HEX)); // Set the destination port
  406. int rsp = waitResponse();
  407. return rsp;
  408. }
  409. int modemSend(const void* buff, size_t len, uint8_t mux = 0) {
  410. stream.write((uint8_t*)buff, len);
  411. stream.flush();
  412. return len;
  413. }
  414. bool modemGetConnected(uint8_t mux = 0) {
  415. commandMode();
  416. if (beeType == S6B) sendAT(GF("AI"));
  417. else sendAT(GF("CI"));
  418. int res = waitResponse(GF("0"));
  419. exitCommand();
  420. return 1 == res;
  421. }
  422. /* Private Utilities */
  423. template<typename T>
  424. void streamWrite(T last) {
  425. stream.print(last);
  426. }
  427. template<typename T, typename... Args>
  428. void streamWrite(T head, Args... tail) {
  429. stream.print(head);
  430. streamWrite(tail...);
  431. }
  432. int streamRead() { return stream.read(); }
  433. String streamReadUntil(char c) {
  434. TINY_GSM_YIELD();
  435. String return_string = stream.readStringUntil(c);
  436. return_string.trim();
  437. if (String(c) == GSM_NL) {
  438. DBG(return_string, "\r\n");
  439. } else DBG(return_string, c);
  440. return return_string;
  441. }
  442. void streamClear(void) {
  443. while (stream.available())
  444. {streamRead();}
  445. }
  446. bool commandMode(void) {
  447. delay(guardTime); // cannot send anything for 1 second before entering command mode
  448. streamWrite(GF("+++")); // enter command mode
  449. DBG("\r\n+++\r\n");
  450. return 1 == waitResponse(guardTime*2);
  451. }
  452. void writeChanges(void) {
  453. sendAT(GF("WR")); // Write changes to flash
  454. waitResponse();
  455. sendAT(GF("AC")); // Apply changes
  456. waitResponse();
  457. }
  458. void exitCommand(void) {
  459. sendAT(GF("CN")); // Exit command mode
  460. waitResponse();
  461. }
  462. template<typename... Args>
  463. void sendAT(Args... cmd) {
  464. streamWrite("AT", cmd..., GSM_NL);
  465. stream.flush();
  466. TINY_GSM_YIELD();
  467. DBG(">>> AT ", cmd..., "\r\n");
  468. }
  469. // TODO: Optimize this!
  470. uint8_t waitResponse(uint32_t timeout, 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. int a = streamRead();
  487. if (a <= 0) continue; // Skip 0x00 bytes, just in case
  488. data += (char)a;
  489. if (r1 && data.endsWith(r1)) {
  490. index = 1;
  491. goto finish;
  492. } else if (r2 && data.endsWith(r2)) {
  493. index = 2;
  494. goto finish;
  495. } else if (r3 && data.endsWith(r3)) {
  496. index = 3;
  497. goto finish;
  498. } else if (r4 && data.endsWith(r4)) {
  499. index = 4;
  500. goto finish;
  501. } else if (r5 && data.endsWith(r5)) {
  502. index = 5;
  503. goto finish;
  504. }
  505. }
  506. } while (millis() - startMillis < timeout);
  507. finish:
  508. if (!index) {
  509. data.trim();
  510. data.replace(GSM_NL GSM_NL, GSM_NL);
  511. data.replace(GSM_NL, "\r\n" " ");
  512. if (data.length()) {
  513. DBG("### Unhandled:", data, "\r\n");
  514. } else DBG("### NO RESPONSE!\r\n");
  515. }
  516. else {
  517. data.trim();
  518. data.replace(GSM_NL GSM_NL, GSM_NL);
  519. data.replace(GSM_NL, "\r\n ");
  520. if (data.length()) {
  521. DBG("<<< ", data, "\r\n");
  522. }
  523. }
  524. return index;
  525. }
  526. uint8_t waitResponse(uint32_t timeout,
  527. GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  528. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  529. {
  530. String data;
  531. return waitResponse(timeout, data, r1, r2, r3, r4, r5);
  532. }
  533. uint8_t waitResponse(GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  534. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  535. {
  536. return waitResponse(1000, r1, r2, r3, r4, r5);
  537. }
  538. private:
  539. int guardTime;
  540. XBeeType beeType;
  541. Stream& stream;
  542. GsmClient* sockets[TINY_GSM_MUX_COUNT];
  543. };
  544. #endif