JsonHttpClient.ino 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  1. // Sample Arduino Json Web Client
  2. // Downloads and parse http://jsonplaceholder.typicode.com/users/1
  3. //
  4. // Copyright Benoit Blanchon 2014-2017
  5. // MIT License
  6. //
  7. // Arduino JSON library
  8. // https://bblanchon.github.io/ArduinoJson/
  9. // If you like this project, please add a star!
  10. #include <ArduinoJson.h>
  11. #include <Ethernet.h>
  12. #include <SPI.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. UserData userData;
  34. if (readReponseContent(&userData)) {
  35. printUserData(&userData);
  36. }
  37. }
  38. }
  39. disconnect();
  40. wait();
  41. }
  42. // Initialize Serial port
  43. void initSerial() {
  44. Serial.begin(BAUD_RATE);
  45. while (!Serial) {
  46. ; // wait for serial port to initialize
  47. }
  48. Serial.println("Serial ready");
  49. }
  50. // Initialize Ethernet library
  51. void initEthernet() {
  52. byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
  53. if (!Ethernet.begin(mac)) {
  54. Serial.println("Failed to configure Ethernet");
  55. return;
  56. }
  57. Serial.println("Ethernet ready");
  58. delay(1000);
  59. }
  60. // Open connection to the HTTP server
  61. bool connect(const char* hostName) {
  62. Serial.print("Connect to ");
  63. Serial.println(hostName);
  64. bool ok = client.connect(hostName, 80);
  65. Serial.println(ok ? "Connected" : "Connection Failed!");
  66. return ok;
  67. }
  68. // Send the HTTP GET request to the server
  69. bool sendRequest(const char* host, const char* resource) {
  70. Serial.print("GET ");
  71. Serial.println(resource);
  72. client.print("GET ");
  73. client.print(resource);
  74. client.println(" HTTP/1.0");
  75. client.print("Host: ");
  76. client.println(host);
  77. client.println("Connection: close");
  78. client.println();
  79. return true;
  80. }
  81. // Skip HTTP headers so that we are at the beginning of the response's body
  82. bool skipResponseHeaders() {
  83. // HTTP headers end with an empty line
  84. char endOfHeaders[] = "\r\n\r\n";
  85. client.setTimeout(HTTP_TIMEOUT);
  86. bool ok = client.find(endOfHeaders);
  87. if (!ok) {
  88. Serial.println("No response or invalid response!");
  89. }
  90. return ok;
  91. }
  92. // Parse the JSON from the input string and extract the interesting values
  93. // Here is the JSON we need to parse
  94. // {
  95. // "id": 1,
  96. // "name": "Leanne Graham",
  97. // "username": "Bret",
  98. // "email": "Sincere@april.biz",
  99. // "address": {
  100. // "street": "Kulas Light",
  101. // "suite": "Apt. 556",
  102. // "city": "Gwenborough",
  103. // "zipcode": "92998-3874",
  104. // "geo": {
  105. // "lat": "-37.3159",
  106. // "lng": "81.1496"
  107. // }
  108. // },
  109. // "phone": "1-770-736-8031 x56442",
  110. // "website": "hildegard.org",
  111. // "company": {
  112. // "name": "Romaguera-Crona",
  113. // "catchPhrase": "Multi-layered client-server neural-net",
  114. // "bs": "harness real-time e-markets"
  115. // }
  116. // }
  117. bool readReponseContent(struct UserData* userData) {
  118. // Compute optimal size of the JSON buffer according to what we need to parse.
  119. // See https://bblanchon.github.io/ArduinoJson/assistant/
  120. const size_t BUFFER_SIZE =
  121. JSON_OBJECT_SIZE(8) // the root object has 8 elements
  122. + JSON_OBJECT_SIZE(5) // the "address" object has 5 elements
  123. + JSON_OBJECT_SIZE(2) // the "geo" object has 2 elements
  124. + JSON_OBJECT_SIZE(3) // the "company" object has 3 elements
  125. + MAX_CONTENT_SIZE; // additional space for strings
  126. // Allocate a temporary memory pool
  127. DynamicJsonBuffer jsonBuffer(BUFFER_SIZE);
  128. JsonObject& root = jsonBuffer.parseObject(client);
  129. if (!root.success()) {
  130. Serial.println("JSON parsing failed!");
  131. return false;
  132. }
  133. // Here were copy the strings we're interested in
  134. strcpy(userData->name, root["name"]);
  135. strcpy(userData->company, root["company"]["name"]);
  136. // It's not mandatory to make a copy, you could just use the pointers
  137. // Since, they are pointing inside the "content" buffer, so you need to make
  138. // sure it's still in memory when you read the string
  139. return true;
  140. }
  141. // Print the data extracted from the JSON
  142. void printUserData(const struct UserData* userData) {
  143. Serial.print("Name = ");
  144. Serial.println(userData->name);
  145. Serial.print("Company = ");
  146. Serial.println(userData->company);
  147. }
  148. // Close the connection with the HTTP server
  149. void disconnect() {
  150. Serial.println("Disconnect");
  151. client.stop();
  152. }
  153. // Pause for a 1 minute
  154. void wait() {
  155. Serial.println("Wait 60 seconds");
  156. delay(60000);
  157. }