ESP32 as a Server Handling HTTP GET Requests from a Client


 

ESP32 C-Code used in this video:

// Tinker Foundry
// ESP32 Server to handle GET requests from a client on the local WiFi network
// Indicate request on serial interface and also provide a response to the client
// To test this, once uploaded onto the ESP32, note the IP address reported by ESP32 over the serial monitor, and
// then open a browser on your computer and enter the following in the address bar: http://IP_Address_from_ESP32/?param1=10&param2=hello
// Also, try running the accompanying Python HTTP client code with GUI for a complete experience...

#include <WiFi.h>

// need to install libraries ESPAsyncWebserver and AsyncTCP from Github respository
// https://github.com/me-no-dev/ESPAsyncWebServer
// https://github.com/me-no-dev/AsyncTCP
// In both cases, download library zip files and extract to C:\Users\name\Documents\Arduino\Libraries directory so Arduino will see them
// Remove the "-master" suffix of the library directories
#include "ESPAsyncWebServer.h"

const char* ssid     = "xxxxxxxx";   //input your wifi name
const char* password = "xxxxxxxx";   //input your wifi password

AsyncWebServer server(80);

int cmd_cnt = 0; // this is a counter that we will return as part of data we will return in our responses to client

// Setup function
void setup() {

  pinMode (LED_BUILTIN, OUTPUT); // set built-in LED as output
 
  // standard serial interface setup stuff
  Serial.begin(115200);
  Serial.setDebugOutput(true);
  Serial.println();

  // Setup WiFi...
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");

  Serial.print("Msg: Ready! Use 'http://");
  Serial.print(WiFi.localIP());
 
  // Setup route on server by binding it to handling function...
  server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){ // use index route "/" and specify we only receive http GET requests
    // Below is handling function...
    int paramsNr = request->params(); // this is number of query parameters sent by client
    Serial.print(paramsNr);
    Serial.println(" parameters received");
 
    // go through and extract the parameters themselves in a loop
    for (int i=0; i<paramsNr; i++)
    {
      AsyncWebParameter* p = request->getParam(i); // retrieve using getParam
      Serial.print("Param name: ");
      Serial.println(p->name());

      Serial.print("Param value: ");
      Serial.println(p->value());

      if (p->name() == "LEDCONTROL")
      {
         if (p->value() == "ON"){
           digitalWrite (LED_BUILTIN, HIGH);
           Serial.println("LED On Command");
        } else if (p->value() == "OFF"){
          digitalWrite (LED_BUILTIN, LOW);
          Serial.println("LED Off Command");
        }
      }
      Serial.print("Command Count: ");
      Serial.println(cmd_cnt);
      Serial.println("-----");
    }

    request->send(200, "text/plain", String(cmd_cnt)); // Return response to client indicating "OK"
    cmd_cnt++;
 
  });

  server.begin();
}

// Main Loop
void loop() {
}

----------------------------------------------------------------------------------------------------------------

Python code to implement client with GUI from the video:

# Tinker Foundry Example Python Code
# Python HTTP client to work with ESP32 server using GET requests - this is for the accompanying ESP32 server code meant for this example
# This runs on your local computer, connected on the same WiFi network as your ESP32 controller

# Using simple GUI library for the interface
import PySimpleGUI as sg

# Need the HTTP library - use "pip install requests" if not already installed
import requests

# Using PySimpleGui
sg.theme('SandyBeach') # Window theme

# below are choices for passing parameter types...
param_choices = ('LEDCONTROL', 'Message')

# GUI window layout
layout = [
         [sg.Text('Enter Client Request Details for ESP32 Server')],
         [sg.Text('URL Location', size = (15,1)), sg.Input(expand_x=True, key='urlpath')],
         [sg.Text('Parameter Type', size = (15,1)), sg.Combo(param_choices, size=(15, len(param_choices)), default_value = 'LEDCONTROL', readonly = True, key='param')],
         [sg.Text('Parameter Value', size = (15,1)), sg.Multiline(expand_x=True, expand_y=True, key='value')],
         [sg.Button('Send Request')],
         [sg.HSeparator()],
         [sg.Text('Response output:')],
         [sg.Multiline(expand_x=True, expand_y=True, key='response')],
         [sg.HSeparator()]
]

window = sg.Window('Web Client GUI for ESP32 Server Example', resizable=True).Layout(layout)

while True:  # The Event Loop
    event, values = window.read()
    if event == sg.WIN_CLOSED or event == 'Exit':
        break
    if event == 'Send Request':
        window['response'].print("Submitting request...")
        window['response'].print("")
        URL = values['urlpath'] # url for sending the request to
        PARAMS = {values['param']:values['value']} # parameter and value for the request
        r = requests.get(url = URL, params = PARAMS) # send the GET request
        data = r.content # this is what is returned from the serviced request
        window['response'].print(data) # print out the returned data
        window['response'].print("-------------")

window.close()




Comments

Popular posts from this blog

ESP32 Based Pulse-Oximeter using MAX30102

ESP32 Web Sockets - Transferring Image Raw Data

Heart Rate Measurement with ESP32 and Pulse Oximeter Module using FFT