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.

1068 lines
32 KiB

7 years ago
6 years ago
7 years ago
7 years ago
6 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, XBee module by Sara Damiano
  6. * @date Nov 2016
  7. */
  8. #ifndef TinyGsmClientXBee_h
  9. #define TinyGsmClientXBee_h
  10. //#pragma message("TinyGSM: TinyGsmClientXBee")
  11. //#define TINY_GSM_DEBUG Serial
  12. // XBee's do not support multi-plexing in transparent/command mode
  13. // The much more complicated API mode is needed for multi-plexing
  14. #define TINY_GSM_MUX_COUNT 1
  15. // XBee's have a default guard time of 1 second (1000ms, 10 extra for safety here)
  16. #define TINY_GSM_XBEE_GUARD_TIME 1010
  17. #include <TinyGsmCommon.h>
  18. #define GSM_NL "\r"
  19. static const char GSM_OK[] TINY_GSM_PROGMEM = "OK" GSM_NL;
  20. static const char GSM_ERROR[] TINY_GSM_PROGMEM = "ERROR" GSM_NL;
  21. enum SimStatus {
  22. SIM_ERROR = 0,
  23. SIM_READY = 1,
  24. SIM_LOCKED = 2,
  25. };
  26. enum RegStatus {
  27. REG_OK = 0,
  28. REG_UNREGISTERED = 1,
  29. REG_SEARCHING = 2,
  30. REG_DENIED = 3,
  31. REG_UNKNOWN = 4,
  32. };
  33. // These are responses to the HS command to get "hardware series"
  34. enum XBeeType {
  35. XBEE_UNKNOWN = 0,
  36. XBEE_S6B_WIFI = 0x601, // Digi XBee® Wi-Fi
  37. XBEE_LTE1_VZN = 0xB01, // Digi XBee® Cellular LTE Cat 1
  38. XBEE_3G = 0xB02, // Digi XBee® Cellular 3G
  39. XBEE3_LTE1_ATT = 0xB06, // Digi XBee3™ Cellular LTE CAT 1
  40. XBEE3_LTEM_ATT = 0xB08, // Digi XBee3™ Cellular LTE-M
  41. XBEE3_LTENB = 3, // Digi XBee3™ Cellular NB-IoT -- HS unknown to SRGD
  42. };
  43. class TinyGsmXBee : public TinyGsmModem
  44. {
  45. public:
  46. class GsmClient : public Client
  47. {
  48. friend class TinyGsmXBee;
  49. // typedef TinyGsmFifo<uint8_t, TINY_GSM_RX_BUFFER> RxFifo;
  50. public:
  51. GsmClient() {}
  52. GsmClient(TinyGsmXBee& modem, uint8_t mux = 0) {
  53. init(&modem, mux);
  54. }
  55. bool init(TinyGsmXBee* modem, uint8_t mux = 0) {
  56. this->at = modem;
  57. this->mux = mux;
  58. sock_connected = false;
  59. at->sockets[mux] = this;
  60. return true;
  61. }
  62. public:
  63. // NOTE: The XBee saves all paramter information in flash. When you turn it
  64. // on it immediately begins to re-connect to whatever was last connected to.
  65. // All the modemConnect() function does is tell it the paramters to put into
  66. // flash. The connection itself is not opened until you attempt to send data.
  67. // Because all settings are saved to flash, it is possible (or likely) that
  68. // you could send out data even if you haven't "made" any connection.
  69. virtual int connect(const char *host, uint16_t port) {
  70. at->streamClear(); // Empty anything in the buffer before starting
  71. if (at->commandMode()) { // Don't try if we didn't successfully get into command mode
  72. sock_connected = at->modemConnect(host, port, mux, false);
  73. at->writeChanges();
  74. at->exitCommand();
  75. }
  76. return sock_connected;
  77. }
  78. virtual int connect(IPAddress ip, uint16_t port) {
  79. at->streamClear(); // Empty anything in the buffer before starting
  80. if (at->commandMode()) { // Don't try if we didn't successfully get into command mode
  81. sock_connected = at->modemConnect(ip, port, mux, false);
  82. at->writeChanges();
  83. at->exitCommand();
  84. }
  85. return sock_connected;
  86. }
  87. virtual void stop() {
  88. at->streamClear(); // Empty anything in the buffer
  89. at->commandMode();
  90. // For WiFi models, there's no direct way to close the socket. This is a
  91. // hack to shut the socket by setting the timeout to zero.
  92. if (at->beeType == XBEE_S6B_WIFI) {
  93. at->sendAT(GF("TM0")); // Set socket timeout (using Digi default of 10 seconds)
  94. at->waitResponse(5000); // This response can be slow
  95. at->writeChanges();
  96. }
  97. // For cellular models, per documentation: If you change the TM (socket
  98. // timeout) value while in Transparent Mode, the current connection is
  99. // immediately closed.
  100. at->sendAT(GF("TM64")); // Set socket timeout (using Digi default of 10 seconds)
  101. at->waitResponse(5000); // This response can be slow
  102. at->writeChanges();
  103. at->exitCommand();
  104. at->streamClear(); // Empty anything remaining in the buffer
  105. sock_connected = false;
  106. // Note: because settings are saved in flash, the XBEE will attempt to
  107. // reconnect to the previous socket if it receives any outgoing data.
  108. // Setting sock_connected to false after the stop ensures that connected()
  109. // will return false after a stop has been ordered. This makes it play
  110. // much more nicely with libraries like PubSubClient.
  111. }
  112. virtual size_t write(const uint8_t *buf, size_t size) {
  113. TINY_GSM_YIELD();
  114. return at->modemSend(buf, size, mux);
  115. }
  116. virtual size_t write(uint8_t c) {
  117. return write(&c, 1);
  118. }
  119. virtual size_t write(const char *str) {
  120. if (str == NULL) return 0;
  121. return write((const uint8_t *)str, strlen(str));
  122. }
  123. virtual int available() {
  124. TINY_GSM_YIELD();
  125. return at->stream.available();
  126. /*
  127. if (!rx.size() || at->stream.available()) {
  128. at->maintain();
  129. }
  130. return at->stream.available() + rx.size();
  131. */
  132. }
  133. virtual int read(uint8_t *buf, size_t size) {
  134. TINY_GSM_YIELD();
  135. return at->stream.readBytes((char *)buf, size);
  136. /*
  137. size_t cnt = 0;
  138. uint32_t _startMillis = millis();
  139. while (cnt < size && millis() - _startMillis < _timeout) {
  140. size_t chunk = TinyGsmMin(size-cnt, rx.size());
  141. if (chunk > 0) {
  142. rx.get(buf, chunk);
  143. buf += chunk;
  144. cnt += chunk;
  145. continue;
  146. }
  147. // TODO: Read directly into user buffer?
  148. if (!rx.size() || at->stream.available()) {
  149. at->maintain();
  150. }
  151. }
  152. return cnt;
  153. */
  154. }
  155. virtual int read() {
  156. TINY_GSM_YIELD();
  157. return at->stream.read();
  158. /*
  159. uint8_t c;
  160. if (read(&c, 1) == 1) {
  161. return c;
  162. }
  163. return -1;
  164. */
  165. }
  166. virtual int peek() { return at->stream.peek(); }
  167. virtual void flush() { at->stream.flush(); }
  168. virtual uint8_t connected() {
  169. if (available()) {
  170. return true;
  171. }
  172. // Double check that we don't know it's closed
  173. // NOTE: modemGetConnected() is likely to return a "false" true because
  174. // it will return unknown until after data is sent over the connection.
  175. // If the socket is definitely closed, modemGetConnected() will set
  176. // sock_connected to false;
  177. at->modemGetConnected();
  178. return sock_connected;
  179. }
  180. virtual operator bool() { return connected(); }
  181. /*
  182. * Extended API
  183. */
  184. String remoteIP() TINY_GSM_ATTR_NOT_IMPLEMENTED;
  185. private:
  186. TinyGsmXBee* at;
  187. uint8_t mux;
  188. bool sock_connected;
  189. // RxFifo rx;
  190. };
  191. class GsmClientSecure : public GsmClient
  192. {
  193. public:
  194. GsmClientSecure() {}
  195. GsmClientSecure(TinyGsmXBee& modem, uint8_t mux = 0)
  196. : GsmClient(modem, mux)
  197. {}
  198. public:
  199. virtual int connect(const char *host, uint16_t port) {
  200. at->streamClear(); // Empty anything in the buffer before starting
  201. if (at->commandMode()) { // Don't try if we didn't successfully get into command mode
  202. sock_connected = at->modemConnect(host, port, mux, true);
  203. at->writeChanges();
  204. at->exitCommand();
  205. }
  206. return sock_connected;
  207. }
  208. virtual int connect(IPAddress ip, uint16_t port) {
  209. at->streamClear(); // Empty anything in the buffer before starting
  210. if (at->commandMode()) { // Don't try if we didn't successfully get into command mode
  211. sock_connected = at->modemConnect(ip, port, mux, false);
  212. at->writeChanges();
  213. at->exitCommand();
  214. }
  215. return sock_connected;
  216. }
  217. };
  218. public:
  219. TinyGsmXBee(Stream& stream)
  220. : TinyGsmModem(stream), stream(stream)
  221. {
  222. beeType = XBEE_UNKNOWN; // Start not knowing what kind of bee it is
  223. guardTime = TINY_GSM_XBEE_GUARD_TIME; // Start with the default guard time of 1 second
  224. resetPin = -1;
  225. savedIP = IPAddress(0,0,0,0);
  226. savedHost = "";
  227. memset(sockets, 0, sizeof(sockets));
  228. }
  229. TinyGsmXBee(Stream& stream, int8_t resetPin)
  230. : TinyGsmModem(stream), stream(stream)
  231. {
  232. beeType = XBEE_UNKNOWN; // Start not knowing what kind of bee it is
  233. guardTime = TINY_GSM_XBEE_GUARD_TIME; // Start with the default guard time of 1 second
  234. this->resetPin = resetPin;
  235. savedIP = IPAddress(0,0,0,0);
  236. savedHost = "";
  237. memset(sockets, 0, sizeof(sockets));
  238. }
  239. /*
  240. * Basic functions
  241. */
  242. bool init(const char* pin = NULL) {
  243. if (resetPin >= 0) {
  244. pinMode(resetPin, OUTPUT);
  245. digitalWrite(resetPin, HIGH);
  246. }
  247. if (!commandMode(10)) return false; // Try up to 10 times for the init
  248. sendAT(GF("AP0")); // Put in transparent mode
  249. bool ret_val = waitResponse() == 1;
  250. ret_val &= writeChanges();
  251. sendAT(GF("GT64")); // shorten the guard time to 100ms
  252. ret_val &= waitResponse();
  253. ret_val &= writeChanges();
  254. if (ret_val) guardTime = 110;
  255. getSeries(); // Get the "Hardware Series";
  256. exitCommand();
  257. return ret_val;
  258. }
  259. String getModemName() {
  260. return getBeeName();
  261. }
  262. void setBaud(unsigned long baud) {
  263. if (!commandMode()) return;
  264. switch(baud)
  265. {
  266. case 2400: sendAT(GF("BD1")); break;
  267. case 4800: sendAT(GF("BD2")); break;
  268. case 9600: sendAT(GF("BD3")); break;
  269. case 19200: sendAT(GF("BD4")); break;
  270. case 38400: sendAT(GF("BD5")); break;
  271. case 57600: sendAT(GF("BD6")); break;
  272. case 115200: sendAT(GF("BD7")); break;
  273. case 230400: sendAT(GF("BD8")); break;
  274. case 460800: sendAT(GF("BD9")); break;
  275. case 921600: sendAT(GF("BDA")); break;
  276. default: {
  277. DBG(GF("Specified baud rate is unsupported! Setting to 9600 baud."));
  278. sendAT(GF("BD3")); // Set to default of 9600
  279. break;
  280. }
  281. }
  282. waitResponse();
  283. writeChanges();
  284. exitCommand();
  285. }
  286. bool testAT(unsigned long timeout = 10000L) {
  287. for (unsigned long start = millis(); millis() - start < timeout; ) {
  288. if (commandMode())
  289. {
  290. sendAT();
  291. if (waitResponse(200) == 1) {
  292. exitCommand();
  293. return true;
  294. }
  295. }
  296. delay(100);
  297. }
  298. return false;
  299. }
  300. void maintain() {
  301. // this only happens OUTSIDE command mode, so if we're getting characters
  302. // they should be data received from the TCP connection
  303. // TINY_GSM_YIELD();
  304. // while (stream.available()) {
  305. // char c = stream.read();
  306. // if (c > 0) sockets[0]->rx.put(c);
  307. // }
  308. }
  309. bool factoryDefault() {
  310. if (!commandMode()) return false; // Return immediately
  311. sendAT(GF("RE"));
  312. bool ret_val = waitResponse() == 1;
  313. ret_val &= writeChanges();
  314. exitCommand();
  315. // Make sure the guard time for the modem object is set back to default
  316. // otherwise communication would fail after the reset
  317. guardTime = 1010;
  318. return ret_val;
  319. }
  320. String getModemInfo() {
  321. String modemInf = "";
  322. if (!commandMode()) return modemInf; // Try up to 10 times for the init
  323. sendAT(GF("HS")); // Get the "Hardware Series"
  324. modemInf += readResponseString();
  325. exitCommand();
  326. return modemInf;
  327. }
  328. bool hasSSL() {
  329. if (beeType == XBEE_S6B_WIFI) return false;
  330. else return true;
  331. }
  332. bool hasWifi() {
  333. if (beeType == XBEE_S6B_WIFI) return true;
  334. else return false;
  335. }
  336. bool hasGPRS() {
  337. if (beeType == XBEE_S6B_WIFI) return false;
  338. else return true;
  339. }
  340. XBeeType getBeeType() {
  341. return beeType;
  342. }
  343. String getBeeName() {
  344. switch (beeType){
  345. case XBEE_S6B_WIFI: return "Digi XBee® Wi-Fi";
  346. case XBEE_LTE1_VZN: return "Digi XBee® Cellular LTE Cat 1";
  347. case XBEE_3G: return "Digi XBee® Cellular 3G";
  348. case XBEE3_LTE1_ATT: return "Digi XBee3™ Cellular LTE CAT 1";
  349. case XBEE3_LTEM_ATT: return "Digi XBee3™ Cellular LTE-M";
  350. case XBEE3_LTENB: return "Digi XBee3™ Cellular NB-IoT";
  351. default: return "Digi XBee®";
  352. }
  353. }
  354. /*
  355. * Power functions
  356. */
  357. // The XBee's have a bad habit of getting into an unresponsive funk
  358. // This uses the board's hardware reset pin to force it to reset
  359. void pinReset() {
  360. if (resetPin >= 0) {
  361. DBG("### Forcing a modem reset!\r\n");
  362. digitalWrite(resetPin, LOW);
  363. delay(1);
  364. digitalWrite(resetPin, HIGH);
  365. }
  366. }
  367. bool restart() {
  368. if (!commandMode()) return false; // Return immediately
  369. if (beeType == XBEE_UNKNOWN) getSeries(); // how we restart depends on this
  370. if (beeType != XBEE_S6B_WIFI) {
  371. sendAT(GF("AM1")); // Digi suggests putting cellular modules into airplane mode before restarting
  372. // This allows the sockets and connections to close cleanly
  373. if (waitResponse() != 1) return exitAndFail();
  374. if (!writeChanges()) return exitAndFail();
  375. }
  376. sendAT(GF("FR"));
  377. if (waitResponse() != 1) return exitAndFail();
  378. if (beeType == XBEE_S6B_WIFI) delay(2000); // Wifi module actually resets about 2 seconds later
  379. else delay(100); // cellular modules wait 100ms before reset happes
  380. // Wait until reboot complete and responds to command mode call again
  381. for (unsigned long start = millis(); millis() - start < 60000L; ) {
  382. if (commandMode(1)) break;
  383. delay(250); // wait a litle before trying again
  384. }
  385. if (beeType != XBEE_S6B_WIFI) {
  386. sendAT(GF("AM0")); // Turn off airplane mode
  387. if (waitResponse() != 1) return exitAndFail();
  388. if (!writeChanges()) return exitAndFail();
  389. }
  390. exitCommand();
  391. return true;
  392. }
  393. void setupPinSleep(bool maintainAssociation = false) {
  394. if (!commandMode()) return; // Return immediately
  395. if (beeType == XBEE_UNKNOWN) getSeries(); // Command depends on series
  396. sendAT(GF("SM"),1); // Pin sleep
  397. waitResponse();
  398. if (beeType == XBEE_S6B_WIFI && !maintainAssociation) {
  399. sendAT(GF("SO"),200); // For lowest power, dissassociated deep sleep
  400. waitResponse();
  401. }
  402. else if (!maintainAssociation){
  403. sendAT(GF("SO"),1); // For supported cellular modules, maintain association
  404. // Not supported by all modules, will return "ERROR"
  405. waitResponse();
  406. }
  407. writeChanges();
  408. exitCommand();
  409. }
  410. bool poweroff() { // Not supported
  411. return false;
  412. }
  413. bool radioOff() TINY_GSM_ATTR_NOT_IMPLEMENTED;
  414. bool sleepEnable(bool enable = true) TINY_GSM_ATTR_NOT_IMPLEMENTED;
  415. /*
  416. * SIM card functions
  417. */
  418. bool simUnlock(const char *pin) { // Not supported
  419. return false;
  420. }
  421. String getSimCCID() {
  422. if (!commandMode()) return ""; // Return immediately
  423. sendAT(GF("S#"));
  424. String res = readResponseString();
  425. exitCommand();
  426. return res;
  427. }
  428. String getIMEI() {
  429. if (!commandMode()) return ""; // Return immediately
  430. sendAT(GF("IM"));
  431. String res = readResponseString();
  432. exitCommand();
  433. return res;
  434. }
  435. SimStatus getSimStatus(unsigned long timeout = 10000L) {
  436. return SIM_READY; // unsupported
  437. }
  438. RegStatus getRegistrationStatus() {
  439. if (!commandMode()) return REG_UNKNOWN; // Return immediately
  440. if (beeType == XBEE_UNKNOWN) getSeries(); // Need to know the bee type to interpret response
  441. sendAT(GF("AI"));
  442. int16_t intRes = readResponseInt();
  443. RegStatus stat = REG_UNKNOWN;
  444. switch (beeType){
  445. case XBEE_S6B_WIFI: {
  446. switch (intRes) {
  447. case 0x00: // 0x00 Successfully joined an access point, established IP addresses and IP listening sockets
  448. stat = REG_OK;
  449. break;
  450. case 0x01: // 0x01 Wi-Fi transceiver initialization in progress.
  451. case 0x02: // 0x02 Wi-Fi transceiver initialized, but not yet scanning for access point.
  452. case 0x40: // 0x40 Waiting for WPA or WPA2 Authentication.
  453. case 0x41: // 0x41 Device joined a network and is waiting for IP configuration to complete
  454. case 0x42: // 0x42 Device is joined, IP is configured, and listening sockets are being set up.
  455. case 0xFF: // 0xFF Device is currently scanning for the configured SSID.
  456. stat = REG_SEARCHING;
  457. break;
  458. case 0x13: // 0x13 Disconnecting from access point.
  459. restart(); // Restart the device; the S6B tends to get stuck "disconnecting"
  460. stat = REG_UNREGISTERED;
  461. break;
  462. case 0x23: // 0x23 SSID not configured.
  463. stat = REG_UNREGISTERED;
  464. break;
  465. case 0x24: // 0x24 Encryption key invalid (either NULL or invalid length for WEP).
  466. case 0x27: // 0x27 SSID was found, but join failed.
  467. stat = REG_DENIED;
  468. break;
  469. default:
  470. stat = REG_UNKNOWN;
  471. break;
  472. }
  473. break;
  474. }
  475. default: { // Cellular XBee's
  476. switch (intRes) {
  477. case 0x00: // 0x00 Connected to the Internet.
  478. stat = REG_OK;
  479. break;
  480. case 0x22: // 0x22 Registering to cellular network.
  481. case 0x23: // 0x23 Connecting to the Internet.
  482. case 0xFF: // 0xFF Initializing.
  483. stat = REG_SEARCHING;
  484. break;
  485. case 0x24: // 0x24 The cellular component is missing, corrupt, or otherwise in error.
  486. case 0x2B: // 0x2B USB Direct active.
  487. case 0x2C: // 0x2C Cellular component is in PSM (power save mode).
  488. stat = REG_UNKNOWN;
  489. break;
  490. case 0x25: // 0x25 Cellular network registration denied.
  491. stat = REG_DENIED;
  492. break;
  493. case 0x2A: // 0x2A Airplane mode.
  494. sendAT(GF("AM0")); // Turn off airplane mode
  495. waitResponse();
  496. writeChanges();
  497. stat = REG_UNKNOWN;
  498. break;
  499. case 0x2F: // 0x2F Bypass mode active.
  500. sendAT(GF("AP0")); // Set back to transparent mode
  501. waitResponse();
  502. writeChanges();
  503. stat = REG_UNKNOWN;
  504. break;
  505. default:
  506. stat = REG_UNKNOWN;
  507. break;
  508. }
  509. break;
  510. }
  511. }
  512. exitCommand();
  513. return stat;
  514. }
  515. String getOperator() {
  516. if (!commandMode()) return ""; // Return immediately
  517. sendAT(GF("MN"));
  518. String res = readResponseString();
  519. exitCommand();
  520. return res;
  521. }
  522. /*
  523. * Generic network functions
  524. */
  525. int16_t getSignalQuality() {
  526. if (!commandMode()) return 0; // Return immediately
  527. if (beeType == XBEE_UNKNOWN) getSeries(); // Need to know what type of bee so we know how to ask
  528. if (beeType == XBEE_S6B_WIFI) sendAT(GF("LM")); // ask for the "link margin" - the dB above sensitivity
  529. else sendAT(GF("DB")); // ask for the cell strength in dBm
  530. int16_t intRes = readResponseInt();
  531. exitCommand();
  532. if (beeType == XBEE3_LTEM_ATT && intRes == 105) intRes = 0; // tends to reply with "69" when signal is unknown
  533. if (beeType == XBEE_S6B_WIFI) return -93 + intRes; // the maximum sensitivity is -93dBm
  534. else return -1*intRes; // need to convert to negative number
  535. }
  536. bool isNetworkConnected() {
  537. RegStatus s = getRegistrationStatus();
  538. return (s == REG_OK);
  539. }
  540. bool waitForNetwork(unsigned long timeout = 60000L) {
  541. for (unsigned long start = millis(); millis() - start < timeout; ) {
  542. if (isNetworkConnected()) {
  543. return true;
  544. }
  545. delay(250); // per Neil H. - more stable with delay
  546. }
  547. return false;
  548. }
  549. /*
  550. * WiFi functions
  551. */
  552. bool networkConnect(const char* ssid, const char* pwd) {
  553. if (!commandMode()) return false; // return immediately
  554. //nh For no pwd don't set setscurity or pwd
  555. if (NULL == ssid ) return exitAndFail();
  556. if (NULL != pwd)
  557. {
  558. sendAT(GF("EE"), 2); // Set security to WPA2
  559. if (waitResponse() != 1) return exitAndFail();
  560. sendAT(GF("PK"), pwd);
  561. } else {
  562. sendAT(GF("EE"), 0); // Set No security
  563. }
  564. if (waitResponse() != 1) return exitAndFail();
  565. sendAT(GF("ID"), ssid);
  566. if (waitResponse() != 1) return exitAndFail();
  567. if (!writeChanges()) return exitAndFail();
  568. exitCommand();
  569. return true;
  570. }
  571. bool networkDisconnect() {
  572. if (!commandMode()) return false; // return immediately
  573. sendAT(GF("NR0")); // Do a network reset in order to disconnect
  574. // NOTE: On wifi modules, using a network reset will not
  575. // allow the same ssid to re-join without rebooting the module.
  576. int8_t res = (1 == waitResponse(5000));
  577. writeChanges();
  578. exitCommand();
  579. return res;
  580. }
  581. /*
  582. * IP Address functions
  583. */
  584. String getLocalIP() {
  585. if (!commandMode()) return ""; // Return immediately
  586. sendAT(GF("MY"));
  587. String IPaddr; IPaddr.reserve(16);
  588. // wait for the response - this response can be very slow
  589. IPaddr = readResponseString(30000);
  590. exitCommand();
  591. IPaddr.trim();
  592. return IPaddr;
  593. }
  594. /*
  595. * GPRS functions
  596. */
  597. bool gprsConnect(const char* apn, const char* user = NULL, const char* pwd = NULL) {
  598. if (!commandMode()) return false; // Return immediately
  599. sendAT(GF("AN"), apn); // Set the APN
  600. waitResponse();
  601. writeChanges();
  602. exitCommand();
  603. return true;
  604. }
  605. bool gprsDisconnect() {
  606. if (!commandMode()) return false; // return immediately
  607. sendAT(GF("AM1")); // Cheating and disconnecting by turning on airplane mode
  608. int8_t res = (1 == waitResponse(5000));
  609. writeChanges();
  610. sendAT(GF("AM0")); // Airplane mode off
  611. waitResponse(5000);
  612. writeChanges();
  613. exitCommand();
  614. return res;
  615. }
  616. bool isGprsConnected() {
  617. return isNetworkConnected();
  618. }
  619. /*
  620. * Messaging functions
  621. */
  622. String sendUSSD(const String& code) TINY_GSM_ATTR_NOT_IMPLEMENTED;
  623. bool sendSMS(const String& number, const String& text) {
  624. if (!commandMode()) return false; // Return immediately
  625. sendAT(GF("IP"), 2); // Put in text messaging mode
  626. if (waitResponse() !=1) return exitAndFail();
  627. sendAT(GF("PH"), number); // Set the phone number
  628. if (waitResponse() !=1) return exitAndFail();
  629. sendAT(GF("TDD")); // Set the text delimiter to the standard 0x0D (carriage return)
  630. if (waitResponse() !=1) return exitAndFail();
  631. if (!writeChanges()) return exitAndFail();
  632. exitCommand();
  633. streamWrite(text);
  634. stream.write((char)0x0D); // close off with the carriage return
  635. return true;
  636. }
  637. /*
  638. * Location functions
  639. */
  640. String getGsmLocation() TINY_GSM_ATTR_NOT_AVAILABLE;
  641. /*
  642. * Battery functions
  643. */
  644. uint16_t getBattVoltage() TINY_GSM_ATTR_NOT_AVAILABLE;
  645. int8_t getBattPercent() TINY_GSM_ATTR_NOT_AVAILABLE;
  646. /*
  647. * Client related functions
  648. */
  649. protected:
  650. IPAddress getHostIP(const char* host) {
  651. String strIP; strIP.reserve(16);
  652. unsigned long startMillis = millis();
  653. bool gotIP = false;
  654. // XBee's require a numeric IP address for connection, but do provide the
  655. // functionality to look up the IP address from a fully qualified domain name
  656. while (millis() - startMillis < 45000L) // the lookup can take a while
  657. {
  658. sendAT(GF("LA"), host);
  659. while (stream.available() < 4 && (millis() - startMillis < 45000L)) {}; // wait for any response
  660. strIP = stream.readStringUntil('\r'); // read result
  661. strIP.trim();
  662. if (!strIP.endsWith(GF("ERROR"))) {
  663. gotIP = true;
  664. break;
  665. }
  666. delay(2500); // wait a bit before trying again
  667. }
  668. if (gotIP) { // No reason to continue if we don't know the IP address
  669. return TinyGsmIpFromString(strIP);
  670. }
  671. else return IPAddress(0,0,0,0);
  672. }
  673. bool modemConnect(const char* host, uint16_t port, uint8_t mux = 0, bool ssl = false) {
  674. // If requested host is the same as the previous one and we already
  675. // have a valid IP address, we don't have to do anything.
  676. if (this->savedHost == String(host) && savedIP != IPAddress(0,0,0,0)) {
  677. return true;
  678. }
  679. // Otherwise, set the new host and mark the IP as invalid
  680. this->savedHost = String(host);
  681. savedIP = getHostIP(host); // This will return 0.0.0.0 if lookup fails
  682. // If we now have a valid IP address, use it to connect
  683. if (savedIP != IPAddress(0,0,0,0)) { // Only re-set connection information if we have an IP address
  684. return modemConnect(savedIP, port, mux, ssl);
  685. }
  686. else return false;
  687. }
  688. bool modemConnect(IPAddress ip, uint16_t port, uint8_t mux = 0, bool ssl = false) {
  689. savedIP = ip; // Set the newly requested IP address
  690. bool success = true;
  691. String host; host.reserve(16);
  692. host += ip[0];
  693. host += ".";
  694. host += ip[1];
  695. host += ".";
  696. host += ip[2];
  697. host += ".";
  698. host += ip[3];
  699. if (ssl) {
  700. sendAT(GF("IP"), 4); // Put in SSL over TCP communication mode
  701. success &= (1 == waitResponse());
  702. } else {
  703. sendAT(GF("IP"), 1); // Put in TCP mode
  704. success &= (1 == waitResponse());
  705. }
  706. sendAT(GF("DL"), host); // Set the "Destination Address Low"
  707. success &= (1 == waitResponse());
  708. sendAT(GF("DE"), String(port, HEX)); // Set the destination port
  709. success &= (1 == waitResponse());
  710. return success;
  711. }
  712. int16_t modemSend(const void* buff, size_t len, uint8_t mux = 0) {
  713. stream.write((uint8_t*)buff, len);
  714. stream.flush();
  715. return len;
  716. }
  717. // NOTE: The CI command returns the status of the TCP connection as open only
  718. // after data has been sent on the socket. If it returns 0xFF the socket may
  719. // really be open, but no data has yet been sent. We return this unknown value
  720. // as true so there's a possibility it's wrong.
  721. bool modemGetConnected() {
  722. if (!commandMode()) return false; // Return immediately
  723. // If the IP address is 0, it's not valid so we can't be connected
  724. if (savedIP == IPAddress(0,0,0,0)) return false;
  725. // Verify that we're connected to the *right* IP address
  726. // We might be connected - but to the wrong thing
  727. // NOTE: In transparent mode, there is only one connection possible - no multiplex
  728. String strIP; strIP.reserve(16);
  729. sendAT(GF("DL"));
  730. strIP = stream.readStringUntil('\r'); // read result
  731. if (TinyGsmIpFromString(strIP) != savedIP) return exitAndFail();
  732. if (beeType == XBEE_UNKNOWN) getSeries(); // Need to know the bee type to interpret response
  733. switch (beeType){ // The wifi be can only say if it's connected to the netowrk
  734. case XBEE_S6B_WIFI: {
  735. RegStatus s = getRegistrationStatus();
  736. if (s != REG_OK) {
  737. sockets[0]->sock_connected = false;
  738. }
  739. return (s == REG_OK); // if it's connected, we hope the sockets are too
  740. }
  741. default: { // Cellular XBee's
  742. sendAT(GF("CI"));
  743. int16_t intRes = readResponseInt();
  744. exitCommand();
  745. switch(intRes) {
  746. case 0x00: // 0x00 = The socket is definitely open
  747. case 0xFF: // 0xFF = No known status - this is always returned prior to sending data
  748. return true;
  749. case 0x02: // 0x02 = Invalid parameters (bad IP/host)
  750. case 0x12: // 0x12 = DNS query lookup failure
  751. case 0x25: // 0x25 = Unknown server - DNS lookup failed (0x22 for UDP socket!)
  752. savedIP = IPAddress(0,0,0,0); // force a lookup next time!
  753. default: // If it's anything else (inc 0x02, 0x12, and 0x25)...
  754. sockets[0]->sock_connected = false; // ...it's definitely NOT connected
  755. return false;
  756. }
  757. }
  758. }
  759. }
  760. public:
  761. /*
  762. Utilities
  763. */
  764. void streamClear(void) {
  765. while (stream.available()) {
  766. stream.read();
  767. TINY_GSM_YIELD();
  768. }
  769. }
  770. template<typename... Args>
  771. void sendAT(Args... cmd) {
  772. streamWrite("AT", cmd..., GSM_NL);
  773. stream.flush();
  774. TINY_GSM_YIELD();
  775. //DBG("### AT:", cmd...);
  776. }
  777. // TODO: Optimize this!
  778. // NOTE: This function is used while INSIDE command mode, so we're only
  779. // waiting for requested responses. The XBee has no unsoliliced responses
  780. // (URC's) when in command mode.
  781. uint8_t waitResponse(uint32_t timeout, String& data,
  782. GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  783. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  784. {
  785. /*String r1s(r1); r1s.trim();
  786. String r2s(r2); r2s.trim();
  787. String r3s(r3); r3s.trim();
  788. String r4s(r4); r4s.trim();
  789. String r5s(r5); r5s.trim();
  790. DBG("### ..:", r1s, ",", r2s, ",", r3s, ",", r4s, ",", r5s);*/
  791. data.reserve(16); // Should never be getting much here for the XBee
  792. int8_t index = 0;
  793. unsigned long startMillis = millis();
  794. do {
  795. TINY_GSM_YIELD();
  796. while (stream.available() > 0) {
  797. int a = stream.read();
  798. if (a <= 0) continue; // Skip 0x00 bytes, just in case
  799. data += (char)a;
  800. if (r1 && data.endsWith(r1)) {
  801. index = 1;
  802. goto finish;
  803. } else if (r2 && data.endsWith(r2)) {
  804. index = 2;
  805. goto finish;
  806. } else if (r3 && data.endsWith(r3)) {
  807. index = 3;
  808. goto finish;
  809. } else if (r4 && data.endsWith(r4)) {
  810. index = 4;
  811. goto finish;
  812. } else if (r5 && data.endsWith(r5)) {
  813. index = 5;
  814. goto finish;
  815. }
  816. }
  817. } while (millis() - startMillis < timeout);
  818. finish:
  819. if (!index) {
  820. data.trim();
  821. data.replace(GSM_NL GSM_NL, GSM_NL);
  822. data.replace(GSM_NL, "\r\n ");
  823. if (data.length()) {
  824. DBG("### Unhandled:", data, "\r\n");
  825. } else {
  826. DBG("### NO RESPONSE FROM MODEM!\r\n");
  827. }
  828. } else {
  829. data.trim();
  830. data.replace(GSM_NL GSM_NL, GSM_NL);
  831. data.replace(GSM_NL, "\r\n ");
  832. if (data.length()) {
  833. }
  834. }
  835. //DBG('<', index, '>');
  836. return index;
  837. }
  838. uint8_t waitResponse(uint32_t timeout,
  839. GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  840. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  841. {
  842. String data;
  843. return waitResponse(timeout, data, r1, r2, r3, r4, r5);
  844. }
  845. uint8_t waitResponse(GsmConstStr r1=GFP(GSM_OK), GsmConstStr r2=GFP(GSM_ERROR),
  846. GsmConstStr r3=NULL, GsmConstStr r4=NULL, GsmConstStr r5=NULL)
  847. {
  848. return waitResponse(1000, r1, r2, r3, r4, r5);
  849. }
  850. bool commandMode(uint8_t retries = 3) {
  851. uint8_t triesMade = 0;
  852. uint8_t triesUntilReset = 2; // only reset after 2 failures
  853. bool success = false;
  854. streamClear(); // Empty everything in the buffer before starting
  855. while (!success and triesMade < retries) {
  856. // Cannot send anything for 1 "guard time" before entering command mode
  857. // Default guard time is 1s, but the init fxn decreases it to 250 ms
  858. delay(guardTime);
  859. streamWrite(GF("+++")); // enter command mode
  860. int res = waitResponse(guardTime*2);
  861. success = (1 == res);
  862. if (0 == res) {
  863. triesUntilReset--;
  864. if (triesUntilReset == 0) {
  865. triesUntilReset = 2;
  866. pinReset(); // if it's unresponsive, reset
  867. delay(250); // a short delay to allow it to come back up TODO-optimize this
  868. }
  869. }
  870. triesMade ++;
  871. }
  872. return success;
  873. }
  874. bool writeChanges(void) {
  875. sendAT(GF("WR")); // Write changes to flash
  876. if (1 != waitResponse()) return false;
  877. sendAT(GF("AC")); // Apply changes
  878. if (1 != waitResponse()) return false;
  879. return true;
  880. }
  881. void exitCommand(void) {
  882. sendAT(GF("CN")); // Exit command mode
  883. waitResponse();
  884. }
  885. bool exitAndFail(void) {
  886. exitCommand(); // Exit command mode
  887. return false;
  888. }
  889. void getSeries(void) {
  890. sendAT(GF("HS")); // Get the "Hardware Series";
  891. int16_t intRes = readResponseInt();
  892. beeType = (XBeeType)intRes;
  893. DBG(GF("### Modem: "), getModemName());
  894. }
  895. String readResponseString(uint32_t timeout = 1000) {
  896. TINY_GSM_YIELD();
  897. unsigned long startMillis = millis();
  898. while (!stream.available() && millis() - startMillis < timeout) {};
  899. String res = stream.readStringUntil('\r'); // lines end with carriage returns
  900. res.trim();
  901. return res;
  902. }
  903. int16_t readResponseInt(uint32_t timeout = 1000) {
  904. String res = readResponseString(timeout); // it just works better reading a string first
  905. char buf[5] = {0,};
  906. res.toCharArray(buf, 5);
  907. int16_t intRes = strtol(buf, 0, 16);
  908. return intRes;
  909. }
  910. public:
  911. Stream& stream;
  912. protected:
  913. int16_t guardTime;
  914. int8_t resetPin;
  915. XBeeType beeType;
  916. IPAddress savedIP;
  917. String savedHost;
  918. GsmClient* sockets[TINY_GSM_MUX_COUNT];
  919. };
  920. #endif