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.

580 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
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. exitCommand();
  134. guardTime = 125;
  135. return true;
  136. }
  137. bool autoBaud(unsigned long timeout = 10000L) { // not supported
  138. return false;
  139. }
  140. void maintain() {}
  141. bool factoryDefault() {
  142. commandMode();
  143. sendAT(GF("RE"));
  144. bool ret_val = waitResponse() == 1;
  145. writeChanges();
  146. exitCommand();
  147. return ret_val;
  148. }
  149. /*
  150. * Power functions
  151. */
  152. bool restart() {
  153. commandMode();
  154. sendAT(GF("FR"));
  155. if (waitResponse() != 1) {
  156. return false;
  157. }
  158. delay (2000); // Actually resets about 2 seconds later
  159. for (unsigned long start = millis(); millis() - start < 60000L; ) {
  160. if (commandMode()) {
  161. exitCommand();
  162. return true;
  163. }
  164. }
  165. exitCommand();
  166. return false;;
  167. }
  168. void setupPinSleep() {
  169. commandMode();
  170. sendAT(GF("SM"),1);
  171. waitResponse();
  172. sendAT(GF("SO"),200);
  173. waitResponse();
  174. writeChanges();
  175. exitCommand();
  176. }
  177. /*
  178. * SIM card & Networ Operator functions
  179. */
  180. bool simUnlock(const char *pin) { // Not supported
  181. return false;
  182. }
  183. String getSimCCID() {
  184. commandMode();
  185. sendAT(GF("S#"));
  186. // wait for the response
  187. unsigned long startMillis = millis();
  188. while (!stream.available() && millis() - startMillis < 1000) {};
  189. String res = streamReadUntil('\r'); // Does not send an OK, just the result
  190. exitCommand();
  191. return res;
  192. }
  193. String getIMEI() {
  194. commandMode();
  195. sendAT(GF("IM"));
  196. // wait for the response
  197. unsigned long startMillis = millis();
  198. while (!stream.available() && millis() - startMillis < 1000) {};
  199. String res = streamReadUntil('\r'); // Does not send an OK, just the result
  200. exitCommand();
  201. return res;
  202. }
  203. int getSignalQuality() {
  204. commandMode();
  205. sendAT(GF("DB"));
  206. // wait for the response
  207. unsigned long startMillis = millis();
  208. while (!stream.available() && millis() - startMillis < 1000) {};
  209. char buf[4] = { 0, }; // Does not send an OK, just the result
  210. buf[0] = streamRead();
  211. buf[1] = streamRead();
  212. buf[2] = streamRead();
  213. buf[3] = streamRead();
  214. exitCommand();
  215. int intr = strtol(buf, 0, 16);
  216. return intr;
  217. }
  218. SimStatus getSimStatus(unsigned long timeout = 10000L) {
  219. return SIM_READY; // unsupported
  220. }
  221. RegStatus getRegistrationStatus() {
  222. commandMode();
  223. sendAT(GF("AI"));
  224. // wait for the response
  225. unsigned long startMillis = millis();
  226. while (!stream.available() && millis() - startMillis < 1000) {};
  227. String res = streamReadUntil('\r'); // Does not send an OK, just the result
  228. exitCommand();
  229. if(res == GF("0x00"))
  230. return REG_OK_HOME;
  231. else if(res == GF("0x13") || res == GF("0x2A"))
  232. return REG_UNREGISTERED;
  233. else if(res == GF("0xFF") || res == GF("0x22") || res == GF("0x23") ||
  234. res == GF("0x40") || res == GF("0x41") || res == GF("0x42"))
  235. return REG_SEARCHING;
  236. else if(res == GF("0x24"))
  237. return REG_DENIED;
  238. else return REG_UNKNOWN;
  239. }
  240. String getOperator() {
  241. commandMode();
  242. sendAT(GF("MN"));
  243. // wait for the response
  244. unsigned long startMillis = millis();
  245. while (!stream.available() && millis() - startMillis < 1000) {};
  246. String res = streamReadUntil('\r'); // Does not send an OK, just the result
  247. exitCommand();
  248. return res;
  249. }
  250. bool waitForNetwork(unsigned long timeout = 60000L) {
  251. for (unsigned long start = millis(); millis() - start < timeout; ) {
  252. commandMode();
  253. sendAT(GF("AI"));
  254. // wait for the response
  255. unsigned long startMillis = millis();
  256. while (!stream.available() && millis() - startMillis < 1000) {};
  257. String res = streamReadUntil('\r'); // Does not send an OK, just the result
  258. exitCommand();
  259. if (res == GF("0")) {
  260. return true;
  261. }
  262. delay(1000);
  263. }
  264. return false;
  265. }
  266. /*
  267. * WiFi functions
  268. */
  269. bool networkConnect(const char* ssid, const char* pwd) {
  270. commandMode();
  271. sendAT(GF("EE"), 2); // Set security to WPA2
  272. waitResponse();
  273. sendAT(GF("ID"), ssid);
  274. if (waitResponse() != 1) {
  275. goto fail;
  276. }
  277. sendAT(GF("PK"), pwd);
  278. if (waitResponse() != 1) {
  279. goto fail;
  280. }
  281. writeChanges();
  282. exitCommand();
  283. return true;
  284. fail:
  285. exitCommand();
  286. return false;
  287. }
  288. bool networkDisconnect() {
  289. return false; // Doesn't support disconnecting
  290. }
  291. /*
  292. * GPRS functions
  293. */
  294. bool gprsConnect(const char* apn, const char* user = "", const char* pw = "") {
  295. commandMode();
  296. sendAT(GF("AN"), apn); // Set the APN
  297. waitResponse();
  298. writeChanges();
  299. exitCommand();
  300. return true;
  301. }
  302. bool gprsDisconnect() { // TODO
  303. return false;
  304. }
  305. /*
  306. * Messaging functions
  307. */
  308. void sendUSSD() {
  309. }
  310. void sendSMS() {
  311. }
  312. bool sendSMS(const String& number, const String& text) {
  313. commandMode();
  314. sendAT(GF("IP"), 2); // Put in text messaging mode
  315. waitResponse();
  316. sendAT(GF("PH"), number); // Set the phone number
  317. waitResponse();
  318. sendAT(GF("TDD")); // Set the text delimiter to the standard 0x0D (carriabe return)
  319. waitResponse();
  320. writeChanges();
  321. exitCommand();
  322. stream.print(text);
  323. stream.write((char)0x0D); // close off with the carriage return
  324. return true;
  325. }
  326. /* Public Utilities */
  327. template<typename... Args>
  328. void sendAT(Args... cmd) {
  329. streamWrite("AT", cmd..., GSM_NL);
  330. stream.flush();
  331. TINY_GSM_YIELD();
  332. DBG(">>> AT ", cmd..., "\r\n");
  333. }
  334. // TODO: Optimize this!
  335. uint8_t waitResponse(uint32_t timeout, String& data,
  336. GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  337. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  338. {
  339. /*String r1s(r1); r1s.trim();
  340. String r2s(r2); r2s.trim();
  341. String r3s(r3); r3s.trim();
  342. String r4s(r4); r4s.trim();
  343. String r5s(r5); r5s.trim();
  344. DBG("### ..:", r1s, ",", r2s, ",", r3s, ",", r4s, ",", r5s);*/
  345. data.reserve(64);
  346. int index = 0;
  347. unsigned long startMillis = millis();
  348. do {
  349. TINY_GSM_YIELD();
  350. while (stream.available() > 0) {
  351. int a = streamRead();
  352. if (a <= 0) continue; // Skip 0x00 bytes, just in case
  353. data += (char)a;
  354. if (r1 && data.endsWith(r1)) {
  355. index = 1;
  356. goto finish;
  357. } else if (r2 && data.endsWith(r2)) {
  358. index = 2;
  359. goto finish;
  360. } else if (r3 && data.endsWith(r3)) {
  361. index = 3;
  362. goto finish;
  363. } else if (r4 && data.endsWith(r4)) {
  364. index = 4;
  365. goto finish;
  366. } else if (r5 && data.endsWith(r5)) {
  367. index = 5;
  368. goto finish;
  369. }
  370. }
  371. } while (millis() - startMillis < timeout);
  372. finish:
  373. if (!index) {
  374. data.trim();
  375. data.replace(GSM_NL GSM_NL, GSM_NL);
  376. data.replace(GSM_NL, "\r\n" " ");
  377. if (data.length()) {
  378. DBG("### Unhandled:", data, "\r\n");
  379. } else DBG("### NO RESPONSE!\r\n");
  380. }
  381. else {
  382. data.trim();
  383. data.replace(GSM_NL GSM_NL, GSM_NL);
  384. data.replace(GSM_NL, "\r\n ");
  385. if (data.length()) {
  386. DBG("<<< ", data, "\r\n");
  387. }
  388. }
  389. return index;
  390. }
  391. uint8_t waitResponse(uint32_t timeout,
  392. GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  393. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  394. {
  395. String data;
  396. return waitResponse(timeout, data, r1, r2, r3, r4, r5);
  397. }
  398. uint8_t waitResponse(GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  399. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  400. {
  401. return waitResponse(1000, r1, r2, r3, r4, r5);
  402. }
  403. private:
  404. int modemConnect(const char* host, uint16_t port, uint8_t mux = 1) {
  405. sendAT(GF("LA"), host);
  406. String IPaddr; IPaddr.reserve(16);
  407. // wait for the response
  408. unsigned long startMillis = millis();
  409. while (stream.available() < 8 && millis() - startMillis < 30000) {};
  410. IPaddr = streamReadUntil('\r'); // read result
  411. IPAddress ip;
  412. ip.fromString(IPaddr);
  413. return modemConnect(ip, port);
  414. }
  415. int modemConnect(IPAddress ip, uint16_t port, uint8_t mux = 1) {
  416. String host; host.reserve(16);
  417. host += ip[0];
  418. host += ".";
  419. host += ip[1];
  420. host += ".";
  421. host += ip[2];
  422. host += ".";
  423. host += ip[3];
  424. sendAT(GF("IP"), 1); // Put in TCP mode
  425. waitResponse();
  426. sendAT(GF("DL"), host); // Set the "Destination Address Low"
  427. waitResponse();
  428. sendAT(GF("DE"), String(port, HEX)); // Set the destination port
  429. int rsp = waitResponse();
  430. return rsp;
  431. }
  432. int modemSend(const void* buff, size_t len, uint8_t mux = 1) {
  433. stream.write((uint8_t*)buff, len);
  434. stream.flush();
  435. return len;
  436. }
  437. bool modemGetConnected(uint8_t mux = 1) {
  438. commandMode();
  439. sendAT(GF("AI"));
  440. int res = waitResponse(GF("0"));
  441. exitCommand();
  442. return 1 == res;
  443. }
  444. /* Private Utilities */
  445. template<typename T>
  446. void streamWrite(T last) {
  447. stream.print(last);
  448. }
  449. template<typename T, typename... Args>
  450. void streamWrite(T head, Args... tail) {
  451. stream.print(head);
  452. streamWrite(tail...);
  453. }
  454. int streamRead() {
  455. TINY_GSM_YIELD();
  456. int c = stream.read();
  457. DBG((char)c);
  458. return c;
  459. }
  460. String streamReadUntil(char c) {
  461. TINY_GSM_YIELD();
  462. String return_string = stream.readStringUntil(c);
  463. return_string.trim();
  464. if (String(c) == GSM_NL){
  465. DBG(return_string, "\r\n");
  466. } else DBG(return_string, c);
  467. return return_string;
  468. }
  469. void streamClear(void) {
  470. while (stream.available())
  471. {streamRead();}
  472. }
  473. bool commandMode(void){
  474. delay(guardTime); // cannot send anything for 1 second before entering command mode
  475. streamWrite(GF("+++")); // enter command mode
  476. DBG("\r\n+++\r\n");
  477. return 1 == waitResponse(guardTime*2);
  478. }
  479. void writeChanges(void){
  480. sendAT(GF("WR")); // Write changes to flash
  481. waitResponse();
  482. sendAT(GF("AC")); // Apply changes
  483. waitResponse();
  484. }
  485. void exitCommand(void){
  486. sendAT(GF("CN")); // Exit command mode
  487. waitResponse();
  488. }
  489. private:
  490. int guardTime;
  491. Stream& stream;
  492. GsmClient* sockets[1];
  493. };
  494. typedef TinyGsm::GsmClient TinyGsmClient;
  495. #endif