diff --git a/src/GSMClient.cpp b/src/GSMClient.cpp index 24a6254..62dcd57 100644 --- a/src/GSMClient.cpp +++ b/src/GSMClient.cpp @@ -51,7 +51,9 @@ GSMClient::GSMClient(int socket, bool synch) : _host(NULL), _port(0), _ssl(false), - _writeSync(true) + _writeSync(true), + _connectTimeout(30000UL), + _socketTimeout(15000UL) { MODEM.addUrcHandler(this); } @@ -233,7 +235,13 @@ int GSMClient::connect() } if (_synch) { - while (ready() == 0); + unsigned long start = millis(); + while (ready() == 0) { + if (_connectTimeout && !((millis() - start) < _connectTimeout)) { + stop(); + return 2; + } + } } else if (ready() == 0) { return 0; } @@ -241,7 +249,13 @@ int GSMClient::connect() _state = CLIENT_STATE_CREATE_SOCKET; if (_synch) { + unsigned long start = millis(); while (ready() == 0) { + if (_connectTimeout && !((millis() - start) < _connectTimeout)) { + stop(); + return 2; + } + delay(100); } @@ -271,7 +285,13 @@ size_t GSMClient::write(const uint8_t *buf) size_t GSMClient::write(const uint8_t* buf, size_t size) { if (_writeSync) { - while (ready() == 0); + unsigned long start = millis(); + while (ready() == 0) { + if (_socketTimeout && !((millis() - start) < _socketTimeout)) { + stop(); + return 0; + } + } } else if (ready() == 0) { return 0; } @@ -385,7 +405,13 @@ int GSMClient::read() int GSMClient::available() { if (_synch) { - while (ready() == 0); + unsigned long start = millis(); + while (ready() == 0) { + if (_socketTimeout && !((millis() - start) < _socketTimeout)) { + stop(); + return 0; + } + } } else if (ready() == 0) { return 0; } @@ -434,6 +460,16 @@ void GSMClient::stop() _connected = false; } +void GSMClient::setSocketTimeout(unsigned long timeout) +{ + _socketTimeout = timeout; +} + +void GSMClient::setConnectTimeout(unsigned long timeout) +{ + _connectTimeout = timeout; +} + void GSMClient::handleUrc(const String& urc) { if (urc.startsWith("+UUSORD: ")) { diff --git a/src/GSMClient.h b/src/GSMClient.h index 1455d58..547852f 100644 --- a/src/GSMClient.h +++ b/src/GSMClient.h @@ -128,6 +128,14 @@ class GSMClient : public Client, public ModemUrcHandler { */ void stop(); + /** Set timeout for connecting + */ + void setConnectTimeout(unsigned long timeout); + + /** Set timeout for socket operations + */ + void setSocketTimeout(unsigned long timeout); + virtual void handleUrc(const String& urc); private: @@ -145,6 +153,9 @@ class GSMClient : public Client, public ModemUrcHandler { bool _writeSync; String _response; + + unsigned long _connectTimeout; + unsigned long _socketTimeout; }; #endif