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.

568 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
  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("EE"), 2); // Set security to WPA2
  262. waitResponse();
  263. sendAT(GF("ID"), ssid);
  264. if (waitResponse() != 1) {
  265. goto fail;
  266. }
  267. sendAT(GF("PK"), pwd);
  268. if (waitResponse() != 1) {
  269. goto fail;
  270. }
  271. writeChanges();
  272. exitCommand();
  273. return true;
  274. fail:
  275. exitCommand();
  276. return false;
  277. }
  278. bool networkDisconnect() {
  279. return false; // Doesn't support disconnecting
  280. }
  281. /*
  282. * GPRS functions
  283. */
  284. bool gprsConnect(const char* apn, const char* user = "", const char* pw = "") {
  285. commandMode();
  286. sendAT(GF("AN"), apn); // Set the APN
  287. waitResponse();
  288. writeChanges();
  289. exitCommand();
  290. return true;
  291. }
  292. bool gprsDisconnect() { // TODO
  293. return false;
  294. }
  295. /*
  296. * Messaging functions
  297. */
  298. void sendUSSD() {
  299. }
  300. void sendSMS() {
  301. }
  302. bool sendSMS(const String& number, const String& text) {
  303. commandMode();
  304. sendAT(GF("IP"), 2); // Put in text messaging mode
  305. waitResponse();
  306. sendAT(GF("PH"), number); // Set the phone number
  307. waitResponse();
  308. sendAT(GF("TDD")); // Set the text delimiter to the standard 0x0D (carriabe return)
  309. waitResponse();
  310. writeChanges();
  311. exitCommand();
  312. stream.print(text);
  313. stream.write((char)0x0D); // close off with the carriage return
  314. return true;
  315. }
  316. /* Public Utilities */
  317. template<typename... Args>
  318. void sendAT(Args... cmd) {
  319. streamWrite("AT", cmd..., GSM_NL);
  320. stream.flush();
  321. TINY_GSM_YIELD();
  322. DBG(">>> AT ", cmd..., "\r\n");
  323. }
  324. // TODO: Optimize this!
  325. uint8_t waitResponse(uint32_t timeout, String& data,
  326. GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  327. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  328. {
  329. /*String r1s(r1); r1s.trim();
  330. String r2s(r2); r2s.trim();
  331. String r3s(r3); r3s.trim();
  332. String r4s(r4); r4s.trim();
  333. String r5s(r5); r5s.trim();
  334. DBG("### ..:", r1s, ",", r2s, ",", r3s, ",", r4s, ",", r5s);*/
  335. data.reserve(64);
  336. int index = 0;
  337. unsigned long startMillis = millis();
  338. do {
  339. TINY_GSM_YIELD();
  340. while (stream.available() > 0) {
  341. int a = streamRead();
  342. if (a <= 0) continue; // Skip 0x00 bytes, just in case
  343. data += (char)a;
  344. if (r1 && data.endsWith(r1)) {
  345. index = 1;
  346. goto finish;
  347. } else if (r2 && data.endsWith(r2)) {
  348. index = 2;
  349. goto finish;
  350. } else if (r3 && data.endsWith(r3)) {
  351. index = 3;
  352. goto finish;
  353. } else if (r4 && data.endsWith(r4)) {
  354. index = 4;
  355. goto finish;
  356. } else if (r5 && data.endsWith(r5)) {
  357. index = 5;
  358. goto finish;
  359. }
  360. }
  361. } while (millis() - startMillis < timeout);
  362. finish:
  363. if (!index) {
  364. data.trim();
  365. data.replace(GSM_NL GSM_NL, GSM_NL);
  366. data.replace(GSM_NL, "\r\n" " ");
  367. if (data.length()) {
  368. DBG("### Unhandled:", data);
  369. }
  370. }
  371. else {
  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("<<< ", data, "\r\n");
  377. }
  378. }
  379. // if (gotData) {
  380. // sockets[mux]->sock_available = modemGetAvailable(mux);
  381. // }
  382. return index;
  383. }
  384. uint8_t waitResponse(uint32_t timeout,
  385. GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  386. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  387. {
  388. String data;
  389. return waitResponse(timeout, data, r1, r2, r3, r4, r5);
  390. }
  391. uint8_t waitResponse(GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  392. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  393. {
  394. return waitResponse(1000, r1, r2, r3, r4, r5);
  395. }
  396. private:
  397. int modemConnect(const char* host, uint16_t port, uint8_t mux = 1, bool isUDP=false) {
  398. sendAT(GF("LA"), host);
  399. String ipadd; ipadd.reserve(16);
  400. ipadd = streamReadUntil('\r');
  401. IPAddress ip;
  402. ip.fromString(ipadd);
  403. return modemConnect(ip, port, mux, isUDP);
  404. }
  405. int modemConnect(IPAddress ip, uint16_t port, uint8_t mux = 1, bool isUDP=false) {
  406. String host; host.reserve(16);
  407. host += ip[0];
  408. host += ".";
  409. host += ip[1];
  410. host += ".";
  411. host += ip[2];
  412. host += ".";
  413. host += ip[3];
  414. if (isUDP) {
  415. sendAT(GF("IP"), 0); // Put in UDP mode
  416. waitResponse();
  417. } else {
  418. sendAT(GF("IP"), 1); // Put in TCP mode
  419. waitResponse();
  420. }
  421. sendAT(GF("DL"), host);
  422. waitResponse();
  423. sendAT(GF("DE"), String(port, HEX));
  424. int rsp = waitResponse();
  425. return rsp;
  426. }
  427. int modemSend(const void* buff, size_t len, uint8_t mux = 1) {
  428. stream.write((uint8_t*)buff, len);
  429. return len;
  430. }
  431. bool modemGetConnected(uint8_t mux = 1) {
  432. commandMode();
  433. sendAT(GF("AI"));
  434. int res = waitResponse(GF("0"));
  435. exitCommand();
  436. return 1 == res;
  437. }
  438. /* Private Utilities */
  439. template<typename T>
  440. void streamWrite(T last) {
  441. stream.print(last);
  442. }
  443. template<typename T, typename... Args>
  444. void streamWrite(T head, Args... tail) {
  445. stream.print(head);
  446. streamWrite(tail...);
  447. }
  448. int streamRead() {
  449. int c = stream.read();
  450. DBG((char)c);
  451. return c;
  452. }
  453. String streamReadUntil(char c) {
  454. String return_string = stream.readStringUntil(c);
  455. return_string.trim();
  456. if (String(c) == GSM_NL){
  457. DBG(return_string, "\r\n");
  458. } else DBG(return_string, c);
  459. return return_string;
  460. }
  461. bool commandMode(void){
  462. delay(guardTime); // cannot send anything for 1 second before entering command mode
  463. streamWrite(GF("+++")); // enter command mode
  464. DBG("\r\n+++\r\n");
  465. waitResponse(guardTime);
  466. return 1 == waitResponse(1100); // wait another second for an "OK\r"
  467. }
  468. void writeChanges(void){
  469. sendAT(GF("WR")); // Write changes to flash
  470. waitResponse();
  471. sendAT(GF("AC")); // Apply changes
  472. waitResponse();
  473. }
  474. void exitCommand(void){
  475. sendAT(GF("CN")); // Exit command mode
  476. waitResponse();
  477. }
  478. private:
  479. int guardTime;
  480. Stream& stream;
  481. GsmClient* sockets[1];
  482. };
  483. typedef TinyGsm::GsmClient TinyGsmClient;
  484. #endif