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.

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