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.

592 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
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 & Network Operator 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. int getSignalQuality() {
  215. commandMode();
  216. if (beeType == S6B) sendAT(GF("LM")); // ask for the "link margin" - the dB above sensitivity
  217. else sendAT(GF("DB")); // ask for the cell strenght in dBm
  218. // wait for the response
  219. unsigned long startMillis = millis();
  220. while (!stream.available() && millis() - startMillis < 1000) {};
  221. char buf[2] = {0}; // Set up buffer for response
  222. buf[0] = streamRead();
  223. buf[1] = streamRead();
  224. DBG(buf[0], buf[1], "\n");
  225. exitCommand();
  226. int intr = strtol(buf, 0, 16);
  227. if (beeType == S6B) return -93 + intr; // the maximum sensitivity is -93dBm
  228. else return -1*intr; // need to convert to negative number
  229. }
  230. SimStatus getSimStatus(unsigned long timeout = 10000L) {
  231. return SIM_READY; // unsupported
  232. }
  233. RegStatus getRegistrationStatus() {
  234. commandMode();
  235. if (beeType == S6B) sendAT(GF("AI"));
  236. else sendAT(GF("CI"));
  237. // wait for the response
  238. unsigned long startMillis = millis();
  239. while (!stream.available() && millis() - startMillis < 1000) {};
  240. String res = streamReadUntil('\r'); // Does not send an OK, just the result
  241. exitCommand();
  242. if(res == GF("0"))
  243. return REG_OK_HOME;
  244. else if(res == GF("13") || res == GF("2A"))
  245. return REG_UNREGISTERED;
  246. else if(res == GF("FF") || res == GF("22") || res == GF("23") ||
  247. res == GF("40") || res == GF("41") || res == GF("42"))
  248. return REG_SEARCHING;
  249. else if(res == GF("24"))
  250. return REG_DENIED;
  251. else return REG_UNKNOWN;
  252. }
  253. String getOperator() {
  254. commandMode();
  255. sendAT(GF("MN"));
  256. // wait for the response
  257. unsigned long startMillis = millis();
  258. while (!stream.available() && millis() - startMillis < 1000) {};
  259. String res = streamReadUntil('\r'); // Does not send an OK, just the result
  260. exitCommand();
  261. return res;
  262. }
  263. bool waitForNetwork(unsigned long timeout = 60000L) {
  264. for (unsigned long start = millis(); millis() - start < timeout; ) {
  265. commandMode();
  266. if (beeType == S6B) sendAT(GF("AI"));
  267. else sendAT(GF("CI"));
  268. // wait for the response
  269. unsigned long startMillis = millis();
  270. while (!stream.available() && millis() - startMillis < 1000) {};
  271. String res = streamReadUntil('\r'); // Does not send an OK, just the result
  272. exitCommand();
  273. if (res == GF("0")) {
  274. return true;
  275. }
  276. delay(1000);
  277. }
  278. return false;
  279. }
  280. /*
  281. * WiFi functions
  282. */
  283. bool networkConnect(const char* ssid, const char* pwd) {
  284. commandMode();
  285. sendAT(GF("EE"), 2); // Set security to WPA2
  286. waitResponse();
  287. sendAT(GF("ID"), ssid);
  288. if (waitResponse() != 1) {
  289. goto fail;
  290. }
  291. sendAT(GF("PK"), pwd);
  292. if (waitResponse() != 1) {
  293. goto fail;
  294. }
  295. writeChanges();
  296. exitCommand();
  297. return true;
  298. fail:
  299. exitCommand();
  300. return false;
  301. }
  302. bool networkDisconnect() {
  303. return false; // Doesn't support disconnecting
  304. }
  305. /*
  306. * GPRS functions
  307. */
  308. bool gprsConnect(const char* apn, const char* user = "", const char* pw = "") {
  309. commandMode();
  310. sendAT(GF("AN"), apn); // Set the APN
  311. waitResponse();
  312. writeChanges();
  313. exitCommand();
  314. return true;
  315. }
  316. bool gprsDisconnect() { // TODO
  317. return false;
  318. }
  319. /*
  320. * Messaging functions
  321. */
  322. void sendUSSD() {
  323. }
  324. void sendSMS() {
  325. }
  326. bool sendSMS(const String& number, const String& text) {
  327. commandMode();
  328. sendAT(GF("IP"), 2); // Put in text messaging mode
  329. waitResponse();
  330. sendAT(GF("PH"), number); // Set the phone number
  331. waitResponse();
  332. sendAT(GF("TDD")); // Set the text delimiter to the standard 0x0D (carriabe return)
  333. waitResponse();
  334. writeChanges();
  335. exitCommand();
  336. stream.print(text);
  337. stream.write((char)0x0D); // close off with the carriage return
  338. return true;
  339. }
  340. /* Public Utilities */
  341. template<typename... Args>
  342. void sendAT(Args... cmd) {
  343. streamWrite("AT", cmd..., GSM_NL);
  344. stream.flush();
  345. TINY_GSM_YIELD();
  346. DBG(">>> AT ", cmd..., "\r\n");
  347. }
  348. // TODO: Optimize this!
  349. uint8_t waitResponse(uint32_t timeout, String& data,
  350. GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  351. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  352. {
  353. /*String r1s(r1); r1s.trim();
  354. String r2s(r2); r2s.trim();
  355. String r3s(r3); r3s.trim();
  356. String r4s(r4); r4s.trim();
  357. String r5s(r5); r5s.trim();
  358. DBG("### ..:", r1s, ",", r2s, ",", r3s, ",", r4s, ",", r5s);*/
  359. data.reserve(64);
  360. int index = 0;
  361. unsigned long startMillis = millis();
  362. do {
  363. TINY_GSM_YIELD();
  364. while (stream.available() > 0) {
  365. int a = streamRead();
  366. if (a <= 0) continue; // Skip 0x00 bytes, just in case
  367. data += (char)a;
  368. if (r1 && data.endsWith(r1)) {
  369. index = 1;
  370. goto finish;
  371. } else if (r2 && data.endsWith(r2)) {
  372. index = 2;
  373. goto finish;
  374. } else if (r3 && data.endsWith(r3)) {
  375. index = 3;
  376. goto finish;
  377. } else if (r4 && data.endsWith(r4)) {
  378. index = 4;
  379. goto finish;
  380. } else if (r5 && data.endsWith(r5)) {
  381. index = 5;
  382. goto finish;
  383. }
  384. }
  385. } while (millis() - startMillis < timeout);
  386. finish:
  387. if (!index) {
  388. data.trim();
  389. data.replace(GSM_NL GSM_NL, GSM_NL);
  390. data.replace(GSM_NL, "\r\n" " ");
  391. if (data.length()) {
  392. DBG("### Unhandled:", data, "\r\n");
  393. } else DBG("### NO RESPONSE!\r\n");
  394. }
  395. else {
  396. data.trim();
  397. data.replace(GSM_NL GSM_NL, GSM_NL);
  398. data.replace(GSM_NL, "\r\n ");
  399. if (data.length()) {
  400. DBG("<<< ", data, "\r\n");
  401. }
  402. }
  403. return index;
  404. }
  405. uint8_t waitResponse(uint32_t timeout,
  406. GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  407. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  408. {
  409. String data;
  410. return waitResponse(timeout, data, r1, r2, r3, r4, r5);
  411. }
  412. uint8_t waitResponse(GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  413. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  414. {
  415. return waitResponse(1000, r1, r2, r3, r4, r5);
  416. }
  417. private:
  418. int modemConnect(const char* host, uint16_t port, uint8_t mux = 1) {
  419. sendAT(GF("LA"), host);
  420. String IPaddr; IPaddr.reserve(16);
  421. // wait for the response
  422. unsigned long startMillis = millis();
  423. while (stream.available() < 8 && millis() - startMillis < 30000) {};
  424. IPaddr = streamReadUntil('\r'); // read result
  425. IPAddress ip;
  426. ip.fromString(IPaddr);
  427. return modemConnect(ip, port);
  428. }
  429. int modemConnect(IPAddress ip, uint16_t port, uint8_t mux = 1) {
  430. String host; host.reserve(16);
  431. host += ip[0];
  432. host += ".";
  433. host += ip[1];
  434. host += ".";
  435. host += ip[2];
  436. host += ".";
  437. host += ip[3];
  438. sendAT(GF("IP"), 1); // Put in TCP mode
  439. waitResponse();
  440. sendAT(GF("DL"), host); // Set the "Destination Address Low"
  441. waitResponse();
  442. sendAT(GF("DE"), String(port, HEX)); // Set the destination port
  443. int rsp = waitResponse();
  444. return rsp;
  445. }
  446. int modemSend(const void* buff, size_t len, uint8_t mux = 1) {
  447. stream.write((uint8_t*)buff, len);
  448. stream.flush();
  449. return len;
  450. }
  451. bool modemGetConnected(uint8_t mux = 1) {
  452. commandMode();
  453. if (beeType == S6B) sendAT(GF("AI"));
  454. else sendAT(GF("CI"));
  455. int res = waitResponse(GF("0"));
  456. exitCommand();
  457. return 1 == res;
  458. }
  459. /* Private Utilities */
  460. template<typename T>
  461. void streamWrite(T last) {
  462. stream.print(last);
  463. }
  464. template<typename T, typename... Args>
  465. void streamWrite(T head, Args... tail) {
  466. stream.print(head);
  467. streamWrite(tail...);
  468. }
  469. int streamRead() { return stream.read(); }
  470. String streamReadUntil(char c) {
  471. TINY_GSM_YIELD();
  472. String return_string = stream.readStringUntil(c);
  473. return_string.trim();
  474. if (String(c) == GSM_NL){
  475. DBG(return_string, "\r\n");
  476. } else DBG(return_string, c);
  477. return return_string;
  478. }
  479. void streamClear(void) {
  480. while (stream.available())
  481. {streamRead();}
  482. }
  483. bool commandMode(void){
  484. delay(guardTime); // cannot send anything for 1 second before entering command mode
  485. streamWrite(GF("+++")); // enter command mode
  486. DBG("\r\n+++\r\n");
  487. return 1 == waitResponse(guardTime*2);
  488. }
  489. void writeChanges(void){
  490. sendAT(GF("WR")); // Write changes to flash
  491. waitResponse();
  492. sendAT(GF("AC")); // Apply changes
  493. waitResponse();
  494. }
  495. void exitCommand(void){
  496. sendAT(GF("CN")); // Exit command mode
  497. waitResponse();
  498. }
  499. private:
  500. int guardTime;
  501. XBeeType beeType;
  502. Stream& stream;
  503. GsmClient* sockets[1];
  504. };
  505. typedef TinyGsm::GsmClient TinyGsmClient;
  506. #endif