Réception des données POST

Bonjour,
J'utilise une carte mega avec un shield ethernet rev 2. J'ai sur l'une des pages générée grace au shield ethernet, j'ai créé un formulaire utilisant la méthode "POST" sur ce point tout fonctionne. Mon problème arrive lorsque je souhaite récupérer les données du formulaire sur la carte arduino. Pour le moment j'ai pue récupérer toute l'en-tête, mais comme je l'ai dit, je n'ai pas encore pue récupérer les données qui sont affichés dans l'inspecteur du navigateur sous le nom de "Charge utile"(Chrome) ou "Requete"(FireFox). Dans mon cas le formulaire redirige vers "./command.php".
Pouvez-vous m'aider ?
Le code qui s'exécute lorsque le client se connecte a "./command.php" :

        } else if (reception.startsWith("POST /")) {
          EthernetClient cl = serveur.available();
          if (ac == "command.php") {
            char    headerLine[80];
            char    headerIndex;
            headerIndex = 0;
            while (client.connected()) {
              if (client.available()) {
                char c = client.read();
                if (c == '\n') {

                  //---- test ligne d'entete avec mot de passe
                  headerLine[headerIndex] = 0;
                  headerIndex = 0;
                  Serial.println (headerLine);
                  // you're starting a new line
                }
                else if (c != '\r') {

                  //---- mémorisation ligne d'entete courante
                  if (headerIndex < 79)
                    headerLine[headerIndex++] = c;
                }
              }
            }
          }
        }

La réponse actuelle dans le terminale :

18:31:29.600 -> 'reception' = POST /command.php HTTP/1.1

18:31:29.634 -> Host: 192.168.1.11
18:31:29.668 -> Connection: keep-alive
18:31:29.668 -> Content-Length: 11
18:31:29.702 -> Pragma: no-cache
18:31:29.702 -> Cache-Control: no-cache
18:31:29.744 -> Authorization: Basic dGVzdDp0ZXN0ZQ==
18:31:29.770 -> Upgrade-Insecure-Requests: 1
18:31:29.804 -> User-Agent: Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML,
18:31:29.907 -> Origin: http://192.168.1.11
18:31:29.941 -> Content-Type: application/x-www-form-urlencoded
18:31:29.976 -> Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/
18:31:30.077 -> Referer: http://192.168.1.11/page
18:31:30.112 -> Accept-Encoding: gzip, deflate
18:31:30.146 -> Accept-Language: fr-FR,fr;q=0.9,de-DE;q=0.8,de;q=0.7,en-US;q=0.6,en;q=0.5

La réponse souhaité :

18:31:29.600 -> 'reception' = POST /command.php HTTP/1.1

18:31:29.634 -> Host: 192.168.1.11
18:31:29.668 -> Connection: keep-alive
18:31:29.668 -> Content-Length: 11
18:31:29.702 -> Pragma: no-cache
18:31:29.702 -> Cache-Control: no-cache
18:31:29.744 -> Authorization: Basic dGVzdDp0ZXN0ZQ==
18:31:29.770 -> Upgrade-Insecure-Requests: 1
18:31:29.804 -> User-Agent: Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML,
18:31:29.907 -> Origin: http://192.168.1.11
18:31:29.941 -> Content-Type: application/x-www-form-urlencoded
18:31:29.976 -> Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/
18:31:30.077 -> Referer: http://192.168.1.11/page
18:31:30.112 -> Accept-Encoding: gzip, deflate
18:31:30.146 -> Accept-Language: fr-FR,fr;q=0.9,de-DE;q=0.8,de;q=0.7,en-US;q=0.6,en;q=0.5

18:31:31.146 -> command=/command

Merci

postez tout le code... (Snippets R Us!)

Le voici escusez-moi.

#include <SPI.h>
#include <SD.h>
#include <Ethernet.h>
byte mac[] = {0x90, 0xA2, 0xDA, 0x00, 0x1A, 0x71};
byte ip[] = {192, 168, 1, 11};
unsigned long tpsDep;         //Tps depart pour la gestion des LEDs
int modeLed = {1};  // TABLEAU des modes d'allumage (0=eteint, 1=allume et 2=clignotte)
String reception = "";      //Chaine reçue par le serveur (première ligne uniquement <=> requète)
String reception2 = "ERROR : 555";
char carLu;
byte d = 0;

EthernetServer serveur(80); // déclare l'objet serveur au port d'écoute

File myFile;

int OP;
int OPING;
int CL;

void setup() {

  Serial.begin(9600);

  Serial.print("Initializing SD card...");
  if (!SD.begin(4)) {
    Serial.println("initialization failed!");
  }
  Serial.println("initialization done.");
  ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  // open the file. note that only one file can be open at a time,
  // so you have to close this one before opening another.
  myFile = SD.open("test.txt", FILE_WRITE);

  // if the file opened okay, write to it:
  if (myFile) {
    Serial.print("Writing to test.txt...");
    myFile.println("testing 1, 2, 3.");
    // close the file:
    myFile.close();
    Serial.println("done.");
  } else {
    // if the file didn't open, print an error:
    Serial.println("error opening test.txt");
  }

  Ethernet.begin (mac, ip);
  delay(1000);                                 //Délais d'initialisation du Shield Ethernet 2
  if (Ethernet.localIP() != NULL)              //Petite vérification avant démarrage du serveur
  {
    Serial.print(F("Serveur a l'adresse '"));
    Serial.print(Ethernet.localIP());
    Serial.println(F("' OK!'"));
  }
  else
  {
    Serial.println(F("Erreur serveur"));
  }

  pinMode(4, OUTPUT);   // on met le pin 4 du SPI commun à la carte SD à Output, sinon conflit
  digitalWrite(4, HIGH);

  ale("OP");
  ale("OPING");
  ale("CL");
  Serial.println(OP);
  Serial.println(OPING);
  Serial.println(CL);
}

void loop()
{
  gestionClient();    //fonction de gestion de la communication client
}



//  *****************************************************  FONCTIONS  *******************************************************

//FONCTION de gestion de la communication client
void gestionClient()
{
  EthernetClient client = serveur.available();  //on ecoute le port
  if (client)   //si le client existe
  {
    reception = "";
    if (client.connected())
    {
      Serial.println(F("Client connecte"));
      if (client.available()) carLu = client.read();
      while (client.available() && carLu != 10) //Tant qu'il reste au moins 1 octet à lire sur la première ligne
      {
        reception = reception + carLu;
        carLu = client.read();
      }
      Serial.print(F("\n'reception' = "));
      Serial.println(reception);
      if (reception.startsWith("GET")) {                       //Si la chaine reçue contient une requète
        if (reception.startsWith("GET / HTTP/1.1")) {         //Requête sans paramètre => affichage de la page
          accueil(client);
        } else if (reception.startsWith("GET /page")) {
          page();
        } else if (reception.startsWith("GET /disconect ")) {
          disconect(client);
        } else if (reception.indexOf("test.txt") != -1)      //Si demande d'envoi du fichier 'style.css'
        { //(balise <link> dans le fichier html)
          if (d >= 1) {
            Serial.print("Client autorisé : ");
            Serial.println(d);
            if (SD.exists("test.txt"))                        //Si le fichier "style.css" existe on l'ouvre en
            { //lecture, puis on lit son contenu caractère par
              d--;
              client.println("HTTP/1.1 200 OK");  //type de HTML
              client.println("Content-Type: text/html; charset=ascii");  //type de fichier et encodage de caracteres
              client.println("Connection: close");    //fermeture de la connexion quand toute la reponse a ete envoyee
              client.println();
              client.println("<html><head></head><body><pre style='word-wrap: break-word; white-space: pre-wrap;'>");
              File fichier = SD.open("test.txt", FILE_READ);  //caractère que l'on envoie en même temps vers
              while (fichier.available())                      //le client pour affichage.
              {
                char carTemp = fichier.read();
                Serial.write(carTemp);
                client.write(carTemp);
              }
              fichier.close();
              client.println("</pre></body></html>");
            } else {
              Serial.println(F("Fichier 'test.txt' absent"));
              return;
            }
          }
          else {
            Serial.print("Client interdit : ");
            Serial.println(d);
          }
        } else {
          String nomDeFichier;
          nomDeFichier = reception.substring(5); // 5 pour aller juste après le 'GET /'
          int index =  nomDeFichier.indexOf(' '); // on pourrait tester l'index car si c'est -1 ce n'est pas bon
          nomDeFichier.remove(index);
          Serial.print("Fichier demandé : [");
          Serial.print(nomDeFichier);
          Serial.println(']');
          if (SD.exists(nomDeFichier))                        //Si le fichier "style.css" existe on l'ouvre en
          { //lecture, puis on lit son contenu caractère par
            client.println("HTTP/1.1 200 OK");  //type de HTML
            if (nomDeFichier.endsWith(".ico")) {
              client.println("Content-Type: image/vnd.microsoft.icon");  //type de fichier et encodage de caracteres
            } else if (nomDeFichier.endsWith(".css")) {
              client.println("Content-Type: text/css");  //type de fichier et encodage de caracteres
            } else {
              client.println("Content-Type: text/html");  //type de fichier et encodage de caracteres
            }
            client.println("Connection: close");    //fermeture de la connexion quand toute la reponse a ete envoyee
            client.println();
            File fichier = SD.open(nomDeFichier, FILE_READ);  //caractère que l'on envoie en même temps vers
            while (fichier.available())                      //le client pour affichage.
            {
              char carTemp = fichier.read();
              if (nomDeFichier.endsWith(".ico")) {} else {
                Serial.write(carTemp);
              }
              client.write(carTemp);
            }
            fichier.close();
          } else {
            Serial.print(F("Fichier '"));
            Serial.print(nomDeFichier);
            Serial.println(F("' absent"));
            return;
          }
        }
      } else if (reception.startsWith("POST")) {
        String ac;
        ac = reception.substring(6);
        int inde =  ac.indexOf(' ');
        ac.remove(inde);
        if (reception.startsWith("POST /?")) {
          String action;
          action = reception.substring(7);
          int index =  action.indexOf('+');
          action.remove(index);

          String mdp;
          String amdp;
          amdp = reception.substring(7);
          index++;
          mdp = amdp.substring(index);
          int inde =  mdp.indexOf(' ');
          mdp.remove(inde);

          Serial.print("Action demandé : [");
          Serial.print(action);
          Serial.println(']');
          Serial.print("MDP donnée : [");
          Serial.print(mdp);
          Serial.println(']');
          if (action == "CLOSE") {
            if (mdp.toInt() == CL) {
              digitalWrite(3, LOW);
              Serial.println("Fermeture porte.");
              Serial.print("MDP CL = ");
              Serial.println(CL);
              modeLed = 1;
              Serial.println(modeLed);
            } else {
              Serial.print("MDP donné (");
              Serial.print(mdp);
              Serial.print(") ne corecepond pas avec le mdp demandé (");
              Serial.print(CL);
              Serial.println(").");
            }
          } else if (action == "OPEN") {
            if (mdp.toInt() == OP) {
              digitalWrite(3, HIGH);
              Serial.println("Ouverture porte.");
              Serial.print("MDP OP = ");
              Serial.println(OP);
              modeLed = 0;
              Serial.println(modeLed);
            } else {
              Serial.print("MDP donné(");
              Serial.print(mdp);
              Serial.print(") ne corecepond pas avec le mdp demandé(");
              Serial.print(OP);
              Serial.println(").");
            }
          } else if (action == "OPENING") {
            if (mdp.toInt() == OPING) {
              digitalWrite(3, HIGH);
              Serial.println("Ouverture 5 sec porte.");
              delay(5000);
              digitalWrite(3, LOW);
              Serial.print("MDP OPING = ");
              Serial.println(OPING);
            } else {
              Serial.print("MDP donné (");
              Serial.print(mdp);
              Serial.print(") ne corecepond pas avec le mdp demandé (");
              Serial.print(OPING);
              Serial.println(").");
            }
          } else {
            Serial.print("Action invalide.");
            redirect("page");
          }
        } else if (reception.startsWith("POST /")) {
          EthernetClient cl = serveur.available();
          if (ac == "command.php") {
            char    headerLine[80];
            char    headerIndex;
            headerIndex = 0;
            while (client.connected()) {
              if (client.available()) {
                char c = client.read();
                if (c == '\n') {

                  //---- test ligne d'entete avec mot de passe
                  headerLine[headerIndex] = 0;
                  headerIndex = 0;
                  Serial.println (headerLine);
                  // you're starting a new line
                }
                else if (c != '\r') {

                  //---- mémorisation ligne d'entete courante
                  if (headerIndex < 79)
                    headerLine[headerIndex++] = c;
                }
              }
            }
          }
        } else {
          redirect("page");
        }
      } else Serial.println(F("Requete non conforme"));
      delay(1);                                               //La transmission est rapide mais pas instantanée
      client.stop();
    }
  }
}

//                                         ******************************

//FONCTION en-tete de page
void enTete(EthernetClient cl)
{
  //infos sur le navigateur
  cl.println("HTTP/1.1 200 OK");  //type de HTML
  cl.println("Content-Type: text/html; charset=UTF-8");  //type de fichier et encodage de caracteres
  cl.println("Connection: close");    //fermeture de la connexion quand toute la reponse a ete envoyee
  cl.println();

  //balises d'entete
  cl.println("<!DOCTYPE HTML>");
  cl.println("<html>");
  cl.println("  <head>");
  cl.println("    <link rel='shortcut icon'type='image/vnd.microsoft.icon'href='http://91.169.86.51:49152/favicon.ico'>");
  cl.println("    <meta http-equiv='content-type' content='text/html; charset=windows-1252'>");
  cl.println("    <title>Web commande de leds</title>");
  cl.println("    <link rel='stylesheet' href='psd.css'/>");
  cl.println("    <link rel='stylesheet' href='all.css'/>");
  //cl.println("    <META http-EQUIV='Refresh' CONTENT='60; url=http://192.168.1.11/'>");
  //balises d'entete
  cl.println("  </head>");
  cl.println("  <body>");
  cl.println("    <div class='topnav'>");
  cl.println("      <a class='active' href='./'>Home</a>");
  cl.println("      <a class='pasive' href='./page'>Page</a>");
  cl.println("      <strong class='titre'>Commande de leds</strong>");
  cl.println("      <div class='login-container'>");
  cl.println("        <button type='submit' onclick='window.location.href = `./disconect`'>Logout</button>");
  cl.println("      </div>");
  cl.println("    </div>");
  cl.println("    <hr>");
  cl.println("      <br />");
  //cl.print("<META http-EQUIV='Refresh' CONTENT='1; url=http://192.168.1.11/'>");
}


//                                         ******************************

//FONCTION corps de page
void corps(EthernetClient cl)
{
  String v;
  int c;
  switch (modeLed) {
    case 0:
      v = "CLOSE";
      c = CL;
      cl.print("La porte est déverouillée cliquez pour la verouillée.");
      cl.print("<form action='./?");
      cl.print(v);
      cl.print("+");
      cl.print(c);
      cl.print("' method='OPEN'>");
      cl.print("<table>");
      cl.print("<tbody>");
      cl.print("</tr>");
      cl.print("<tr><td></td><td><button formmethod='post'  class='CL'>verouillée</button></td></tr>");
      cl.print("</tbody></table>");
      cl.print("</form>");
      break;
    case 1:
      cl.print("La porte est verouillée cliquez pour la déverouillée.");
      cl.print("<h1>");
      for (int t = 0; t < 2; t++) {
        switch (t) {
          case 0:
            v = "OPEN";
            c = OP;
            cl.print("<form action='./?");
            cl.print(v);
            cl.print("+");
            cl.print(c);
            cl.print("' method='OPEN'>");
            cl.print("<table>");
            cl.print("<tbody>");
            cl.print("</tr>");
            cl.print("<tr><td></td><td><button formmethod='post' class='OP'>Déverouiller</button></td></tr>");
            break;

          case 1:
            v = "OPENING";
            c = OPING;
            cl.print("<form action='./?");
            cl.print(v);
            cl.print("+");
            cl.print(c);
            cl.print("' method='OPEN'>");
            cl.print("<table>");
            cl.print("<tbody>");
            cl.print("</tr>");
            cl.print("<tr><td></td><td><button formmethod='post' class='OPING'>Déverouiller<br>5sec</br></button></td></tr>");
        }
        cl.print("</tbody></table>");
        cl.print("</form>");
      }
      cl.print("</h1>");
      break;
  }
}

//                                         ******************************

//FONCTION pied de page
void piedPage(EthernetClient cl)
{
  cl.println("      <br />");
  cl.println("    <hr>");
  myFile = SD.open("test.txt");
  if (myFile) {
    cl.println("<script type='text/javascript'>");
    cl.println("function goToBottom (el)");
    cl.println("{");
    cl.println("el.contentWindow.scrollTo (0, 999999999);");
    cl.println("}");
    cl.println("</script>");
    cl.println("<iframe src='http://192.168.1.11/test.txt' onload='goToBottom (this)' fullscreen='true'></iframe>");
  }
  cl.println("    <form action='/command.php' method='get' class='form-example'>");
  cl.println("      <div class='form-example'>");
  cl.println("        <input type='text' name='command' id='command' placeholder='Saisisez la command ici' required>");
  cl.println("        <input type='submit' formmethod='post' value='Subscribe!'>");
  cl.println("      </div>");
  cl.println("    </form>");
  cl.println("  </body>");
  cl.println("</html>");
}

//                                         ******************************

void accueil(EthernetClient cl) {
  cl.println("HTTP/1.1 200 OK");  //type de HTML
  cl.println("Content-Type: text/html; charset=ascii");  //type de fichier et encodage de caracteres
  cl.println("WWW-Authenticate: Basic realm=\"something\"");
  cl.println("Connection: close");    //fermeture de la connexion quand toute la reponse a ete envoyee
  cl.println();
  cl.println("<!DOCTYPE HTML>");
  cl.println("<html>");
  cl.println("  <head>");
  cl.println("    <meta http-equiv='content-type' content='text/html; charset=windows-1252'>");
  cl.println("    <title>My security</title>");
  cl.println("    <link rel='stylesheet' href='all.css'/>");
  //cl.println("    <META http-EQUIV='Refresh' CONTENT='60; url=http://192.168.1.11/'>");
  //balises d'entete
  cl.println("  </head>");
  cl.println("  <body>");
  cl.println("    <div class='topnav'>");
  cl.println("      <a class='active' href='./'>Home</a>");
  cl.println("      <a class='pasive' href='./page'>Page</a>");
  cl.println("      <strong class='titre'>My security home</strong>");
  cl.println("      <div class='login-container'>");
  cl.println("        <button type='submit' onclick='window.location.href = `./page`'>Login</button>");
  cl.println("      </div>");
  cl.println("    </div>");
  cl.println("  </body>");
  cl.println("</html>");
}

//                                         ******************************

void page() {
  EthernetClient client = serveur.available();  //on ecoute le port
  char    headerLine[80];
  char    headerIndex;
  bool    passwordOk;
  boolean currentLineIsBlank = true;
  passwordOk = false;
  headerIndex = 0;
  while (client.connected()) {
    if (client.available()) {
      char c = client.read();

      // if you've gotten to the end of the line (received a newline
      // character) and the line is blank, the http request has ended,
      // so you can send a reply
      if (c == '\n' && currentLineIsBlank) {

        if (passwordOk) {
          enTete(client);
          corps(client);
          piedPage(client);
          d++;
        }
        else
        {
          //---- envoi code d'erreur 401 ----
          client.println("HTTP/1.1 401 OK");
          client.println ("WWW-Authenticate: Basic realm=\"something\"");
          client.println("Content-Type: text/html");
          client.println("Connection: close");
          client.println();
          client.println("<!DOCTYPE HTML>");
          client.println("<html>");
          client.println("mot de passe incorrect");
          client.println("</html>");
        }
        break;
      }
      if (c == '\n') {

        //---- test ligne d'entete avec mot de passe
        headerLine[headerIndex] = 0;
        headerIndex = 0;
        Serial.println (headerLine);
        if (strcmp (headerLine, "Authorization: Basic dGVzdDp0ZXN0ZQ==") == 0)
          passwordOk = true;

        // you're starting a new line
        currentLineIsBlank = true;
      }
      else if (c != '\r') {

        //---- mémorisation ligne d'entete courante
        if (headerIndex < 79)
          headerLine[headerIndex++] = c;

        // you've gotten a character on the current line
        currentLineIsBlank = false;
      }
    }
  }
}

//                                         ******************************

void disconect(EthernetClient cl) {

  cl.println("HTTP/1.1 401 OK");
  cl.println ("WWW-Authenticate: Basic realm=");
  cl.println("Content-Type: text/html");
  cl.println("Connection: close");
  cl.println();
  cl.println("<!DOCTYPE HTML>");
  redirect("");
}

//                                         ******************************

void ale(String N) {

  if (N == "OP") {
    int OP1;
    OP1 = random(analogRead(A1), analogRead(A2));
    int OP2;
    analogWrite(A3, HIGH);
    OP2 = random(analogRead(A3), analogRead(A4));
    analogWrite(A3, LOW);
    if (OP1 > OP2) {
      OP = random(OP2, OP1);
    } else if (OP1 < OP2) {
      OP = random(OP1, OP2);
    } else if (OP1 == OP2) {
      ale("OP");
    }
    Serial.print("OP = ");
    Serial.println(OP);
  } else if (N == "CL") {
    int CL1;
    CL1 = random(analogRead(A1), analogRead(A2));
    int CL2;
    analogWrite(A3, HIGH);
    CL2 = random(analogRead(A3), analogRead(A4));
    analogWrite(A3, LOW);
    if (CL1 > CL2) {
      CL = random(CL2, CL1);
    } else if (CL1 < CL2) {
      CL = random(CL1, CL2);
    } else if (CL1 == CL2) {
      ale("CL");
    }
    Serial.print("CL = ");
    Serial.println(CL);
  } else if (N == "OPING") {
    int OPING1;
    OPING1 = random(analogRead(A1), analogRead(A2));
    int OPING2;
    analogWrite(A3, HIGH);
    OPING2 = random(analogRead(A3), analogRead(A4));
    analogWrite(A3, LOW);
    if (OPING1 > OPING2) {
      OPING = random(OPING2, OPING1);
    } else if (OPING1 < OPING2) {
      OPING = random(OPING1, OPING2);
    } else if (OPING1 == OPING2) {
      ale("OPING");
    }
    Serial.print("OPING = ");
    Serial.println(OPING);
  }
}

//                                         ******************************

void redirect(String p) {
  EthernetClient cl = serveur.available();
  cl.println("HTTP/1.1 200 OK");  //type de HTML
  cl.println("Content-Type: text/html; charset=ascii");  //type de fichier et encodage de caracteres
  cl.println("Connection: close");    //fermeture de la connexion quand toute la reponse a ete envoyee
  cl.println();
  cl.println("<!DOCTYPE HTML>");
  cl.println("<html>");
  cl.println("  <head>");
  cl.println("    <title>My security</title>");
  cl.print("    <META http-EQUIV='Refresh' CONTENT='0; ./");
  cl.print(p);
  cl.println("'>");
  //balises d'entete
  cl.println("  </head>");
  cl.println("</html>");
}

Je relance la question, car j'ignore si, aucune personne avant vue ma question ne sais me répondre ou si je n'ai pas donné assez d'informations. Pouvez-vous me le dire si je n'ai pas donné assez d'informations ?
Merci

Tout le monde n'a pas forcément envie de lire pratiquement 600 lignes de code avec une fonction gestionClient() totalement monolithique.
Tu aurais pu te donner un peu plus de peine pour rendre tout ça un peu plus lisible :

  • réception de la requête
  • parsing des données (non fait actuellement)
  • traitements applicatifs à part

Actuellement tout est mélangé.

http.cpp
http.h
Ici tu trouveras un code générique :

  • http_request::read() : lecture de la requête (GET ou POST)
  • http_request::parse() : parsing des arguments ( ce qui te manque)

Le projet complet :
arduino-w5100

Tu remarqueras que je n'utilise aucune String.

je suis en déplacement en ce moment, lire 600 lignes de code avec les trois quarts qui n'ont rien à voir avec la question c'est un peu trop pour regarder sur l'écran de l'iPhone

faites un code plus simple avec juste dans le setup() l'émission de la requête POST et la lecture de la réponse dans la loop()

assurez vous de ne pas arrêter la lecture de la réponse à la détection d'une ligne vide (qui marque la fin de l'en tête) mais de bien lire ce qui suit

Voici une version condensé :

#include <SPI.h>
#include <SD.h>
#include <Ethernet.h>
byte mac[] = {0x90, 0xA2, 0xDA, 0x00, 0x1A, 0x71};
byte ip[] = {192, 168, 1, 11};
String reception = "";      //Chaine reçue par le serveur (première ligne uniquement <=> requète)
char carLu;


EthernetServer serveur(80); // déclare l'objet serveur au port d'écoute

void setup() {

  Serial.begin(9600);
  Ethernet.begin (mac, ip);
  delay(1000);                                 //Délais d'initialisation du Shield Ethernet 2
  if (Ethernet.localIP() != NULL)              //Petite vérification avant démarrage du serveur
  {
    Serial.print(F("Serveur a l'adresse '"));
    Serial.print(Ethernet.localIP());
    Serial.println(F("' OK!'"));
  }
  else
  {
    Serial.println(F("Erreur serveur"));
  }
}

void loop()
{
  gestionClient();    //fonction de gestion de la communication client
}



//  *****************************************************  FONCTIONS  *******************************************************

//FONCTION de gestion de la communication client
void gestionClient()
{
  EthernetClient client = serveur.available();  //on ecoute le port
  if (client)   //si le client existe
  {
    reception = "";
    if (client.connected())
    {
      Serial.println(F("Client connecte"));
      if (client.available()) carLu = client.read();
      while (client.available() && carLu != 10) //Tant qu'il reste au moins 1 octet à lire sur la première ligne
      {
        reception = reception + carLu;
        carLu = client.read();
      }
      Serial.print(F("\n'reception' = "));
      Serial.println(reception);
      if (reception.startsWith("GET")) {                       //Si la chaine reçue contient une requète
        if (reception.startsWith("GET / HTTP/1.1")) {         //Requête sans paramètre => affichage de la page
          enTete(client);
        }
      } else if (reception.startsWith("POST")) {
        String ac;
        ac = reception.substring(6);
        int inde =  ac.indexOf(' ');
        ac.remove(inde);
        if (reception.startsWith("POST /")) {
          EthernetClient cl = serveur.available();
          if (ac == "command.php") {
            char    headerLine[80];
            char    headerIndex;
            headerIndex = 0;
            while (client.connected()) {
              if (client.available()) {
                char c = client.read();
                if (c == '\n') {

                  //---- test ligne d'entete avec mot de passe
                  headerLine[headerIndex] = 0;
                  headerIndex = 0;
                  Serial.println (headerLine);
                  // you're starting a new line
                }
                else if (c != '\r') {

                  //---- mémorisation ligne d'entete courante
                  if (headerIndex < 79)
                    headerLine[headerIndex++] = c;
                }
              }
            }
          }
        }
      } else Serial.println(F("Requete non conforme"));
      delay(1);                                               //La transmission est rapide mais pas instantanée
      client.stop();
    }
  }
}

//                                         ******************************

//FONCTION en-tete de page
void enTete(EthernetClient cl)
{
  //infos sur le navigateur
  cl.println("HTTP/1.1 200 OK");  //type de HTML
  cl.println("Content-Type: text/html; charset=UTF-8");  //type de fichier et encodage de caracteres
  cl.println("Connection: close");    //fermeture de la connexion quand toute la reponse a ete envoyee
  cl.println();

  //balises d'entete
  cl.println("<!DOCTYPE HTML>");
  cl.println("<html>");
  cl.println("  <head>");
  cl.println("    <link rel='shortcut icon'type='image/vnd.microsoft.icon'href='http://91.169.86.51:49152/favicon.ico'>");
  cl.println("    <meta http-equiv='content-type' content='text/html; charset=windows-1252'>");
  cl.println("    <title>Web commande de leds</title>");
  //balises d'entete
  cl.println("  </head>");
  cl.println("  <body>");
  cl.println("    <form action='/command.php' method='get' class='form-example'>");
  cl.println("      <div class='form-example'>");
  cl.println("        <input type='text' name='command' id='command' placeholder='Saisisez la command ici' required>");
  cl.println("        <input type='submit' formmethod='post' value='Subscribe!'>");
  cl.println("      </div>");
  cl.println("    </form>");
  cl.println("  </body>");
  cl.println("</html>");
}

Ma réponse précédente comportait un lien vers un exemple.
L'as-tu lu ?
Un exemple plus simple :
ethernet.ino

j'écrirais cela plutôt

reception = "";
while (client.available() ) {
  carLu = client.read();
  if (carLu != '\n')  reception += carLu;
  else break;
}
// attention on sort avec encore des données potentiellement disponibles dans le client donc stop() ne va pas libérer le client
Serial.print(F("\n'reception' = ")); Serial.println(reception);

et voir ce que ça imprime.

Cala ne fonctionne pas mieux je le ait déjà quand je confirme que la requête vient de mon formulaire.

Oui mais je n'avais pas bien compris le premier code je vais essayer celui la,
Merci

Dans l'exemple cité, j'ai l'impression que Ctrl-T de l'IDE m'a balancé des espaces dans les balises HTML. C'est corrigé.

la question c'est que voyez vous? que donne le print ?

J'ai la réponse que je vous ait déjà envoyé au debut.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.