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.

621 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 testAT(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. sendAT(GF("AI"));
  229. // wait for the response
  230. unsigned long startMillis = millis();
  231. while (!stream.available() && millis() - startMillis < 1000) {};
  232. String res = streamReadUntil('\r'); // Does not send an OK, just the result
  233. exitCommand();
  234. if(res == GF("0"))
  235. return REG_OK_HOME;
  236. else if(res == GF("13") || res == GF("2A"))
  237. return REG_UNREGISTERED;
  238. else if(res == GF("FF") || res == GF("22") || res == GF("23") ||
  239. res == GF("40") || res == GF("41") || res == GF("42"))
  240. return REG_SEARCHING;
  241. else if(res == GF("24") || res == GF("25") || res == GF("27"))
  242. return REG_DENIED;
  243. else return REG_UNKNOWN;
  244. }
  245. String getOperator() {
  246. commandMode();
  247. sendAT(GF("MN"));
  248. // wait for the response
  249. unsigned long startMillis = millis();
  250. while (!stream.available() && millis() - startMillis < 1000) {};
  251. String res = streamReadUntil('\r'); // Does not send an OK, just the result
  252. exitCommand();
  253. return res;
  254. }
  255. /*
  256. * Generic network functions
  257. */
  258. int getSignalQuality() {
  259. commandMode();
  260. if (beeType == S6B) sendAT(GF("LM")); // ask for the "link margin" - the dB above sensitivity
  261. else sendAT(GF("DB")); // ask for the cell strenght in dBm
  262. // wait for the response
  263. unsigned long startMillis = millis();
  264. while (!stream.available() && millis() - startMillis < 1000) {};
  265. char buf[2] = {0}; // Set up buffer for response
  266. buf[0] = streamRead();
  267. buf[1] = streamRead();
  268. DBG(buf[0], buf[1], "\n");
  269. exitCommand();
  270. int intr = strtol(buf, 0, 16);
  271. if (beeType == S6B) return -93 + intr; // the maximum sensitivity is -93dBm
  272. else return -1*intr; // need to convert to negative number
  273. }
  274. bool waitForNetwork(unsigned long timeout = 60000L) {
  275. for (unsigned long start = millis(); millis() - start < timeout; ) {
  276. commandMode();
  277. sendAT(GF("AI"));
  278. // wait for the response
  279. unsigned long startMillis = millis();
  280. while (!stream.available() && millis() - startMillis < 1000) {};
  281. String res = streamReadUntil('\r'); // Does not send an OK, just the result
  282. exitCommand();
  283. if (res == GF("0")) {
  284. return true;
  285. }
  286. delay(1000);
  287. }
  288. return false;
  289. }
  290. /*
  291. * WiFi functions
  292. */
  293. bool networkConnect(const char* ssid, const char* pwd) {
  294. commandMode();
  295. sendAT(GF("EE"), 2); // Set security to WPA2
  296. waitResponse();
  297. sendAT(GF("ID"), ssid);
  298. if (waitResponse() != 1) {
  299. goto fail;
  300. }
  301. sendAT(GF("PK"), pwd);
  302. if (waitResponse() != 1) {
  303. goto fail;
  304. }
  305. writeChanges();
  306. exitCommand();
  307. return true;
  308. fail:
  309. exitCommand();
  310. return false;
  311. }
  312. bool networkDisconnect() {
  313. return false; // Doesn't support disconnecting
  314. }
  315. String getLocalIP() {
  316. commandMode();
  317. sendAT(GF("MY"));
  318. String IPaddr; IPaddr.reserve(16);
  319. // wait for the response
  320. unsigned long startMillis = millis();
  321. while (stream.available() < 8 && millis() - startMillis < 30000) {};
  322. IPaddr = streamReadUntil('\r'); // read result
  323. return IPaddr;
  324. }
  325. IPAddress localIP() {
  326. return TinyGsmIpFromString(getLocalIP());
  327. }
  328. /*
  329. * GPRS functions
  330. */
  331. bool gprsConnect(const char* apn, const char* user = "", const char* pw = "") {
  332. commandMode();
  333. sendAT(GF("AN"), apn); // Set the APN
  334. waitResponse();
  335. writeChanges();
  336. exitCommand();
  337. return true;
  338. }
  339. bool gprsDisconnect() { // TODO
  340. return false;
  341. }
  342. /*
  343. * Messaging functions
  344. */
  345. void sendUSSD() {
  346. }
  347. void sendSMS() {
  348. }
  349. bool sendSMS(const String& number, const String& text) {
  350. commandMode();
  351. sendAT(GF("IP"), 2); // Put in text messaging mode
  352. waitResponse();
  353. sendAT(GF("PH"), number); // Set the phone number
  354. waitResponse();
  355. sendAT(GF("TDD")); // Set the text delimiter to the standard 0x0D (carriabe return)
  356. waitResponse();
  357. writeChanges();
  358. exitCommand();
  359. stream.print(text);
  360. stream.write((char)0x0D); // close off with the carriage return
  361. return true;
  362. }
  363. private:
  364. int modemConnect(const char* host, uint16_t port, uint8_t mux = 0) {
  365. sendAT(GF("LA"), host);
  366. String strIP; strIP.reserve(16);
  367. // wait for the response
  368. unsigned long startMillis = millis();
  369. while (stream.available() < 8 && millis() - startMillis < 30000) {};
  370. strIP = streamReadUntil('\r'); // read result
  371. IPAddress ip = TinyGsmIpFromString(strIP);
  372. return modemConnect(ip, port);
  373. }
  374. int modemConnect(IPAddress ip, uint16_t port, uint8_t mux = 0) {
  375. String host; host.reserve(16);
  376. host += ip[0];
  377. host += ".";
  378. host += ip[1];
  379. host += ".";
  380. host += ip[2];
  381. host += ".";
  382. host += ip[3];
  383. sendAT(GF("IP"), 1); // Put in TCP mode
  384. waitResponse();
  385. sendAT(GF("DL"), host); // Set the "Destination Address Low"
  386. waitResponse();
  387. sendAT(GF("DE"), String(port, HEX)); // Set the destination port
  388. int rsp = waitResponse();
  389. return rsp;
  390. }
  391. int modemSend(const void* buff, size_t len, uint8_t mux = 0) {
  392. stream.write((uint8_t*)buff, len);
  393. stream.flush();
  394. return len;
  395. }
  396. bool modemGetConnected(uint8_t mux = 0) {
  397. commandMode();
  398. sendAT(GF("AI"));
  399. int res = waitResponse(GF("0"));
  400. exitCommand();
  401. return 1 == res;
  402. }
  403. public:
  404. /* Utilities */
  405. template<typename T>
  406. void streamWrite(T last) {
  407. stream.print(last);
  408. }
  409. template<typename T, typename... Args>
  410. void streamWrite(T head, Args... tail) {
  411. stream.print(head);
  412. streamWrite(tail...);
  413. }
  414. int streamRead() { return stream.read(); }
  415. String streamReadUntil(char c) {
  416. TINY_GSM_YIELD();
  417. String return_string = stream.readStringUntil(c);
  418. return_string.trim();
  419. if (String(c) == GSM_NL) {
  420. DBG(return_string, "\r\n");
  421. } else DBG(return_string, c);
  422. return return_string;
  423. }
  424. void streamClear(void) {
  425. while (stream.available()) { streamRead(); }
  426. }
  427. bool commandMode(void) {
  428. delay(guardTime); // cannot send anything for 1 second before entering command mode
  429. streamWrite(GF("+++")); // enter command mode
  430. DBG("\r\n+++\r\n");
  431. return 1 == waitResponse(guardTime*2);
  432. }
  433. void writeChanges(void) {
  434. sendAT(GF("WR")); // Write changes to flash
  435. waitResponse();
  436. sendAT(GF("AC")); // Apply changes
  437. waitResponse();
  438. }
  439. void exitCommand(void) {
  440. sendAT(GF("CN")); // Exit command mode
  441. waitResponse();
  442. }
  443. template<typename... Args>
  444. void sendAT(Args... cmd) {
  445. streamWrite("AT", cmd..., GSM_NL);
  446. stream.flush();
  447. TINY_GSM_YIELD();
  448. //DBG("### AT:", cmd...);
  449. }
  450. // TODO: Optimize this!
  451. uint8_t waitResponse(uint32_t timeout, String& data,
  452. GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  453. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  454. {
  455. /*String r1s(r1); r1s.trim();
  456. String r2s(r2); r2s.trim();
  457. String r3s(r3); r3s.trim();
  458. String r4s(r4); r4s.trim();
  459. String r5s(r5); r5s.trim();
  460. DBG("### ..:", r1s, ",", r2s, ",", r3s, ",", r4s, ",", r5s);*/
  461. data.reserve(64);
  462. int index = 0;
  463. unsigned long startMillis = millis();
  464. do {
  465. TINY_GSM_YIELD();
  466. while (stream.available() > 0) {
  467. int a = streamRead();
  468. if (a <= 0) continue; // Skip 0x00 bytes, just in case
  469. data += (char)a;
  470. if (r1 && data.endsWith(r1)) {
  471. index = 1;
  472. goto finish;
  473. } else if (r2 && data.endsWith(r2)) {
  474. index = 2;
  475. goto finish;
  476. } else if (r3 && data.endsWith(r3)) {
  477. index = 3;
  478. goto finish;
  479. } else if (r4 && data.endsWith(r4)) {
  480. index = 4;
  481. goto finish;
  482. } else if (r5 && data.endsWith(r5)) {
  483. index = 5;
  484. goto finish;
  485. }
  486. }
  487. } while (millis() - startMillis < timeout);
  488. finish:
  489. if (!index) {
  490. data.trim();
  491. data.replace(GSM_NL GSM_NL, GSM_NL);
  492. data.replace(GSM_NL, "\r\n" " ");
  493. if (data.length()) {
  494. DBG("### Unhandled:", data, "\r\n");
  495. } else {
  496. DBG("### NO RESPONSE!\r\n");
  497. }
  498. } else {
  499. data.trim();
  500. data.replace(GSM_NL GSM_NL, GSM_NL);
  501. data.replace(GSM_NL, "\r\n ");
  502. if (data.length()) {
  503. DBG("<<< ", data, "\r\n");
  504. }
  505. }
  506. return index;
  507. }
  508. uint8_t waitResponse(uint32_t timeout,
  509. GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  510. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  511. {
  512. String data;
  513. return waitResponse(timeout, data, r1, r2, r3, r4, r5);
  514. }
  515. uint8_t waitResponse(GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  516. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  517. {
  518. return waitResponse(1000, r1, r2, r3, r4, r5);
  519. }
  520. private:
  521. int guardTime;
  522. XBeeType beeType;
  523. Stream& stream;
  524. GsmClient* sockets[TINY_GSM_MUX_COUNT];
  525. };
  526. #endif