Ir al contenido

#4 Mostrar valor de una entrada

Este capítulo explica cómo mostrar un valor de entrada actualizado dinámicamente en la página web. Obviamente, también es posible mostrar otros valores dinámicos de variables o cualquier otra cosa.

Mostrar el valor de entrada

Se agrega un elemento de texto HTML a la página web para poner el valor de entrada. Para actualizarlo dinámicamente, es necesario agregar un poco de JavaScript en la página web. La función JavaScript updateInputValue() envía una solicitud al servidor para obtener el valor de entrada y, cuando se recibe la respuesta, inserta el texto recibido en el elemento HTML de valor de entrada utilizando la función getElementById() y la propiedad innerHTML.

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>"
                 "<p>Input value: <span id='input-value'></span></p>"
                 "<script>"
                 "function updateInputValue() {"
                 " var xhttp = new XMLHttpRequest();"
                 " xhttp.onreadystatechange = function() {"
                 " if (this.readyState == 4 && this.status == 200) {"
                 " document.getElementById('input-value').innerHTML = this.responseText;"
                 " }"
                 " };"
                 " xhttp.open('GET', 'inputValue', true);"
                 " xhttp.send();"
                 "}"
                 "setInterval(updateInputValue, 1000);"
                 "</script>"
                 "</body>"
                 "</html>" );


Procesar la solicitud de valor de entrada

El sketch debería reconocer la solicitud /inputValue, y obtener el valor de entrada usando la función digitalRead() y enviar la respuesta al cliente.

// ... } else if (path.compareTo("/inputValue") == 0) { // Get the input value int inputValue = digitalRead(I0_1); // Send input value sendText(client, inputValue == HIGH ? "HIGH" : "LOW"); } else { //...

Sería muy bueno enviar un texto JSON o cualquiera de estos sofisticados protocolos de texto estructurado, sobre todo para aplicaciones más complejas, pero en este caso es suficiente enviar una respuesta de texto sin formato.

void sendText(EthernetClient &client, const char *text) {
  client.println("HTTP/1.1 200 OK");
  client.println("Content-Type: text/plain");
  client.println(); client.println(text);
}  


Ejemplo final

#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 if (path.compareTo("/inputValue") == 0) { // Get the input value
              int inputValue = digitalRead(I0_1); // Send input value
              sendText(client, inputValue == HIGH ? "HIGH" : "LOW");
            }
            else { // Unrecognized path
              sendNotFound(client);
            }
            client.flush(); // Close connection
            client.stop();
            break;
          }
          if (c == '\n') {
            emptyLine = true;
            firstLine = false;
          }
          else if (c != '\r') {
            emptyLine = false;
          }
        } // The request is finished when a blank line is received
      }
    }
  }

  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>"
      "<p>Input value: <span id='input-value'></span></p>"
      "<script>"
      "function updateInputValue() {"
      " var xhttp = new XMLHttpRequest();"
      " xhttp.onreadystatechange = function() {"
      " if (this.readyState == 4 && this.status == 200) {"
      " document.getElementById('input-value').innerHTML = this.responseText;"
      " }"
      " };"
      " xhttp.open('GET', 'inputValue', true);"
      " xhttp.send();"
      "}"
      "setInterval(updateInputValue, 1000);"
      "</script>"
      "</body>"
      "</html>"
    );
  }

  void sendText(EthernetClient &client, const char *text) {
    client.println("HTTP/1.1 200 OK");
    client.println("Content-Type: text/plain");
    client.println();
    client.println(text);
  }




No se permite comentar en este curso.