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.

571 lines
13 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
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. TINY_GSM_YIELD();
  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. TINY_GSM_YIELD();
  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. TINY_GSM_YIELD();
  74. at->commandMode();
  75. at->sendAT(GF("TM0")); // Set socket timeout to 0;
  76. at->waitResponse();
  77. at->writeChanges();
  78. at->exitCommand();
  79. at->modemSend("", 1, mux);
  80. at->waitResponse();
  81. at->waitResponse(); // To clear the buffer
  82. at->commandMode();
  83. at->sendAT(GF("TM64")); // Set socket timeout back to 10seconds;
  84. at->waitResponse();
  85. at->writeChanges();
  86. at->exitCommand();
  87. sock_connected = false;
  88. }
  89. virtual size_t write(const uint8_t *buf, size_t size) {
  90. TINY_GSM_YIELD();
  91. //at->maintain();
  92. return at->modemSend(buf, size, mux);
  93. }
  94. virtual size_t write(uint8_t c) {
  95. return write(&c, 1);
  96. }
  97. virtual int available() {
  98. TINY_GSM_YIELD();
  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. exitCommand();
  138. guardTime = 125;
  139. return true;
  140. }
  141. bool autoBaud(unsigned long timeout = 10000L) { // not supported
  142. return false;
  143. }
  144. void maintain() {
  145. //while (stream.available()) {
  146. waitResponse(10, NULL, NULL);
  147. //}
  148. }
  149. bool factoryDefault() {
  150. commandMode();
  151. sendAT(GF("RE"));
  152. bool ret_val = waitResponse() == 1;
  153. writeChanges();
  154. exitCommand();
  155. return ret_val;
  156. }
  157. /*
  158. * Power functions
  159. */
  160. bool restart() {
  161. commandMode();
  162. sendAT(GF("FR"));
  163. if (waitResponse() != 1) {
  164. return false;
  165. }
  166. delay (2000); // Actually resets about 2 seconds later
  167. for (unsigned long start = millis(); millis() - start < 60000L; ) {
  168. if (commandMode()) {
  169. exitCommand();
  170. return true;
  171. }
  172. }
  173. exitCommand();
  174. return false;;
  175. }
  176. void setupPinSleep() {
  177. commandMode();
  178. sendAT(GF("SM"),1);
  179. waitResponse();
  180. sendAT(GF("SO"),200);
  181. waitResponse();
  182. writeChanges();
  183. exitCommand();
  184. }
  185. /*
  186. * SIM card & Networ Operator functions
  187. */
  188. bool simUnlock(const char *pin) { // Not supported
  189. return false;
  190. }
  191. String getSimCCID() {
  192. commandMode();
  193. sendAT(GF("S#"));
  194. String res = streamReadUntil('\r'); // Does not send an OK, just the result
  195. exitCommand();
  196. return res;
  197. }
  198. String getIMEI() {
  199. commandMode();
  200. sendAT(GF("IM"));
  201. String res = streamReadUntil('\r'); // Does not send an OK, just the result
  202. exitCommand();
  203. return res;
  204. }
  205. int getSignalQuality() {
  206. commandMode();
  207. sendAT(GF("DB"));
  208. char buf[4] = { 0, }; // Does not send an OK, just the result
  209. buf[0] = streamRead();
  210. buf[1] = streamRead();
  211. buf[2] = streamRead();
  212. buf[3] = streamRead();
  213. exitCommand();
  214. int intr = strtol(buf, 0, 16);
  215. return intr;
  216. }
  217. SimStatus getSimStatus(unsigned long timeout = 10000L) {
  218. return SIM_READY; // unsupported
  219. }
  220. RegStatus getRegistrationStatus() {
  221. commandMode();
  222. sendAT(GF("AI"));
  223. String res = streamReadUntil('\r'); // Does not send an OK, just the result
  224. exitCommand();
  225. if(res == GF("0x00"))
  226. return REG_OK_HOME;
  227. else if(res == GF("0x13") || res == GF("0x2A"))
  228. return REG_UNREGISTERED;
  229. else if(res == GF("0xFF") || res == GF("0x22") || res == GF("0x23") ||
  230. res == GF("0x40") || res == GF("0x41") || res == GF("0x42"))
  231. return REG_SEARCHING;
  232. else if(res == GF("0x24"))
  233. return REG_DENIED;
  234. else return REG_UNKNOWN;
  235. }
  236. String getOperator() {
  237. commandMode();
  238. sendAT(GF("MN"));
  239. String res = streamReadUntil('\r'); // Does not send an OK, just the result
  240. exitCommand();
  241. return res;
  242. }
  243. bool waitForNetwork(unsigned long timeout = 60000L) {
  244. for (unsigned long start = millis(); millis() - start < timeout; ) {
  245. commandMode();
  246. sendAT(GF("AI"));
  247. String res = streamReadUntil('\r'); // Does not send an OK, just the result
  248. exitCommand();
  249. if (res == GF("0")) {
  250. return true;
  251. }
  252. delay(1000);
  253. }
  254. return false;
  255. }
  256. /*
  257. * WiFi functions
  258. */
  259. bool networkConnect(const char* ssid, const char* pwd) {
  260. commandMode();
  261. sendAT(GF("AP"), 0); // Put in transparent mode
  262. waitResponse();
  263. sendAT(GF("IP"), 1); // Put in TCP mode
  264. waitResponse();
  265. sendAT(GF("EE"), 2); // Set security to WPA2
  266. waitResponse();
  267. sendAT(GF("ID"), ssid);
  268. if (waitResponse() != 1) {
  269. goto fail;
  270. }
  271. sendAT(GF("PK"), pwd);
  272. if (waitResponse() != 1) {
  273. goto fail;
  274. }
  275. writeChanges();
  276. exitCommand();
  277. return true;
  278. fail:
  279. exitCommand();
  280. return false;
  281. }
  282. bool networkDisconnect() {
  283. return false; // Doesn't support disconnecting
  284. }
  285. /*
  286. * GPRS functions
  287. */
  288. bool gprsConnect(const char* apn, const char* user = "", const char* pw = "") {
  289. commandMode();
  290. sendAT(GF("AP"), 0); // Put in transparent mode
  291. waitResponse();
  292. sendAT(GF("IP"), 1); // Put in TCP mode
  293. waitResponse();
  294. sendAT(GF("AN"), apn); // Set the APN
  295. waitResponse();
  296. writeChanges();
  297. exitCommand();
  298. return true;
  299. }
  300. bool gprsDisconnect() { // TODO
  301. return false;
  302. }
  303. /*
  304. * Messaging functions
  305. */
  306. void sendUSSD() {
  307. }
  308. void sendSMS() {
  309. }
  310. bool sendSMS(const String& number, const String& text) {
  311. commandMode();
  312. sendAT(GF("AP"), 0); // Put in transparent mode
  313. waitResponse();
  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);
  379. }
  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. // if (gotData) {
  390. // sockets[mux]->sock_available = modemGetAvailable(mux);
  391. // }
  392. return index;
  393. }
  394. uint8_t waitResponse(uint32_t timeout,
  395. GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  396. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  397. {
  398. String data;
  399. return waitResponse(timeout, data, r1, r2, r3, r4, r5);
  400. }
  401. uint8_t waitResponse(GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  402. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  403. {
  404. return waitResponse(1000, r1, r2, r3, r4, r5);
  405. }
  406. private:
  407. int modemConnect(const char* host, uint16_t port, uint8_t mux = 1) {
  408. sendAT(GF("LA"), host);
  409. String ipadd; ipadd.reserve(16);
  410. ipadd = streamReadUntil('\r');
  411. IPAddress ip;
  412. ip.fromString(ipadd);
  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("DL"), host);
  425. waitResponse();
  426. sendAT(GF("DE"), String(port, HEX));
  427. int rsp = waitResponse();
  428. return rsp;
  429. }
  430. int modemSend(const void* buff, size_t len, uint8_t mux = 1) {
  431. stream.write((uint8_t*)buff, len);
  432. return len;
  433. }
  434. bool modemGetConnected(uint8_t mux = 1) {
  435. commandMode();
  436. sendAT(GF("AI"));
  437. int res = waitResponse(GF("0"));
  438. exitCommand();
  439. return 1 == res;
  440. }
  441. /* Private Utilities */
  442. template<typename T>
  443. void streamWrite(T last) {
  444. stream.print(last);
  445. }
  446. template<typename T, typename... Args>
  447. void streamWrite(T head, Args... tail) {
  448. stream.print(head);
  449. streamWrite(tail...);
  450. }
  451. int streamRead() {
  452. int c = stream.read();
  453. DBG((char)c);
  454. return c;
  455. }
  456. String streamReadUntil(char c) {
  457. String return_string = stream.readStringUntil(c);
  458. return_string.trim();
  459. if (String(c) == GSM_NL){
  460. DBG(return_string, "\r\n");
  461. } else DBG(return_string, c);
  462. return return_string;
  463. }
  464. bool commandMode(void){
  465. delay(guardTime); // cannot send anything for 1 second before entering command mode
  466. streamWrite(GF("+++")); // enter command mode
  467. DBG("\r\n+++\r\n");
  468. waitResponse(guardTime);
  469. return 1 == waitResponse(1100); // wait another second for an "OK\r"
  470. }
  471. void writeChanges(void){
  472. sendAT(GF("WR")); // Write changes to flash
  473. waitResponse();
  474. sendAT(GF("AC")); // Apply changes
  475. waitResponse();
  476. }
  477. void exitCommand(void){
  478. sendAT(GF("CN")); // Exit command mode
  479. waitResponse();
  480. }
  481. private:
  482. int guardTime;
  483. Stream& stream;
  484. GsmClient* sockets[1];
  485. };
  486. typedef TinyGsm::GsmClient TinyGsmClient;
  487. #endif