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.

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