0

I'm building web based remote control system for esp8266. In arduino IDE, using the ESP libraries. To, send data to the server, I'm using http post. For some settings, I need to transfer 30 or so, different values over a single post request. And assign it to different type of variables.

so, from this:
192.168.1.101/testpost?lenght=10&1=100&2=true&3=1800&4=125

i need this:

uint8_t brightness = 100;
bool randomOrder = true;
uint16_t Delay = 1800;
uint8_t Position = 125;

This is the relevant code. Basically, my idea is, to send the lenght of the array (will be different each time.) in the first argument. Than create a for loop that put every value in a array into variable pointers. But, since lots of different type variables going on, i'm not sure how to do that.

#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>

//values i need to set in a single post.
uint8_t settings0;
bool brightness; 
uint16_t randomOrder; 
uint8_t Delay;

void setup {
//relevant code that handels post request.
server.on("/testpost", HTTP_POST, []() {

String ZeroValue = server.arg("lenght");

int lenght = ZeroValue.toInt();

//this doesnt really work, but its a starting idea.
int* SettingsArray[4] = {&settings0, &brightness, &randomOrder, &Delay};

for( int i = 0; i < lenght; i++) {

     String PresetSettings = server.arg(i);
     SettingsArray[i] = PresetSettings.toInt();
    }
});
}

Ultimately, I can just do that, but I'm wondering if there is a more elegant solution.

brightness = SettingsArray[1];
randomOrder = SettingsArray[2];
Delay = SettingsArray[3];
Position = SettingsArray[4];

1 Answer 1

1

The WebServer class supports argument lookup by name. This should allow HTTP argument parsing that does not require length and/or specific order:

192.168.1.101/testpost?brightness=100&randomOrder=true&delay=1800&position=125

And parse with:

brightness = server.arg("brightness").toInt();
randomOrder = server.arg("randomOrder").toInt();
Delay = server.arg("delay").toInt();
Position = server.arg("position").toInt();

Please note that some value will require cast (and there might be a need for special handling of "true" and "false"). For further robustness each argument name needs to be checked that it is available.

String arg = server.arg("argName");
val = (arg.length() == 0 ? defaultVal : arg.toInt());

Or simply:

String arg = server.arg("argName");
if (arg.length() != 0) val = arg.toInt();

Cheers!

1
  • Thank you! didn't notice i can do that, that simplify code on front end as well.
    – Nah
    Aug 27, 2016 at 11:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.