Analyzing ESP32 Code

Let’s analyze a short ESP32 Wifi code with DeepSeek R1

// https://docs.arduino.cc/libraries/httpclient/
// receiving JSON POST https://www.geeksforgeeks.org/how-to-receive-json-post-with-php/

#include <ArduinoJson.h>
#include <HTTPClient.h>
#include <WiFiMulti.h>

const char *AP_SSID = "AP_NAME";
const char *AP_PWD = "AP_PASSWORD";

void setup() {
  Serial.begin(115200);

  WiFi.begin(AP_SSID, AP_PWD);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi...");
  }
  Serial.println("Connected to WiFi");
  Serial.print("ESP32 Web Server's IP address: ");
  Serial.println(WiFi.localIP());
}

void loop() {
  postDataToServer();
  delay(10000);  // delay 10 seconds
}

int counter=0;

void postDataToServer() {

  Serial.println("Posting JSON data to server...");
  // Block until we are able to connect to the WiFi access point
  if (WiFi.status() == WL_CONNECTED) {

    HTTPClient http;

    http.begin("http://192.168.0.115/post_json.php");
    http.addHeader("Content-Type", "application/json");

    StaticJsonDocument<200> doc;
    // Add values in the document
    //
    doc["sensor"] = "gps";
    doc["time"] = 1351824120;
    doc["counter"] = counter;
    counter++;

    // Add an array.
    //
    JsonArray data = doc.createNestedArray("data");
    data.add(48.756080);
    data.add(2.302038);

    String requestBody;
    serializeJson(doc, requestBody);

    int httpResponseCode = http.POST(requestBody);

    if (httpResponseCode > 0) {

      String response = http.getString();

      Serial.println(httpResponseCode);
      Serial.println(response);

    } else {
      Serial.print("error code");
      Serial.print(httpResponseCode);
      // error codes from https://github.com/amcewen/HttpClient/blob/master/HttpClient.h
      // static const int HTTP_ERROR_CONNECTION_FAILED =-1;
      // static const int HTTP_ERROR_API =-2;
      // static const int HTTP_ERROR_TIMED_OUT =-3;
      // static const int HTTP_ERROR_INVALID_RESPONSE =-4;
    }
  }
}

Prompt

Analyze the following ESP32 code:

Chain of Thought

Okay, I’m trying to understand this ESP32 code that someone provided. Let me go through it step by step.

First, the code starts with some includes: ArduinoJson for handling JSON data, HTTPClient for making HTTP requests, and WiFiMulti for connecting to Wi-Fi. That makes sense because the code is sending data over the internet.

In the setup function, they initialize the serial port at 115200 baud. Then they try to connect to a Wi-Fi network using the SSID and password stored in AP_SSID and AP_PWD. There’s a while loop that waits until the connection is successful, printing dots or messages while waiting. Once connected, it prints the local IP address. That seems standard for ESP32 sketches.

Moving on to the loop function, it calls postDataToServer every 10 seconds. So this is where all the data sending happens periodically.

The postDataToServer function first checks if the WiFi connection is active. If so, it creates an HTTPClient object and starts a POST request to “http://192.168.0.115/post_json.php”. The Content-Type header is set to application/json, which is correct for sending JSON data.

They create a StaticJsonDocument with 200 bytes size. Then they add some key-value pairs: “sensor” as “gps”, “time” as a specific timestamp, and “counter” which increments each time. There’s also an array called “data” with two float values, probably latitude and longitude.

They serialize the JSON document into a String called requestBody. This is important because it converts the structured data into a string that can be sent over HTTP.

Then they send a POST request using http.POST(requestBody). The response code is stored in httpResponseCode. If the response code is positive (meaning success), they read the server’s response and print both the code and the message. Otherwise, they handle errors by printing an error code, which includes possible connection issues or timeouts.

I think this code should work if everything is set up correctly. The ESP32 connects to Wi-Fi, sends JSON data every 10 seconds, and handles responses or errors appropriately. But I wonder about a few things:

  1. Error handling: It checks for httpResponseCode > 0, but what are the possible success codes? Usually, 200 is OK, but other 2xx codes could also be valid. So maybe checking if it’s between 200 and 299 would be better.
  2. Buffer size: The StaticJsonDocument uses 200 bytes. If the JSON data grows larger than that, it might cause issues or overflow. Maybe dynamic memory allocation with JsonDocument could be safer, but I know that’s more complex.
  3. IP address and endpoint: They’re using a local IP (192.168.0.115) which is fine for testing on the same network. But in a real setup, they might want to use a public URL or set up port forwarding.
  4. Security: The Wi-Fi credentials are hardcoded. In production, it’s better to have them stored securely or read from another source without exposing them in the code.
  5. Memory management: Since it’s using StaticJsonDocument, which is allocated on the stack, and assuming 200 bytes is enough, but for larger data, this could be a problem.
  6. Counter variable: The counter increments each time postDataToServer is called, so it should correctly track how many times data has been sent. But since it’s an int, after about 4 billion increments, it would overflow. That’s probably not an issue here but something to consider for long-term use.
  7. Delay in loop: They have a delay of 10 seconds between each POST. This is manageable as the ESP32 can handle that without issues.

I think this code is a good starting point for sending JSON data from ESP32 to a server. It covers connecting to Wi-Fi, creating and sending JSON, handling HTTP responses, and error checking. However, there might be improvements in terms of robustness, security, and resource management depending on the specific use case.

If I were to run this code, I’d need to make sure my ESP32 is connected to the same network as the server running post_json.php at 192.168.0.115. Also, I should have PHP installed and set up correctly on that server to handle incoming POST requests and process the JSON data.

Another thing to note is that in some environments, especially if the ESP32 is behind a router or firewall, the POST request might be blocked unless the necessary ports are open. So ensuring that the server is accessible from the ESP32’s network is crucial.

I think I’ve covered the main points of this code. It seems straightforward but effective for its intended purpose.

Answer

The provided ESP32 code is designed to connect to a Wi-Fi network, periodically send JSON data via an HTTP POST request to a specified server endpoint, and handle responses or errors accordingly. Here’s a detailed analysis:

Key Components and Functionality:

  1. Wi-Fi Connection Setup:
    • The sketch connects to a predefined Wi-Fi network using AP_SSID (SSID) and AP_PWD (password).
    • It waits until the connection is established, printing status messages during the process.
  2. HTTP POST Request with JSON Data:
    • Every 10 seconds, postDataToServer() sends a POST request to “http://192.168.0.115/post_json.php”.
    • A JSON payload is constructed with fields including sensor type, timestamp, counter (incrementing each time), and an array of two float values.
  3. JSON Construction:
    • Uses ArduinoJson library to build a JSON document, ensuring structured data before serialization into a string for transmission.
  4. Response Handling:
    • The server’s response is captured if the HTTP request succeeds (indicated by a positive status code).
    • Error codes are logged if the request fails, providing insight into potential issues like connection problems or timeouts.

Considerations and Enhancements:

  • Error Code Handling: While the current implementation checks for positive responses, it might benefit from handling specific success ranges (e.g., 200-299) to better interpret server responses.
  • Buffer Management: The StaticJsonDocument<200> uses a fixed buffer size. If the JSON data exceeds this, consider using dynamic memory allocation with DynamicJsonDocument for scalability.
  • Network Configuration: Ensure the server at 192.168.0.115 is reachable from the ESP32’s network. For external access, use a public URL and configure port forwarding if necessary.
  • Security Practices: Avoid hardcoding sensitive information like Wi-Fi credentials in production. Consider secure storage methods or alternative credential retrieval mechanisms.
  • Memory Concerns: Be mindful of buffer sizes to prevent overflow, especially with larger datasets.
  • Counter Management: The integer counter will eventually overflow after ~4 billion increments. Depending on usage duration, consider using a larger data type or reset mechanism.

Conclusion:

This code effectively demonstrates sending JSON data from an ESP32 to a server via HTTP POST. It is suitable for testing and small-scale applications but may require enhancements for production environments, such as improved security, robust error handling, and efficient memory management.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *