/** * @file TinyGsmClientSaraR4.h * @author Volodymyr Shymanskyy * @license LGPL-3.0 * @copyright Copyright (c) 2016 Volodymyr Shymanskyy * @date Nov 2016 */ #ifndef SRC_TINYGSMCLIENTSARAR4_H_ #define SRC_TINYGSMCLIENTSARAR4_H_ // #pragma message("TinyGSM: TinyGsmClientSaraR4") // #define TINY_GSM_DEBUG Serial #define TINY_GSM_MUX_COUNT 7 #define TINY_GSM_BUFFER_READ_AND_CHECK_SIZE #include "TinyGsmBattery.tpp" #include "TinyGsmGPRS.tpp" #include "TinyGsmGPS.tpp" #include "TinyGsmGSMLocation.tpp" #include "TinyGsmModem.tpp" #include "TinyGsmSMS.tpp" #include "TinyGsmSSL.tpp" #include "TinyGsmTCP.tpp" #include "TinyGsmTemperature.tpp" #include "TinyGsmTime.tpp" #define GSM_NL "\r\n" static const char GSM_OK[] TINY_GSM_PROGMEM = "OK" GSM_NL; static const char GSM_ERROR[] TINY_GSM_PROGMEM = "ERROR" GSM_NL; #if defined TINY_GSM_DEBUG static const char GSM_CME_ERROR[] TINY_GSM_PROGMEM = GSM_NL "+CME ERROR:"; #endif enum RegStatus { REG_NO_RESULT = -1, REG_UNREGISTERED = 0, REG_SEARCHING = 2, REG_DENIED = 3, REG_OK_HOME = 1, REG_OK_ROAMING = 5, REG_UNKNOWN = 4, }; class TinyGsmSaraR4 : public TinyGsmModem, public TinyGsmGPRS, public TinyGsmTCP, public TinyGsmSSL, public TinyGsmBattery, public TinyGsmGSMLocation, public TinyGsmGPS, public TinyGsmSMS, public TinyGsmTemperature, public TinyGsmTime { friend class TinyGsmModem; friend class TinyGsmGPRS; friend class TinyGsmTCP; friend class TinyGsmSSL; friend class TinyGsmBattery; friend class TinyGsmGSMLocation; friend class TinyGsmGPS; friend class TinyGsmSMS; friend class TinyGsmTemperature; friend class TinyGsmTime; /* * Inner Client */ public: class GsmClientSaraR4 : public GsmClient { friend class TinyGsmSaraR4; public: GsmClientSaraR4() {} explicit GsmClientSaraR4(TinyGsmSaraR4& modem, uint8_t mux = 0) { init(&modem, mux); } bool init(TinyGsmSaraR4* modem, uint8_t mux = 0) { this->at = modem; sock_available = 0; prev_check = 0; sock_connected = false; got_data = false; if (mux < TINY_GSM_MUX_COUNT) { this->mux = mux; } else { this->mux = (mux % TINY_GSM_MUX_COUNT); } at->sockets[this->mux] = this; return true; } public: virtual int connect(const char* host, uint16_t port, int timeout_s) { // stop(); // DON'T stop! TINY_GSM_YIELD(); rx.clear(); uint8_t oldMux = mux; sock_connected = at->modemConnect(host, port, &mux, false, timeout_s); if (mux != oldMux) { DBG("WARNING: Mux number changed from", oldMux, "to", mux); at->sockets[oldMux] = NULL; } at->sockets[mux] = this; at->maintain(); return sock_connected; } virtual int connect(IPAddress ip, uint16_t port, int timeout_s) { return connect(TinyGsmStringFromIp(ip).c_str(), port, timeout_s); } int connect(const char* host, uint16_t port) override { return connect(host, port, 120); } int connect(IPAddress ip, uint16_t port) override { return connect(ip, port, 120); } void stop(uint32_t maxWaitMs) { uint32_t startMillis = millis(); dumpModemBuffer(maxWaitMs); // We want to use an async socket close because the syncrhonous close of // an open socket is INCREDIBLY SLOW and the modem can freeze up. But we // only attempt the async close if we already KNOW the socket is open // because calling the async close on a closed socket and then attempting // opening a new socket causes the board to lock up for 2-3 minutes and // then finally return with a "new" socket that is immediately closed. // Attempting to close a socket that is already closed with a synchronous // close quickly returns an error. if (at->supportsAsyncSockets && sock_connected) { DBG("### Closing socket asynchronously! Socket might remain open " "until arrival of +UUSOCL:", mux); // faster asynchronous close // NOT supported on SARA-R404M / SARA-R410M-01B at->sendAT(GF("+USOCL="), mux, GF(",1")); // NOTE: can take up to 120s to get a response at->waitResponse((maxWaitMs - (millis() - startMillis))); // We set the sock as disconnected right away because it can no longer // be used sock_connected = false; } else { // synchronous close at->sendAT(GF("+USOCL="), mux); // NOTE: can take up to 120s to get a response at->waitResponse((maxWaitMs - (millis() - startMillis))); sock_connected = false; } } void stop() override { stop(135000L); } /* * Extended API */ String remoteIP() TINY_GSM_ATTR_NOT_IMPLEMENTED; }; /* * Inner Secure Client */ public: class GsmClientSecureR4 : public GsmClientSaraR4 { public: GsmClientSecureR4() {} explicit GsmClientSecureR4(TinyGsmSaraR4& modem, uint8_t mux = 0) : GsmClientSaraR4(modem, mux) {} public: int connect(const char* host, uint16_t port, int timeout_s) override { // stop(); // DON'T stop! TINY_GSM_YIELD(); rx.clear(); uint8_t oldMux = mux; sock_connected = at->modemConnect(host, port, &mux, true, timeout_s); if (mux != oldMux) { DBG("WARNING: Mux number changed from", oldMux, "to", mux); at->sockets[oldMux] = NULL; } at->sockets[mux] = this; at->maintain(); return sock_connected; } int connect(IPAddress ip, uint16_t port, int timeout_s) override { return connect(TinyGsmStringFromIp(ip).c_str(), port, timeout_s); } int connect(const char* host, uint16_t port) override { return connect(host, port, 120); } int connect(IPAddress ip, uint16_t port) override { return connect(ip, port, 120); } }; /* * Constructor */ public: explicit TinyGsmSaraR4(Stream& stream) : stream(stream), has2GFallback(false), supportsAsyncSockets(false) { memset(sockets, 0, sizeof(sockets)); } /* * Basic functions */ protected: bool initImpl(const char* pin = NULL) { DBG(GF("### TinyGSM Version:"), TINYGSM_VERSION); DBG(GF("### TinyGSM Compiled Module: TinyGsmClientSaraR4")); if (!testAT()) { return false; } sendAT(GF("E0")); // Echo Off if (waitResponse() != 1) { return false; } #ifdef TINY_GSM_DEBUG sendAT(GF("+CMEE=2")); // turn on verbose error codes #else sendAT(GF("+CMEE=0")); // turn off error codes #endif waitResponse(); String modemName = getModemName(); DBG(GF("### Modem:"), modemName); if (modemName.startsWith("u-blox SARA-R412")) { has2GFallback = true; } else { has2GFallback = false; } if (modemName.startsWith("u-blox SARA-R404M") || modemName.startsWith("u-blox SARA-R410M-01B")) { supportsAsyncSockets = false; } else { supportsAsyncSockets = true; } // Enable automatic time zome update sendAT(GF("+CTZU=1")); if (waitResponse(10000L) != 1) { return false; } SimStatus ret = getSimStatus(); // if the sim isn't ready and a pin has been provided, try to unlock the sim if (ret != SIM_READY && pin != NULL && strlen(pin) > 0) { simUnlock(pin); return (getSimStatus() == SIM_READY); } else { // if the sim is ready, or it's locked but no pin has been provided, // return true return (ret == SIM_READY || ret == SIM_LOCKED); } } // only difference in implementation is the warning on the wrong type String getModemNameImpl() { sendAT(GF("+CGMI")); String res1; if (waitResponse(1000L, res1) != 1) { return "u-blox Cellular Modem"; } res1.replace(GSM_NL "OK" GSM_NL, ""); res1.trim(); sendAT(GF("+GMM")); String res2; if (waitResponse(1000L, res2) != 1) { return "u-blox Cellular Modem"; } res2.replace(GSM_NL "OK" GSM_NL, ""); res2.trim(); String name = res1 + String(' ') + res2; DBG("### Modem:", name); if (!name.startsWith("u-blox SARA-R4") && !name.startsWith("u-blox SARA-N4")) { DBG("### WARNING: You are using the wrong TinyGSM modem!"); } return name; } bool factoryDefaultImpl() { sendAT(GF("&F")); // Resets the current profile, other NVM not affected return waitResponse() == 1; } /* * Power functions */ protected: // using +CFUN=15 instead of the more common CFUN=1,1 bool restartImpl() { if (!testAT()) { return false; } sendAT(GF("+CFUN=15")); if (waitResponse(10000L) != 1) { return false; } delay(3000); // TODO(?): Verify delay timing here return init(); } bool powerOffImpl() { sendAT(GF("+CPWROFF")); return waitResponse(40000L) == 1; } bool sleepEnableImpl(bool enable = true) TINY_GSM_ATTR_NOT_AVAILABLE; /* * Generic network functions */ public: RegStatus getRegistrationStatus() { // Check first for EPS registration RegStatus epsStatus = (RegStatus)getRegistrationStatusXREG("CEREG"); // If we're connected on EPS, great! if (epsStatus == REG_OK_HOME || epsStatus == REG_OK_ROAMING) { return epsStatus; } else { // Otherwise, check generic network status return (RegStatus)getRegistrationStatusXREG("CREG"); } } protected: bool isNetworkConnectedImpl() { RegStatus s = getRegistrationStatus(); return (s == REG_OK_HOME || s == REG_OK_ROAMING); } public: bool setURAT(uint8_t urat) { // AT+URAT=[,[,<2ndPreferredAct>]] sendAT(GF("+COPS=2")); // Deregister from network if (waitResponse() != 1) { return false; } sendAT(GF("+URAT="), urat); // Radio Access Technology (RAT) selection if (waitResponse() != 1) { return false; } sendAT(GF("+COPS=0")); // Auto-register to the network if (waitResponse() != 1) { return false; } return restart(); } /* * GPRS functions */ protected: bool gprsConnectImpl(const char* apn, const char* user = NULL, const char* pwd = NULL) { // gprsDisconnect(); sendAT(GF("+CGATT=1")); // attach to GPRS if (waitResponse(360000L) != 1) { return false; } // Using CGDCONT sets up an "external" PCP context, i.e. a data connection // using the external IP stack (e.g. Windows dial up) and PPP link over the // serial interface. This is the only command set supported by the LTE-M // and LTE NB-IoT modules (SARA-R4xx, SARA-N4xx) // Set the authentication if (user && strlen(user) > 0) { sendAT(GF("+CGAUTH=1,0,\""), user, GF("\",\""), pwd, '"'); waitResponse(); } sendAT(GF("+CGDCONT=1,\"IP\",\""), apn, '"'); // Define PDP context 1 waitResponse(); sendAT(GF("+CGACT=1,1")); // activate PDP profile/context 1 if (waitResponse(150000L) != 1) { return false; } return true; } bool gprsDisconnectImpl() { // Mark all the sockets as closed // This ensures that asynchronously closed sockets are marked closed for (int mux = 0; mux < TINY_GSM_MUX_COUNT; mux++) { GsmClientSaraR4* sock = sockets[mux]; if (sock && sock->sock_connected) { sock->sock_connected = false; } } // sendAT(GF("+CGACT=0,1")); // Deactivate PDP context 1 sendAT(GF("+CGACT=0")); // Deactivate all contexts if (waitResponse(40000L) != 1) { // return false; } sendAT(GF("+CGATT=0")); // detach from GPRS if (waitResponse(360000L) != 1) { return false; } return true; } /* * SIM card functions */ protected: // This uses "CGSN" instead of "GSN" String getIMEIImpl() { sendAT(GF("+CGSN")); if (waitResponse(GF(GSM_NL)) != 1) { return ""; } String res = stream.readStringUntil('\n'); waitResponse(); res.trim(); return res; } /* * Messaging functions */ protected: String sendUSSDImpl(const String& code) TINY_GSM_ATTR_NOT_IMPLEMENTED; bool sendSMS_UTF16Impl(const String& number, const void* text, size_t len) TINY_GSM_ATTR_NOT_IMPLEMENTED; /* * GSM/GPS/GNSS/GLONASS Location functions * NOTE: u-blox modules use the same function to get location data from both * GSM tower triangulation and from dedicated GPS/GNSS/GLONASS receivers. The * only difference in which sensor the data is requested from. If a GNSS * location is requested from a modem without a GNSS receiver installed on the * I2C port, the GSM-based "Cell Locate" location will be returned instead. */ protected: bool enableGPSImpl() { // AT+UGPS=[,[,]] // - 0: GNSS receiver powered off, 1: on // - 0: no aiding (default) // - 3: GPS + SBAS (default) sendAT(GF("+UGPS=1,0,3")); if (waitResponse(10000L, GF(GSM_NL "+UGPS:")) != 1) { return false; } return waitResponse(10000L) == 1; } bool disableGPSImpl() { sendAT(GF("+UGPS=0")); if (waitResponse(10000L, GF(GSM_NL "+UGPS:")) != 1) { return false; } return waitResponse(10000L) == 1; } String inline getUbloxLocationRaw(int8_t sensor) { // AT+ULOC=,,,, // - 2: single shot position // - 0: use the last fix in the internal database and stop the GNSS // receiver // - 1: use the GNSS receiver for localization // - 2: use cellular CellLocate location information // - 3: ?? use the combined GNSS receiver and CellLocate service // information ?? - Docs show using sensor 3 and it's // documented for the +UTIME command but not for +ULOC // - 0: standard (single-hypothesis) response // - Timeout period in seconds // - Target accuracy in meters (1 - 999999) sendAT(GF("+ULOC=2,"), sensor, GF(",0,120,1")); // wait for first "OK" if (waitResponse(10000L) != 1) { return ""; } // wait for the final result - wait full timeout time if (waitResponse(120000L, GF(GSM_NL "+UULOC:")) != 1) { return ""; } String res = stream.readStringUntil('\n'); waitResponse(); res.trim(); return res; } String getGsmLocationRawImpl() { return getUbloxLocationRaw(2); } String getGPSrawImpl() { return getUbloxLocationRaw(1); } inline bool getUbloxLocation(int8_t sensor, float* lat, float* lon, float* speed = 0, float* alt = 0, int* vsat = 0, int* usat = 0, float* accuracy = 0, int* year = 0, int* month = 0, int* day = 0, int* hour = 0, int* minute = 0, int* second = 0) { // AT+ULOC=,,,, // - 2: single shot position // - 2: use cellular CellLocate location information // - 0: use the last fix in the internal database and stop the GNSS // receiver // - 1: use the GNSS receiver for localization // - 3: ?? use the combined GNSS receiver and CellLocate service // information ?? - Docs show using sensor 3 and it's documented // for the +UTIME command but not for +ULOC // - 0: standard (single-hypothesis) response // - Timeout period in seconds // - Target accuracy in meters (1 - 999999) sendAT(GF("+ULOC=2,"), sensor, GF(",0,120,1")); // wait for first "OK" if (waitResponse(10000L) != 1) { return false; } // wait for the final result - wait full timeout time if (waitResponse(120000L, GF(GSM_NL "+UULOC: ")) != 1) { return false; } // +UULOC: ,