#3 Establecer y borrar una salida

                                Este capítulo contiene un par de enlaces para establecer y borrar una salida.

                                Añadir las acciones de establecer y borrar

                                La forma más sencilla para agregar acciones simples en la página web es insertar elementos HTML de enlace(<a>) con rutas de acción asociadas. La respuesta HTTP del servidor debe contener estos enlaces:

                                client.println("HTTP/1.1 200 OK"); 
                                client.println("Content-Type: text/html");  
                                client.println(); 
                                client.println( "<!doctype html>" "<html>" "<head>" "<title>Hello PLC!</title>" "</head>" "<body>" "<h1>Hello PLC!</h1>
                                "<a href='/setOutput'>Set output</a><br>" "<a href='/clearOutput'>Clear output</a><br>" 
                                "</body>" "</html>" ); 
                                client.flush();

                                Interpretar la solicitud

                                Ahora el sketch debe analizar la solicitud para establecer o borrar la salida dependiendo de la ruta. Para hacer esto, obtiene la ruta desde la primera línea de la solicitud usando un objeto String llamado ruta y algunas de sus funciones.

                                • Algunas variables son necesarias:

                                String header; bool firstLine = true; 
                                • Y el carácter recibido del cliente se agrega al encabezado:

                                if (firstLine) { header += c; } 
                                • Cuando se completa la solicitud, el sketch analiza la línea de encabezado para obtener la ruta.

                                int pos = header.indexOf(' '); String path = header.substring(pos + 1, header.indexOf(' ', pos + 1)); 
                                • Recuerda actualizar la variable firstLine cuando el cliente envíe un carácter 'nueva línea' (\ n).

                                if (c == '\n') { emptyLine = true; firstLine = false; } else if (c != '\r') { emptyLine = false; }  


                                Establecer o borrar la salida dependiendo de la ruta

                                El servidor debe establecer la salida en HIGH cuando la ruta sea igual a “/setOutput” y LOW cuando la ruta sea igual a “/clearOutput”.

                                if (path.compareTo("/setOutput") == 0)
                                    { // Set output
                                    digitalWrite(Q0_0, HIGH);
                                    } else if (path.compareTo("/clearOutput") == 0) {
                                    // Clear output
                                    digitalWrite(Q0_0, LOW);
                                }                       

                                Revisión final del código

                                Aquí está el código completo con algunas mejoras:

                                • envía un error 404 para solicitudes desconocidas,

                                • envía una respuesta de redirección a la página principal en la solicitud de comando establecer/borrar,

                                • y agrega la función sendMainPage() para facilitar la lectura y reutilizarla.

                                 

                                Ejemplo de código

                                #include <Ethernet2.h> // Server creation

                                EthernetServer server(80);

                                void setup() {

                                  Serial.begin(9600UL); Serial.println("WebServer started"); // Ethernet initialization

                                  byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};

                                  byte ip[] = {10, 10, 10, 25}; Ethernet.begin(mac, ip); // Server initialization

                                  server.begin();

                                }

                                void loop() { // Wait for clients

                                  EthernetClient client = server.available();

                                  if (client) { // Parse request

                                    bool emptyLine = true;

                                    String header; bool firstLine = true;

                                    while (client.connected()) {

                                      if (client.available()) {

                                        char c = client.read();

                                        if (firstLine) {

                                          header += c;  // The request is finished when an empty line is received

                                        }

                                        if (emptyLine && (c == '\n')) { // Get path from the header line

                                          int pos = header.indexOf(' ');

                                          String path = header.substring(pos + 1, header.indexOf(' ', pos + 1)); // Act depending on path

                                          if (path.compareTo("/") == 0) {

                                            sendMainPage(client);

                                          }

                                          else if (path.compareTo("/setOutput") == 0) { // Set output

                                            digitalWrite(Q0_0, HIGH); // Redirect response

                                            redirectToMainPage(client);

                                          }

                                          else if (path.compareTo("/clearOutput") == 0) { // Clear output

                                            digitalWrite(Q0_0, LOW); // Redirect response

                                            redirectToMainPage(client);

                                          }

                                          else { // Unrecognized path

                                            sendNotFound(client);

                                          } client.flush(); // Close connection

                                          client.stop(); break;

                                        } // The request is finished when a blank line is received

                                        if (c == '\n') {

                                          emptyLine = true;

                                          firstLine = false;

                                        }

                                        else if (c != '\r') {

                                          emptyLine = false;

                                        }

                                      }

                                    }

                                  }

                                }

                                void sendNotFound(EthernetClient &client) { // Path not found

                                  client.println("HTTP/1.1 404 Not Found");

                                  client.println("Content-Type: text/plain");

                                  client.println();

                                  client.println("404 Not Found");

                                }

                                void redirectToMainPage(EthernetClient &client) { // Redirect to main page

                                  client.println("HTTP/1.1 303 See Other");

                                  client.println("Location: /");

                                  client.println();

                                }

                                void sendMainPage(EthernetClient &client) { // Send the response

                                  client.println("HTTP/1.1 200 OK");

                                  client.println("Content-Type: text/html");

                                  client.println(); client.println( "<!doctype html>" "<html>" "<head>" "<title>Hello PLC!</title>" "</head>" "<body>" "<h1>Hello PLC!</h1>" "<a href='/setOutput'>Set output</a><br>" "<a href='/clearOutput'>Clear output</a><br>" "</body>" "</html>" );

                                }



                                Commenting is not enabled on this course.

                                3. Las acciones como digitalWrite() entre otras se ejecutan considerando la función...