Parser for AT commands and similar protocols

Dependencies:   BufferedSerial

Dependents:   ESP8266 xdot-passthru Lab_10 Lab9 ... more

Fork of ATParser by NetworkSocketAPI

Revision:
3:32915b9467d2
Parent:
2:4d68f546861c
Child:
4:38acbd6f9d9e
--- a/ATParser.cpp	Thu Jul 16 22:50:43 2015 +0000
+++ b/ATParser.cpp	Fri Jul 17 16:31:58 2015 +0000
@@ -66,8 +66,10 @@
     }
     
     // Finish with newline
-    if (_putc('\r') < 0 || _putc('\n') < 0)
-        return false;
+    for (int i = 0; _delimiter[i]; i++) {
+        if (_putc(_delimiter[i]) < 0)
+            return false;
+    }
     
 #ifdef AT_ECHO
     printf("AT> %s\r\n", line);
@@ -81,24 +83,19 @@
     
     while (i < size) {
         int c = _getc();
-            
         if (c < 0)
             return false;
+            
+        line[i++] = c;
         
         // Finish when we hit a newline
-        if (c == '\r' || c == '\n') {
-            // Only handle newlines on \n
-            if (c != '\n')
-                continue;
-            
-            line[i++] = 0;
-#ifdef AT_ECHO
+        if (memcmp(&line[i-_delim_size], _delimiter, _delim_size) == 0) {
+            line[i-_delim_size] = 0;
+#ifdef AT_ECHO            
             printf("AT< %s\r\n", line);
 #endif
             return true;
         }
-        
-        line[i++] = c;
     }
     
     // Ran out of space
@@ -113,10 +110,12 @@
     _flush();
     
     // Create and send command
-    if (vsprintf(_buffer, command, args) < 0 ||
-        !_putline(_buffer)) {
-        va_end(args);
-        return false;
+    if (command) {
+        if (vsprintf(_buffer, command, args) < 0 ||
+            !_putline(_buffer)) {
+            va_end(args);
+            return false;
+        }
     }
     
     // Iterate through each line in the expected response
@@ -129,19 +128,15 @@
         int offset = 0;
         
         while (response[i]) {
-            // Only handle newlines on \n
-            if (response[i] == '\n') {
-                i++;
+            if (memcmp(&response[i-_delim_size], _delimiter, _delim_size) == 0) {
+                i += _delim_size;
                 break;
-            } else if (response[i] == '\r') {
-                i++;
             } else if (response[i] == '%' && 
                        response[i+1] != '%' && 
                        response[i+1] != '*') {
-                i++;
-                           
                 _buffer[offset++] = '%';
                 _buffer[offset++] = '*';
+                i++;
             } else {
                 _buffer[offset++] = response[i++];
             }