Cellular library for MTS Socket Modem Arduino Shield devices from Multi-Tech Systems

Dependents:   mtsas mtsas mtsas mtsas

Revision:
11:4e428f689069
Parent:
2:10e72dce251d
Child:
18:fa0d8120f81f
diff -r c188cc05aed5 -r 4e428f689069 Utils/CellUtils.h
--- a/Utils/CellUtils.h	Wed May 21 15:45:05 2014 -0500
+++ b/Utils/CellUtils.h	Thu May 22 09:26:51 2014 -0500
@@ -1,6 +1,11 @@
 #ifndef CELLUTILS_H
 #define CELLUTILS_H
 
+#include "MTSBufferedIO.h"
+#include "MTSLog.h"
+
+using namespace mts;
+
 //Special Payload Character Constants (ASCII Values)
 const char ETX    = 0x03;   //Ends socket connection
 const char DLE    = 0x10;   //Escapes ETX and DLE within Payload
@@ -35,4 +40,60 @@
     }
 }
 
+static string sendCommand(MTSBufferedIO* io, const std::string& command, unsigned int timeoutMillis, char esc = CR)
+{
+    if(io == NULL) {
+        logError("MTSBufferedIO not set");
+        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 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);
+        }
+        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;
+}
+
 #endif