JsonHttpClient.ino 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  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. #include <ArduinoJson.h>
  11. #include <SPI.h>
  12. #include <Ethernet.h>
  13. EthernetClient client;
  14. const char* server = "jsonplaceholder.typicode.com"; // server's address
  15. const char* resource = "/users/1"; // http resource
  16. const unsigned long BAUD_RATE = 9600; // serial connection speed
  17. const unsigned long HTTP_TIMEOUT = 10000; // max respone time from server
  18. const size_t MAX_CONTENT_SIZE = 512; // max size of the HTTP response
  19. // The type of data that we want to extract from the page
  20. struct UserData {
  21. char name[32];
  22. char company[32];
  23. };
  24. // ARDUINO entry point #1: runs once when you press reset or power the board
  25. void setup() {
  26. initSerial();
  27. initEthernet();
  28. }
  29. // ARDUINO entry point #2: runs over and over again forever
  30. void loop() {
  31. if (connect(server)) {
  32. if (sendRequest(server, resource) && skipResponseHeaders()) {
  33. char response[MAX_CONTENT_SIZE];
  34. readReponseContent(response, sizeof(response));
  35. UserData userData;
  36. if (parseUserData(response, &userData)) {
  37. printUserData(&userData);
  38. }
  39. }
  40. disconnect();
  41. }
  42. wait();
  43. }
  44. // Initialize Serial port
  45. void initSerial() {
  46. Serial.begin(BAUD_RATE);
  47. while (!Serial) {
  48. ; // wait for serial port to initialize
  49. }
  50. Serial.println("Serial ready");
  51. }
  52. // Initialize Ethernet library
  53. void initEthernet() {
  54. byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
  55. if (!Ethernet.begin(mac)) {
  56. Serial.println("Failed to configure Ethernet");
  57. return;
  58. }
  59. Serial.println("Ethernet ready");
  60. delay(1000);
  61. }
  62. // Open connection to the HTTP server
  63. bool connect(const char* hostName) {
  64. Serial.print("Connect to ");
  65. Serial.println(hostName);
  66. bool ok = client.connect(hostName, 80);
  67. Serial.println(ok ? "Connected" : "Connection Failed!");
  68. return ok;
  69. }
  70. // Send the HTTP GET request to the server
  71. bool sendRequest(const char* host, const char* resource) {
  72. Serial.print("GET ");
  73. Serial.println(resource);
  74. client.print("GET ");
  75. client.print(resource);
  76. client.println(" HTTP/1.0");
  77. client.print("Host: ");
  78. client.println(server);
  79. client.println("Connection: close");
  80. client.println();
  81. return true;
  82. }
  83. // Skip HTTP headers so that we are at the beginning of the response's body
  84. bool skipResponseHeaders() {
  85. // HTTP headers end with an empty line
  86. char endOfHeaders[] = "\r\n\r\n";
  87. client.setTimeout(HTTP_TIMEOUT);
  88. bool ok = client.find(endOfHeaders);
  89. if (!ok) {
  90. Serial.println("No response or invalid response!");
  91. }
  92. return ok;
  93. }
  94. // Read the body of the response from the HTTP server
  95. void readReponseContent(char* content, size_t maxSize) {
  96. size_t length = client.readBytes(content, maxSize);
  97. content[length] = 0;
  98. Serial.println(content);
  99. }
  100. // Parse the JSON from the input string and extract the interesting values
  101. // Here is the JSON we need to parse
  102. // {
  103. // "id": 1,
  104. // "name": "Leanne Graham",
  105. // "username": "Bret",
  106. // "email": "Sincere@april.biz",
  107. // "address": {
  108. // "street": "Kulas Light",
  109. // "suite": "Apt. 556",
  110. // "city": "Gwenborough",
  111. // "zipcode": "92998-3874",
  112. // "geo": {
  113. // "lat": "-37.3159",
  114. // "lng": "81.1496"
  115. // }
  116. // },
  117. // "phone": "1-770-736-8031 x56442",
  118. // "website": "hildegard.org",
  119. // "company": {
  120. // "name": "Romaguera-Crona",
  121. // "catchPhrase": "Multi-layered client-server neural-net",
  122. // "bs": "harness real-time e-markets"
  123. // }
  124. // }
  125. bool parseUserData(char* content, struct UserData* userData) {
  126. // Compute optimal size of the JSON buffer according to what we need to parse.
  127. // This is only required if you use StaticJsonBuffer.
  128. const size_t BUFFER_SIZE =
  129. JSON_OBJECT_SIZE(8) // the root object has 8 elements
  130. + JSON_OBJECT_SIZE(5) // the "address" object has 5 elements
  131. + JSON_OBJECT_SIZE(2) // the "geo" object has 2 elements
  132. + JSON_OBJECT_SIZE(3); // the "company" object has 3 elements
  133. // Allocate a temporary memory pool on the stack
  134. StaticJsonBuffer<BUFFER_SIZE> jsonBuffer;
  135. // If the memory pool is too big for the stack, use this instead:
  136. // DynamicJsonBuffer jsonBuffer;
  137. JsonObject& root = jsonBuffer.parseObject(content);
  138. if (!root.success()) {
  139. Serial.println("JSON parsing failed!");
  140. return false;
  141. }
  142. // Here were copy the strings we're interested in
  143. strcpy(userData->name, root["name"]);
  144. strcpy(userData->company, root["company"]["name"]);
  145. // It's not mandatory to make a copy, you could just use the pointers
  146. // Since, they are pointing inside the "content" buffer, so you need to make
  147. // sure it's still in memory when you read the string
  148. return true;
  149. }
  150. // Print the data extracted from the JSON
  151. void printUserData(const struct UserData* userData) {
  152. Serial.print("Name = ");
  153. Serial.println(userData->name);
  154. Serial.print("Company = ");
  155. Serial.println(userData->company);
  156. }
  157. // Close the connection with the HTTP server
  158. void disconnect() {
  159. Serial.println("Disconnect");
  160. client.stop();
  161. }
  162. // Pause for a 1 minute
  163. void wait() {
  164. Serial.println("Wait 60 seconds");
  165. delay(60000);
  166. }