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.

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