Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Make aJson parser more robust to come with malformed input

The original parser does not cope gracefully with input that is
not proper json. Try sending "Hi there" to any of the library
examples and see the results.

This commit adds two things:
 - the "getch" method now times out after 500ms. This removes the
   situation whereby the parser got often stuck waiting forever on
   malformed input.
 - A new "flush" method is added, because the parser leaves the
   input buffer untouched in case it cannot understand the contents,
   which means that it will get stuck forever again trying to parse
   the same input if we try several times.
  • Loading branch information...
commit 6a98353b1fd4aafb35bd566097e68a3335e49b3f 1 parent 9b3e717
@elafargue elafargue authored
Showing with 23 additions and 1 deletion.
  1. +21 −1 aJSON.cpp
  2. +2 −0  aJSON.h
View
22 aJSON.cpp
@@ -78,7 +78,12 @@ aJsonStream::getch()
bucket = EOF;
return ret;
}
- while (!stream()->available()) /* spin */;
+ // In case input was malformed - can happen, this is the
+ // real world, we can end up in a situation where the parser
+ // would expect another character and end up stuck on
+ // stream()->available() forever, hence the 500ms timeout.
+ unsigned long i= millis()+500;
+ while ((!stream()->available()) && (millis() < i)) /* spin with a timeout*/;
return stream()->read();
}
@@ -493,6 +498,21 @@ aJsonStream::skip()
return EOF;
}
+// Utility to flush our buffer in case it contains garbage
+// since the parser will return the buffer untouched if it
+// cannot understand it.
+int
+aJsonStream::flush()
+{
+ int in = this->getch();
+ while(in != EOF)
+ {
+ in = this->getch();
+ }
+ return EOF;
+}
+
+
// Parse an object - create a new root, and populate.
aJsonObject*
aJsonClass::parse(char *value)
View
2  aJSON.h
@@ -28,6 +28,7 @@
#include <Print.h>
#include <Stream.h>
#include <Client.h>
+#include <Arduino.h> // To get access to the Arduino millis() function
/******************************************************************************
* Definitions
@@ -87,6 +88,7 @@ class aJsonStream : public Print {
int printString(aJsonObject *item);
int skip();
+ int flush();
int parseValue(aJsonObject *item, char** filter);
int printValue(aJsonObject *item);
Please sign in to comment.
Something went wrong with that request. Please try again.