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.

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