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.

595 lines
14 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. /*
  309. * GPRS functions
  310. */
  311. bool gprsConnect(const char* apn, const char* user = "", const char* pw = "") {
  312. commandMode();
  313. sendAT(GF("AN"), apn); // Set the APN
  314. waitResponse();
  315. writeChanges();
  316. exitCommand();
  317. return true;
  318. }
  319. bool gprsDisconnect() { // TODO
  320. return false;
  321. }
  322. /*
  323. * Messaging functions
  324. */
  325. void sendUSSD() {
  326. }
  327. void sendSMS() {
  328. }
  329. bool sendSMS(const String& number, const String& text) {
  330. commandMode();
  331. sendAT(GF("IP"), 2); // Put in text messaging mode
  332. waitResponse();
  333. sendAT(GF("PH"), number); // Set the phone number
  334. waitResponse();
  335. sendAT(GF("TDD")); // Set the text delimiter to the standard 0x0D (carriabe return)
  336. waitResponse();
  337. writeChanges();
  338. exitCommand();
  339. stream.print(text);
  340. stream.write((char)0x0D); // close off with the carriage return
  341. return true;
  342. }
  343. private:
  344. int modemConnect(const char* host, uint16_t port, uint8_t mux = 1) {
  345. sendAT(GF("LA"), host);
  346. String IPaddr; IPaddr.reserve(16);
  347. // wait for the response
  348. unsigned long startMillis = millis();
  349. while (stream.available() < 8 && millis() - startMillis < 30000) {};
  350. IPaddr = streamReadUntil('\r'); // read result
  351. IPAddress ip;
  352. ip.fromString(IPaddr);
  353. return modemConnect(ip, port);
  354. }
  355. int modemConnect(IPAddress ip, uint16_t port, uint8_t mux = 1) {
  356. String host; host.reserve(16);
  357. host += ip[0];
  358. host += ".";
  359. host += ip[1];
  360. host += ".";
  361. host += ip[2];
  362. host += ".";
  363. host += ip[3];
  364. sendAT(GF("IP"), 1); // Put in TCP mode
  365. waitResponse();
  366. sendAT(GF("DL"), host); // Set the "Destination Address Low"
  367. waitResponse();
  368. sendAT(GF("DE"), String(port, HEX)); // Set the destination port
  369. int rsp = waitResponse();
  370. return rsp;
  371. }
  372. int modemSend(const void* buff, size_t len, uint8_t mux = 1) {
  373. stream.write((uint8_t*)buff, len);
  374. stream.flush();
  375. return len;
  376. }
  377. bool modemGetConnected(uint8_t mux = 1) {
  378. commandMode();
  379. if (beeType == S6B) sendAT(GF("AI"));
  380. else sendAT(GF("CI"));
  381. int res = waitResponse(GF("0"));
  382. exitCommand();
  383. return 1 == res;
  384. }
  385. /* Private Utilities */
  386. template<typename T>
  387. void streamWrite(T last) {
  388. stream.print(last);
  389. }
  390. template<typename T, typename... Args>
  391. void streamWrite(T head, Args... tail) {
  392. stream.print(head);
  393. streamWrite(tail...);
  394. }
  395. int streamRead() { return stream.read(); }
  396. String streamReadUntil(char c) {
  397. TINY_GSM_YIELD();
  398. String return_string = stream.readStringUntil(c);
  399. return_string.trim();
  400. if (String(c) == GSM_NL) {
  401. DBG(return_string, "\r\n");
  402. } else DBG(return_string, c);
  403. return return_string;
  404. }
  405. void streamClear(void) {
  406. while (stream.available())
  407. {streamRead();}
  408. }
  409. bool commandMode(void) {
  410. delay(guardTime); // cannot send anything for 1 second before entering command mode
  411. streamWrite(GF("+++")); // enter command mode
  412. DBG("\r\n+++\r\n");
  413. return 1 == waitResponse(guardTime*2);
  414. }
  415. void writeChanges(void) {
  416. sendAT(GF("WR")); // Write changes to flash
  417. waitResponse();
  418. sendAT(GF("AC")); // Apply changes
  419. waitResponse();
  420. }
  421. void exitCommand(void) {
  422. sendAT(GF("CN")); // Exit command mode
  423. waitResponse();
  424. }
  425. template<typename... Args>
  426. void sendAT(Args... cmd) {
  427. streamWrite("AT", cmd..., GSM_NL);
  428. stream.flush();
  429. TINY_GSM_YIELD();
  430. DBG(">>> AT ", cmd..., "\r\n");
  431. }
  432. // TODO: Optimize this!
  433. uint8_t waitResponse(uint32_t timeout, String& data,
  434. GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  435. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  436. {
  437. /*String r1s(r1); r1s.trim();
  438. String r2s(r2); r2s.trim();
  439. String r3s(r3); r3s.trim();
  440. String r4s(r4); r4s.trim();
  441. String r5s(r5); r5s.trim();
  442. DBG("### ..:", r1s, ",", r2s, ",", r3s, ",", r4s, ",", r5s);*/
  443. data.reserve(64);
  444. int index = 0;
  445. unsigned long startMillis = millis();
  446. do {
  447. TINY_GSM_YIELD();
  448. while (stream.available() > 0) {
  449. int a = streamRead();
  450. if (a <= 0) continue; // Skip 0x00 bytes, just in case
  451. data += (char)a;
  452. if (r1 && data.endsWith(r1)) {
  453. index = 1;
  454. goto finish;
  455. } else if (r2 && data.endsWith(r2)) {
  456. index = 2;
  457. goto finish;
  458. } else if (r3 && data.endsWith(r3)) {
  459. index = 3;
  460. goto finish;
  461. } else if (r4 && data.endsWith(r4)) {
  462. index = 4;
  463. goto finish;
  464. } else if (r5 && data.endsWith(r5)) {
  465. index = 5;
  466. goto finish;
  467. }
  468. }
  469. } while (millis() - startMillis < timeout);
  470. finish:
  471. if (!index) {
  472. data.trim();
  473. data.replace(GSM_NL GSM_NL, GSM_NL);
  474. data.replace(GSM_NL, "\r\n" " ");
  475. if (data.length()) {
  476. DBG("### Unhandled:", data, "\r\n");
  477. } else DBG("### NO RESPONSE!\r\n");
  478. }
  479. else {
  480. data.trim();
  481. data.replace(GSM_NL GSM_NL, GSM_NL);
  482. data.replace(GSM_NL, "\r\n ");
  483. if (data.length()) {
  484. DBG("<<< ", data, "\r\n");
  485. }
  486. }
  487. return index;
  488. }
  489. uint8_t waitResponse(uint32_t timeout,
  490. GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  491. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  492. {
  493. String data;
  494. return waitResponse(timeout, data, r1, r2, r3, r4, r5);
  495. }
  496. uint8_t waitResponse(GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  497. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  498. {
  499. return waitResponse(1000, r1, r2, r3, r4, r5);
  500. }
  501. private:
  502. int guardTime;
  503. XBeeType beeType;
  504. Stream& stream;
  505. GsmClient* sockets[1];
  506. };
  507. typedef TinyGsm::GsmClient TinyGsmClient;
  508. #endif