Cellular library for MTS Socket Modem Arduino Shield devices from Multi-Tech Systems
Dependents: mtsas mtsas mtsas mtsas
Diff: Cellular/Cellular.cpp
- Revision:
- 10:c188cc05aed5
- Parent:
- 9:1a03e3f3e7fe
- Child:
- 11:4e428f689069
--- a/Cellular/Cellular.cpp Wed May 21 15:39:35 2014 -0500 +++ b/Cellular/Cellular.cpp Wed May 21 15:45:05 2014 -0500 @@ -132,6 +132,94 @@ return sendSMS(sms.phoneNumber, sms.message); } +Code Cellular::sendBasicCommand(const std::string& command, unsigned int timeoutMillis, char esc) +{ + if(socketOpened) { + logError("socket is open. Can not send AT commands"); + return ERROR; + } + + string response = sendCommand(command, timeoutMillis, esc); + if (response.size() == 0) { + return NO_RESPONSE; + } else if (response.find("OK") != string::npos) { + return SUCCESS; + } else if (response.find("ERROR") != string::npos) { + return ERROR; + } else { + return FAILURE; + } +} + +string Cellular::sendCommand(const std::string& command, unsigned int timeoutMillis, char esc) +{ + if(io == NULL) { + logError("MTSBufferedIO not set"); + return ""; + } + if(socketOpened) { + logError("socket is open. Can not send AT commands"); + return ""; + } + + io->rxClear(); + io->txClear(); + std::string result; + + //Attempt to write command + if(io->write(command.data(), command.size(), timeoutMillis) != command.size()) { + //Failed to write command + if (command != "AT" && command != "at") { + logError("failed to send command to radio within %d milliseconds", timeoutMillis); + } + return ""; + } + + //Send Escape Character + if (esc != 0x00) { + if(io->write(esc, timeoutMillis) != 1) { + if (command != "AT" && command != "at") { + logError("failed to send character '%c' (0x%02X) to radio within %d milliseconds", esc, esc, timeoutMillis); + } + return ""; + } + } + + int timer = 0; + size_t previous = 0; + char tmp[256]; + tmp[255] = 0; + bool started = !echoMode; + bool done = false; + do { + wait(0.1); + timer += 100; + + previous = result.size(); + //Make a non-blocking read call by passing timeout of zero + int size = io->read(tmp,255,0); //1 less than allocated (timeout is instant) + if(size > 0) { + result.append(tmp, size); + } + if(!started) { + //In Echo Mode (Command will have echo'd + 2 characters for \r\n) + if(result.size() > command.size() + 2) { + started = true; + } + } else { + done = (result.size() == previous); + } + if(timer >= timeoutMillis) { + if (command != "AT" && command != "at") { + logWarning("sendCommand [%s] timed out after %d milliseconds", command.c_str(), timeoutMillis); + } + done = true; + } + } while (!done); + + return result; +} + Code Cellular::sendSMS(const std::string& phoneNumber, const std::string& message) { Code code = sendBasicCommand("AT+CMGF=1", 1000);