Buen día, el inconveniente que tengo es no ejecuta las ordenes de encendido y apagado que le envío por el explorador web.
he logrado conseguir dos códigos: uno que pide autenticacion antes de entrar al servidor web y otro que entras sin autenticacion pero en este sí funcionan las ordenes de encendido y apagado.
El problema es que no logro que haga ambas cosas al mismo tiempo, es decir pedir autenticacion, desplegar la pagina y que se ejecuten las ordenes que envió desde la pagina.
Les estaría muy agradecido de su ayuda por favor
el password es: php:nein
#include <SPI.h>
#include <Ethernet.h>
// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network:
byte mac[] = {
0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip(192,168,1, 111);
// Initialize the Ethernet server library
// with the IP address and port you want to use
// (port 80 is default for HTTP):
EthernetServer server(80);
int relay=6; //Pin del led
String estado="OFF"; //Estado del Led inicialmente "OFF"
void setup() {
// Open serial communications and wait for port to open:
Serial.begin(9600);
// start the Ethernet connection and the server:
Ethernet.begin(mac, ip);
server.begin();
Serial.print("server is at ");
Serial.println(Ethernet.localIP());
pinMode(relay,OUTPUT);
}
void SendOKpage(EthernetClient &client)
{
client.println("<html>");
client.println("<head>");
client.println("</head>");
client.println("<body>");
client.println("<h1 align='center'>ELECTROMECANICA UASD</h1><h3 align='center'>Sistema de Monitoreo y Control de la Energia</h3><h5 align='center'>Que usted quiere hacer?</h5>");
//Creamos los botones. Para enviar parametres a través de HTML se utiliza el metodo URL encode. Los parámetros se envian a través del símbolo '?'
client.println("<div style='text-align:center;'>");
client.println("<button onClick=location.href='./?estado=ON\' style='margin:auto;background-color: #FF0000;color: snow;padding: 10px;border: 1px solid #3F7CFF;width:65px;'>");
client.println("ON");
client.println("</button>");
client.println("<button onClick=location.href='./?estado=OFF\' style='margin:auto;background-color: #FF0000;color: snow;padding: 10px;border: 1px solid #3F7CFF;width:65px;'>");
client.println("OFF");
client.println("</button>");
client.println("
");
client.println("<b>estado = ");
client.print(estado);
client.println("</b>
");
client.println("</b></body>");
client.println("</html>");
}
void SendAuthentificationpage(EthernetClient &client)
{
client.println("HTTP/1.1 401 Authorization Required");
client.println("WWW-Authenticate: Basic realm=\"Secure Area\"");
client.println("Content-Type: text/html");
client.println("Connnection: close");
client.println();
client.println("<!DOCTYPE HTML>");
client.println("<HTML> <HEAD> <TITLE>Error</TITLE>");
client.println(" </HEAD> <BODY><H1>401 Unauthorized.</H1></BODY> </HTML>");
}
char linebuf[80];
int charcount=0;
boolean authentificated=false;
void loop() {
// listen for incoming clients
EthernetClient client = server.available();
if (client) {
Serial.println("new client");
memset(linebuf,0,sizeof(linebuf));
charcount=0;
authentificated=false;
// an http request ends with a blank line
boolean currentLineIsBlank = true;
while (client.connected()) {
if (client.available()) {
char c = client.read();
linebuf[charcount]=c;
if (charcount<sizeof(linebuf)-1) charcount++;
Serial.write(c);
// 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 (authentificated)
SendOKpage(client);
else
SendAuthentificationpage(client);
break;
}
if (c == '\n') {
// you're starting a new line
currentLineIsBlank = true;
if (strstr(linebuf,"Authorization: Basic")>0 && strstr(linebuf,"cGhwOm5laW4=")>0)
authentificated=true;
memset(linebuf,0,sizeof(linebuf));
charcount=0;
}
else if (c != '\r') {
// you've gotten a character on the current line
currentLineIsBlank = false;
}
}
}
// give the web browser time to receive the data
delay(1);
// close the connection:
client.stop();
Serial.println("client disonnected");
}
}
ESTE ES EL CÓDIGO QUE FUNCIONA PERFECTAMENTE PERO SIN PASSWORD
#include <SPI.h> //Importamos librería comunicación SPI
#include <Ethernet.h> //Importamos librería Ethernet
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip(192,168,1,111); //Le damos la IP elegida a Arduino
EthernetServer server(80); //Creamos un servidor Web con el puerto 80 que es el puerto HTTP por defecto
int led=6; //Pin del led
String estado="OFF"; //Estado del Led inicialmente "OFF"
void setup()
{
Serial.begin(9600);
// Inicializamos la comunicación Ethernet y el servidor
Ethernet.begin(mac, ip);
server.begin();
Serial.print("server is at");
Serial.println(Ethernet.localIP());
pinMode(led,OUTPUT);
}
void loop()
{
EthernetClient client = server.available(); //Creamos un cliente Web
if (client) {// Entra en el "if" si detecta un cliente a través de una petición HTTP
Serial.println("new client");
boolean currentLineIsBlank = true; //Una petición HTTP acaba con una línea en blanco
String cadena=""; //Creamos una cadena de caracteres vacía
while (client.connected()) {
if (client.available()) {
char c = client.read();//Leemos la petición HTTP carácter por carácter
Serial.write(c);//Visualizamos la petición HTTP por el Monitor Serial
cadena.concat(c);//Unimos el String 'cadena' con la petición HTTP (c). De esta manera convertimos la petición HTTP a un String
//Ya que hemos convertido la petición HTTP a una cadena de caracteres, ahora podremos buscar partes del texto.
int posicion=cadena.indexOf("SYSTEM="); //Guardamos la posición de la instancia "SYSTEM=" a la variable 'posicion'
if(cadena.substring(posicion)=="SYSTEM=ON")//Si a la posición 'posicion' hay "SYSTEM=ON"
{
digitalWrite(led,HIGH);
estado="ON";
}
if(cadena.substring(posicion)=="SYSTEM=OFF")//Si a la posición 'posicion' hay "SYSTEM=OFF"
{
digitalWrite(led,LOW);
estado="OFF";
}
//Cuando reciba una línea en blanco, quiere decir que la petición HTTP ha acabado y el servidor Web está listo para enviar una respuesta
if (c == '\n' && currentLineIsBlank) {
// Enviamos al cliente una respuesta HTTP
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println();
//Página web en formato HTML
client.println("<html>");
client.println("<head>");
client.println("</head>");
client.println("<body>");
client.println("<h1 align='center'>ELECTROMECANICA UASD</h1><h3 align='center'>Sistema de Monitoreo y Control de la Energia</h3><h5 align='center'>Que usted quiere hacer?</h5>");
//Creamos los botones. Para enviar parametres a través de HTML se utiliza el metodo URL encode. Los parámetros se envian a través del símbolo '?'
client.println("<div style='text-align:center;'>");
client.println("<button onClick=location.href='./?SYSTEM=ON\' style='margin:auto;background-color: #FF0000;color: snow;padding: 10px;border: 1px solid #3F7CFF;width:65px;'>");
client.println("ON");
client.println("</button>");
client.println("<button onClick=location.href='./?SYSTEM=OFF\' style='margin:auto;background-color: #FF0000;color: snow;padding: 10px;border: 1px solid #3F7CFF;width:65px;'>");
client.println("OFF");
client.println("</button>");
client.println("
");
client.println("<b>SYSTEM = ");
client.print(estado);
client.println("</b>
");
client.println("</b></body>");
client.println("</html>");
break;
}
if (c == '\n') {
currentLineIsBlank = true;
}
else if (c != '\r') {
currentLineIsBlank = false;
}
}
}
//Dar tiempo al navegador para recibir los datos
delay(1);
client.stop();// Cierra la conexión
}
}
Y ESTE ES EL CÓDIGO DEL SERVIDOR CON PASSWORD
/*
* Web Server
*
* A simple web server with basic HTTP authentication
*
* Circuit:
* Ethernet shield attached to Arduino board
* Analog inputs attached to pins A0 through A5 (optional)
*/
#include <SPI.h>
#include <Ethernet.h>
// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network:
byte mac[] = {
0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip(192,168,2, 111);
// Initialize the Ethernet server library
// with the IP address and port you want to use
// (port 80 is default for HTTP):
EthernetServer server(80);
void setup() {
// Open serial communications and wait for port to open:
Serial.begin(9600);
// start the Ethernet connection and the server:
Ethernet.begin(mac, ip);
server.begin();
Serial.print("server is at ");
Serial.println(Ethernet.localIP());
}
void SendOKpage(EthernetClient &client)
{
// send a standard http response header
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println("Connnection: close");
client.println();
client.println("<!DOCTYPE HTML>");
client.println("<html>");
// add a meta refresh tag, so the browser pulls again every 5 seconds:
client.println("<meta http-equiv=\"refresh\" content=\"5\">");
// output the value of each analog input pin
for (int analogChannel = 0; analogChannel < 6; analogChannel++) {
int sensorReading = analogRead(analogChannel);
client.print("analog input ");
client.print(analogChannel);
client.print(" is ");
client.print(sensorReading);
client.println("
");
}
client.println("</html>");
}
void SendAuthentificationpage(EthernetClient &client)
{
client.println("HTTP/1.1 401 Authorization Required");
client.println("WWW-Authenticate: Basic realm=\"Secure Area\"");
client.println("Content-Type: text/html");
client.println("Connnection: close");
client.println();
client.println("<!DOCTYPE HTML>");
client.println("<HTML> <HEAD> <TITLE>Error</TITLE>");
client.println(" </HEAD> <BODY><H1>401 Unauthorized.</H1></BODY> </HTML>");
}
char linebuf[80];
int charcount=0;
boolean authentificated=false;
void loop() {
// listen for incoming clients
EthernetClient client = server.available();
if (client) {
Serial.println("new client");
memset(linebuf,0,sizeof(linebuf));
charcount=0;
authentificated=false;
// an http request ends with a blank line
boolean currentLineIsBlank = true;
while (client.connected()) {
if (client.available()) {
char c = client.read();
linebuf[charcount]=c;
if (charcount<sizeof(linebuf)-1) charcount++;
Serial.write(c);
// 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 (authentificated)
SendOKpage(client);
else
SendAuthentificationpage(client);
break;
}
if (c == '\n') {
// you're starting a new line
currentLineIsBlank = true;
if (strstr(linebuf,"Authorization: Basic")>0 && strstr(linebuf,"cGhwOm5laW4=")>0)
authentificated=true;
memset(linebuf,0,sizeof(linebuf));
charcount=0;
}
else if (c != '\r') {
// you've gotten a character on the current line
currentLineIsBlank = false;
}
}
}
// give the web browser time to receive the data
delay(1);
// close the connection:
client.stop();
Serial.println("client disonnected");
}
}