Hi Rui, Sara and colleagues,
I want to use server.on method in a function, with first argument being a string variable:
This works, as usual :
server.on( “/on”, HTTP_GET, [](AsyncWebServerRequest * request) { …..
But this one which I need, does not work :
String txt = “/on”;
server.on( txt, HTTP_GET, [](AsyncWebServerRequest * request) {……
I get following error message :
“no matching function for call to ‘AsyncWebServer::on(String&, WebRequestMethod, setup()::__lambda10)'”
How to get around, any idea?
I don’t want to repeat the same code for “/on1”, “/on2” … to control twelve or more relays.
Kind regards,
Hi.
The best way to achieve that is to make requests with params. For example:
- relay (GPIO 2) request to turn on: /update?output=2&state=1
- relay (GPIO 2) request to turn off: /update?output=2&state=0
- relay (GPIO 4) request to turn on: /update?output=4&state=1
- relay (GPIO 4) request to turn off: /update?output=4&state=0
In your code, define the parameters of the URL:
const char* PARAM_INPUT_1 = "output"; const char* PARAM_INPUT_2 = "state";
Then, handle the web server with on single server.on() for every request. This will find the values passed on the parameters:
server.on("/update", HTTP_GET, [] (AsyncWebServerRequest *request) {
String outputParamValue;
String stateParamValue;
// GET input1 value on <ESP_IP>/update?output=<outputParamValue>&state=<state>
if (request->hasParam(PARAM_INPUT_1) && request->hasParam(PARAM_INPUT_2)) {
outputParamValue= request->getParam(PARAM_INPUT_1)->value();
stateParamValue= request->getParam(PARAM_INPUT_2)->value();
//control the relay
digitalWrite(outputParamValue.toInt(), stateParamValue.toInt());
}
else {
outputParamValue = "No message sent";
stateParamValue= "No message sent";
}
Serial.print("GPIO: ");
Serial.print(outputParamValue);
Serial.print(" - Set to: ");
Serial.println(stateParamValue);
request->send(200, "text/plain", "OK");
});
I hope this is clear. Let me know if you need further help.
Regards,
Sara
Thanks a lot Sara, I will try this.
Kind regards,
Update for result : This has been resulted in a neat, easy to read and working code. Thanks again for your kind involvement.
BR.