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.

624 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
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. return TinyGsmIpFromString(getLocalIP());
  329. }
  330. /*
  331. * GPRS functions
  332. */
  333. bool gprsConnect(const char* apn, const char* user = "", const char* pw = "") {
  334. commandMode();
  335. sendAT(GF("AN"), apn); // Set the APN
  336. waitResponse();
  337. writeChanges();
  338. exitCommand();
  339. return true;
  340. }
  341. bool gprsDisconnect() { // TODO
  342. return false;
  343. }
  344. /*
  345. * Messaging functions
  346. */
  347. void sendUSSD() {
  348. }
  349. void sendSMS() {
  350. }
  351. bool sendSMS(const String& number, const String& text) {
  352. commandMode();
  353. sendAT(GF("IP"), 2); // Put in text messaging mode
  354. waitResponse();
  355. sendAT(GF("PH"), number); // Set the phone number
  356. waitResponse();
  357. sendAT(GF("TDD")); // Set the text delimiter to the standard 0x0D (carriabe return)
  358. waitResponse();
  359. writeChanges();
  360. exitCommand();
  361. stream.print(text);
  362. stream.write((char)0x0D); // close off with the carriage return
  363. return true;
  364. }
  365. private:
  366. int modemConnect(const char* host, uint16_t port, uint8_t mux = 0) {
  367. sendAT(GF("LA"), host);
  368. String strIP; strIP.reserve(16);
  369. // wait for the response
  370. unsigned long startMillis = millis();
  371. while (stream.available() < 8 && millis() - startMillis < 30000) {};
  372. strIP = streamReadUntil('\r'); // read result
  373. IPAddress ip = TinyGsmIpFromString(strIP);
  374. return modemConnect(ip, port);
  375. }
  376. int modemConnect(IPAddress ip, uint16_t port, uint8_t mux = 0) {
  377. String host; host.reserve(16);
  378. host += ip[0];
  379. host += ".";
  380. host += ip[1];
  381. host += ".";
  382. host += ip[2];
  383. host += ".";
  384. host += ip[3];
  385. sendAT(GF("IP"), 1); // Put in TCP mode
  386. waitResponse();
  387. sendAT(GF("DL"), host); // Set the "Destination Address Low"
  388. waitResponse();
  389. sendAT(GF("DE"), String(port, HEX)); // Set the destination port
  390. int rsp = waitResponse();
  391. return rsp;
  392. }
  393. int modemSend(const void* buff, size_t len, uint8_t mux = 0) {
  394. stream.write((uint8_t*)buff, len);
  395. stream.flush();
  396. return len;
  397. }
  398. bool modemGetConnected(uint8_t mux = 0) {
  399. commandMode();
  400. if (beeType == S6B) sendAT(GF("AI"));
  401. else sendAT(GF("CI"));
  402. int res = waitResponse(GF("0"));
  403. exitCommand();
  404. return 1 == res;
  405. }
  406. public:
  407. /* Utilities */
  408. template<typename T>
  409. void streamWrite(T last) {
  410. stream.print(last);
  411. }
  412. template<typename T, typename... Args>
  413. void streamWrite(T head, Args... tail) {
  414. stream.print(head);
  415. streamWrite(tail...);
  416. }
  417. int streamRead() { return stream.read(); }
  418. String streamReadUntil(char c) {
  419. TINY_GSM_YIELD();
  420. String return_string = stream.readStringUntil(c);
  421. return_string.trim();
  422. if (String(c) == GSM_NL) {
  423. DBG(return_string, "\r\n");
  424. } else DBG(return_string, c);
  425. return return_string;
  426. }
  427. void streamClear(void) {
  428. while (stream.available()) { streamRead(); }
  429. }
  430. bool commandMode(void) {
  431. delay(guardTime); // cannot send anything for 1 second before entering command mode
  432. streamWrite(GF("+++")); // enter command mode
  433. DBG("\r\n+++\r\n");
  434. return 1 == waitResponse(guardTime*2);
  435. }
  436. void writeChanges(void) {
  437. sendAT(GF("WR")); // Write changes to flash
  438. waitResponse();
  439. sendAT(GF("AC")); // Apply changes
  440. waitResponse();
  441. }
  442. void exitCommand(void) {
  443. sendAT(GF("CN")); // Exit command mode
  444. waitResponse();
  445. }
  446. template<typename... Args>
  447. void sendAT(Args... cmd) {
  448. streamWrite("AT", cmd..., GSM_NL);
  449. stream.flush();
  450. TINY_GSM_YIELD();
  451. //DBG("### AT:", cmd...);
  452. }
  453. // TODO: Optimize this!
  454. uint8_t waitResponse(uint32_t timeout, String& data,
  455. GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  456. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  457. {
  458. /*String r1s(r1); r1s.trim();
  459. String r2s(r2); r2s.trim();
  460. String r3s(r3); r3s.trim();
  461. String r4s(r4); r4s.trim();
  462. String r5s(r5); r5s.trim();
  463. DBG("### ..:", r1s, ",", r2s, ",", r3s, ",", r4s, ",", r5s);*/
  464. data.reserve(64);
  465. int index = 0;
  466. unsigned long startMillis = millis();
  467. do {
  468. TINY_GSM_YIELD();
  469. while (stream.available() > 0) {
  470. int a = streamRead();
  471. if (a <= 0) continue; // Skip 0x00 bytes, just in case
  472. data += (char)a;
  473. if (r1 && data.endsWith(r1)) {
  474. index = 1;
  475. goto finish;
  476. } else if (r2 && data.endsWith(r2)) {
  477. index = 2;
  478. goto finish;
  479. } else if (r3 && data.endsWith(r3)) {
  480. index = 3;
  481. goto finish;
  482. } else if (r4 && data.endsWith(r4)) {
  483. index = 4;
  484. goto finish;
  485. } else if (r5 && data.endsWith(r5)) {
  486. index = 5;
  487. goto finish;
  488. }
  489. }
  490. } while (millis() - startMillis < timeout);
  491. finish:
  492. if (!index) {
  493. data.trim();
  494. data.replace(GSM_NL GSM_NL, GSM_NL);
  495. data.replace(GSM_NL, "\r\n" " ");
  496. if (data.length()) {
  497. DBG("### Unhandled:", data, "\r\n");
  498. } else {
  499. DBG("### NO RESPONSE!\r\n");
  500. }
  501. } else {
  502. data.trim();
  503. data.replace(GSM_NL GSM_NL, GSM_NL);
  504. data.replace(GSM_NL, "\r\n ");
  505. if (data.length()) {
  506. DBG("<<< ", data, "\r\n");
  507. }
  508. }
  509. return index;
  510. }
  511. uint8_t waitResponse(uint32_t timeout,
  512. GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  513. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  514. {
  515. String data;
  516. return waitResponse(timeout, data, r1, r2, r3, r4, r5);
  517. }
  518. uint8_t waitResponse(GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  519. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  520. {
  521. return waitResponse(1000, r1, r2, r3, r4, r5);
  522. }
  523. private:
  524. int guardTime;
  525. XBeeType beeType;
  526. Stream& stream;
  527. GsmClient* sockets[TINY_GSM_MUX_COUNT];
  528. };
  529. #endif