Advertisement
LrdArc

intip.in/arduinojson

Dec 19th, 2016
342
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.83 KB | None | 0 0
  1. // Sample Arduino Json Web Client
  2. // Downloads and parse http://jsonplaceholder.typicode.com/users/1
  3. //
  4. // Copyright Benoit Blanchon 2014-2016
  5. // MIT License
  6. //
  7. // Arduino JSON library
  8. // https://github.com/bblanchon/ArduinoJson
  9. // If you like this project, please add a star!
  10.  
  11. #include <ArduinoJson.h>
  12. #include <SPI.h>
  13. #include <Ethernet.h>
  14.  
  15. EthernetClient client;
  16. IPAddress ip(192, 168, 137, 2);
  17.  
  18. const char* server = "kp.intip.in"; // server's address
  19. const char* resource = "/api/tweetmin/aearc.json"; // http resource
  20. const unsigned long BAUD_RATE = 9600; // serial connection speed
  21. const unsigned long HTTP_TIMEOUT = 10000; // max respone time from server
  22. const size_t MAX_CONTENT_SIZE = 512; // max size of the HTTP response
  23.  
  24. // The type of data that we want to extract from the page
  25. struct UserData {
  26. char name[32];
  27. char company[32];
  28. };
  29.  
  30. // ARDUINO entry point #1: runs once when you press reset or power the board
  31. void setup() {
  32. initSerial();
  33. initEthernet();
  34. }
  35.  
  36. // ARDUINO entry point #2: runs over and over again forever
  37. void loop() {
  38. if (connect(server)) {
  39. if (sendRequest(server, resource) && skipResponseHeaders()) {
  40. char response[MAX_CONTENT_SIZE];
  41. readReponseContent(response, sizeof(response));
  42.  
  43. UserData userData;
  44. if (parseUserData(response, &userData)) {
  45. //printUserData(&userData);
  46. }
  47. }
  48. disconnect();
  49. }
  50. wait();
  51. }
  52.  
  53. // Initialize Serial port
  54. void initSerial() {
  55. Serial.begin(BAUD_RATE);
  56. while (!Serial) {
  57. ; // wait for serial port to initialize
  58. }
  59. Serial.println("Serial ready");
  60. }
  61.  
  62. // Initialize Ethernet library
  63. void initEthernet() {
  64. byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
  65. if (!Ethernet.begin(mac)) {
  66. Serial.println("Failed to configure Ethernet");
  67. return;
  68. }
  69. Serial.println("Ethernet ready");
  70. delay(1000);
  71. }
  72.  
  73. // Open connection to the HTTP server
  74. bool connect(const char* hostName) {
  75. Serial.print("Connect to ");
  76. Serial.println(hostName);
  77.  
  78. bool ok = client.connect(hostName, 80);
  79.  
  80. Serial.println(ok ? "Connected" : "Connection Failed!");
  81. return ok;
  82. }
  83.  
  84. // Send the HTTP GET request to the server
  85. bool sendRequest(const char* host, const char* resource) {
  86. Serial.print("GET ");
  87. Serial.println(resource);
  88.  
  89. client.print("GET ");
  90. client.print(resource);
  91. client.println(" HTTP/1.1");
  92. client.print("Host: ");
  93. client.println(server);
  94. client.println("Connection: close");
  95. client.println();
  96.  
  97. return true;
  98. }
  99.  
  100. // Skip HTTP headers so that we are at the beginning of the response's body
  101. bool skipResponseHeaders() {
  102. // HTTP headers end with an empty line
  103. char endOfHeaders[] = "\r\n\r\n";
  104.  
  105. client.setTimeout(HTTP_TIMEOUT);
  106. bool ok = client.find(endOfHeaders);
  107.  
  108. if (!ok) {
  109. Serial.println("No response or invalid response!");
  110. }
  111.  
  112. return ok;
  113. }
  114.  
  115. // Read the body of the response from the HTTP server
  116. void readReponseContent(char* content, size_t maxSize) {
  117. size_t length = client.readBytes(content, maxSize);
  118. content[length] = 0;
  119. //Serial.println(content);
  120. }
  121.  
  122. // Parse the JSON from the input string and extract the interesting values
  123. // Here is the JSON we need to parse
  124. // {
  125. // "id": 1,
  126. // "name": "Leanne Graham",
  127. // "username": "Bret",
  128. // "email": "Sincere@april.biz",
  129. // "address": {
  130. // "street": "Kulas Light",
  131. // "suite": "Apt. 556",
  132. // "city": "Gwenborough",
  133. // "zipcode": "92998-3874",
  134. // "geo": {
  135. // "lat": "-37.3159",
  136. // "lng": "81.1496"
  137. // }
  138. // },
  139. // "phone": "1-770-736-8031 x56442",
  140. // "website": "hildegard.org",
  141. // "company": {
  142. // "name": "Romaguera-Crona",
  143. // "catchPhrase": "Multi-layered client-server neural-net",
  144. // "bs": "harness real-time e-markets"
  145. // }
  146. // }
  147. bool parseUserData(char* content, struct UserData* userData) {
  148. // Compute optimal size of the JSON buffer according to what we need to parse.
  149. // This is only required if you use StaticJsonBuffer.
  150. const size_t BUFFER_SIZE =
  151. JSON_OBJECT_SIZE(8) // the root object has 8 elements
  152. + JSON_OBJECT_SIZE(5) // the "address" object has 5 elements
  153. + JSON_OBJECT_SIZE(2) // the "geo" object has 2 elements
  154. + JSON_OBJECT_SIZE(3); // the "company" object has 3 elements
  155.  
  156. // Allocate a temporary memory pool on the stack
  157. //StaticJsonBuffer<BUFFER_SIZE> jsonBuffer;
  158. // If the memory pool is too big for the stack, use this instead:
  159. DynamicJsonBuffer jsonBuffer;
  160.  
  161. // JsonObject& root = jsonBuffer.parseObject(content);
  162. JsonObject& root = jsonBuffer.parseObject(content);
  163.  
  164. if (!root.success()) {
  165. Serial.println("JSON parsing failed!");
  166. return false;
  167. }
  168.  
  169. //const char* bio = root["bio"];
  170. // Print values.
  171. //Serial.println( bio);
  172.  
  173. for ( int x=1; x<=2; x++ ) {
  174. String twit = root["tweet"][x-1]["tweet"];
  175. Serial.println( twit );
  176. if ( twit.indexOf( "afraid" ) != -1 ) Serial.println( "ada" );
  177. else Serial.println( "gak" );
  178. }
  179.  
  180. /*
  181. // Here were copy the strings we're interested in
  182. strcpy(userData->name, root["name"]);
  183. strcpy(userData->company, root["company"]["name"]);
  184. // It's not mandatory to make a copy, you could just use the pointers
  185. // Since, they are pointing inside the "content" buffer, so you need to make
  186. // sure it's still in memory when you read the string
  187. */
  188.  
  189. return true;
  190. }
  191.  
  192. // Print the data extracted from the JSON
  193. void printUserData(const struct UserData* userData) {
  194. Serial.print("Name = ");
  195. Serial.println(userData->name);
  196. Serial.print("Company = ");
  197. Serial.println(userData->company);
  198. }
  199.  
  200. // Close the connection with the HTTP server
  201. void disconnect() {
  202. Serial.println("Disconnect");
  203. client.stop();
  204. }
  205.  
  206. // Pause for a 1 minute
  207. void wait() {
  208. Serial.println("Wait 60 seconds");
  209. delay(60000);
  210. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement