Search code examples
pythonc++httpesp32

How to send string to ESP32 using http


My python code which should be sending the "message"

import requests
r = requests.post('http://192.168.0.100:7777',data="Hello")
print(r.text)

My ESP32 code, I think that the problem is caused because of wrong url, since I'm not sure what IP should I be using there. Is it the IP of the machine where the python code is running ? Or IP of ESP32 ? Or am I completely wrong ?

#include <WiFi.h>
#include <HTTPClient.h>
#include <WebServer.h>

WebServer server(7777);
HTTPClient http;

const char* ssid = "SSID";
const char* password =  "PASSWORD";

void handleRoot() {
  server.send(200, "text/plain", "Hello World!");
}

void handleNotFound() {
  server.send(404, "text/plain", "Hello World!");
}

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

  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    Serial.println("Connecting to WiFi..");
  }
  Serial.println(WiFi.localIP());

  server.on("/", handleRoot);
  server.onNotFound(handleNotFound);
  server.begin();
  http.begin("http://192.168.0.100/");
}

void loop() {
 server.handleClient();
 int httpCode = http.GET();
 String payload = http.getString();
 Serial.println(httpCode);
 Serial.println(payload);
}

EDIT: Now the ESP should act as a server


Solution

  • When you send a GET/POST request you must put the IP of the destination, in this case, the IP of your ESP32.

    First thing to note, my server.begin() was listening on 192.168.4.1:80 by default as an access point.

    Now, to create an asynchronous server that holds GET and POST requests with json data you can have a function like this:

    file http_server.h:

    #include "WiFi.h"
    #include "ESPAsyncWebServer.h"
    #include "ArduinoJson.h"
    
    #ifndef _HTTP_SERVER_
    #define _HTTP_SERVER_
    
    void setup_http_server();
    
    #endif
    

    example of file http_server.cpp:

    #include "http_server.h"
    
    AsyncWebServer server(80);  // start server listening on port 80
    void setup_http_server(){
    
        // Example of function that holds and HTTP_GET request on 192.168.4.1:80/get_data
        server.on("/get_data", HTTP_GET, [](AsyncWebServerRequest *request){
            // Code that holds the request
            Serial.println("Get received"); // Just for debug
            request->send(HTTP_200_code, "text/plain", "Here I am"); 
        });
    
        // Example of function that holds and HTTP_POST request on 192.168.4.1:80/set_data
        server.on("/set_data",
            HTTP_POST,
            [](AsyncWebServerRequest * request){},
            NULL,
            [](AsyncWebServerRequest * request, uint8_t *data, size_t len,
            size_t index, size_t total) {
                // Here goes the code to manage the post request
                // The data is received on 'data' variable
                // Parse data
                Serial.printlnt("POST RECEIVED"); // Just for debug
                StaticJsonBuffer<50> JSONBuffer; // create a buffer that fits for you
                JsonObject& parsed = JSONBuffer.parseObject(data); //Parse message
                uint8_t received_data = parsed["number"]; //Get data
                request->send(HTTP_200_code, "text/plain", "Some message");
        });
    
        server.begin();  // starts asyncrhonus controller
        Serial.println(WiFi.softAPIP());  // you can print you IP yo be sure that it is 192.168.4.1
    }
    

    Finally, if you want to conect directly to your ESP32 with your mobile/computer, you will need to configure its wifi connection as an ACCESS_POINT. So, your setup() and loop()in your main.ino could look like:

    file main.ino:

    #include "http_server.h"
    
    void setup(){
         Serial.begin(9600);  // setup serial communication
         // Set WiFi to station(STA) and access point (AP) mode simultaneously 
         WiFi.mode(WIFI_AP_STA);
         delay(100); // Recommended delay
         WiFi.softAP("choose_some_ssid", "choose_some_password");
    
         // Remember to configure the previous server
         setup_http_server();  // starts the asyncronus https server*/
    }
    
    void loop(){
         delay(1000);
    }
    

    And that's all. to check that everything worked you can connect your mobile phone to the wifi choose_some_ssid with password chose_some_password, open a browser and go to 192.168.4.1/get_data and you should get "Here I am" as response.

    As you said on your question, if you want to send a post with python you can do:

    import requests
    r = requests.post('http://192.168.4.1:80/set_data', data="{'number':55}") // remember that you get the keyword 'number' in the server side
    print(r.text) // should print "Some message"
    

    More information can be found on https://techtutorialsx.com/2018/10/12/esp32-http-web-server-handling-body-data/ Hope it helps!