Pessoal, tudo beleza?
Estou tentando juntar 2 sketchs, 1 é o webserver que a principio está acionando um led e o outro manda meu ip pro no-ip pra eu poder acessar fora de casa, mas não estou conseguindo juntar os 2.
Já tentei mixar eles, mas acredito que o problema esteja na hora de atribuir o MAC e o IP.
To quebrando a cabeça nisso!
Valeu galera!
O webserver é:
/* Web_Authentication.ino - Webduino Authentication example */
/* This example assumes that you're familiar with the basics
* of the Ethernet library (particularly with setting MAC and
* IP addresses) and with the basics of Webduino. If you
* haven't had a look at the HelloWorld example you should
* probably check it out first */
/* you can change the authentication realm by defining
* WEBDUINO_AUTH_REALM before including WebServer.h */
#define WEBDUINO_AUTH_REALM "Weduino Authentication Example"
#include "SPI.h"
#include "Ethernet.h"
#include "WebServer.h"
boolean tog1 = false; //rf1 on
boolean tog2 = true; //rf2 off
boolean tog3 = false; //rf3 off
boolean tog4 = true; //rf4 off
/* CHANGE THIS TO YOUR OWN UNIQUE VALUE. The MAC number should be
* different from any other devices on your network or you'll have
* problems receiving packets. */
static uint8_t mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
/* CHANGE THIS TO MATCH YOUR HOST NETWORK. Most home networks are in
* the 192.168.0.XXX or 192.168.1.XXX subrange. Pick an address
* that's not in use and isn't going to be automatically allocated by
* DHCP from your router. */
static uint8_t ip[] = { 192, 168, 2, 133 };
/* This creates an instance of the webserver. By specifying a prefix
* of "", all pages will be at the root of the server. */
#define PREFIX ""
WebServer webserver(PREFIX, 3389);
void defaultCmd(WebServer &server, WebServer::ConnectionType type, char *, bool)
{
server.httpSuccess();
if (type != WebServer::HEAD)
{
P(helloMsg) = "<h1>Hello, World!</h1><a href=\"private.html\">Private page</a>";
server.printP(helloMsg);
}
}
void privateCmd(WebServer &server, WebServer::ConnectionType type, char *, bool)
{
/* if the user has requested this page using the following credentials
* username = user
* password = user
* display a page saying "Hello User"
*
* the credentials have to be concatenated with a colon like
* username:password
* and encoded using Base64 - this should be done outside of your Arduino
* to be easy on your resources
*
* in other words: "dXNlcjp1c2Vy" is the Base64 representation of "user:user"
*
* if you need to change the username/password dynamically please search
* the web for a Base64 library */
if (server.checkCredentials("dXNlcjp1c2Vy"))
{
server.httpSuccess();
if (type != WebServer::HEAD)
{
P(HTMLOPEN) = "<html>";
P(background) = "<body style=background-color:BLACK>"; //set background to BLACK
P(helloMsg) = "<center><font color=’green’> <h1>MARCELO </h1></font></center>";
P(FORMOPEN) = "<form action=formLogin.html method=POST name=LED id=LED><input type=hidden name=botao id=botao value=0";
P(button1) = "<center><button name=tog1 value=1 type=submit style=font-weight:bold;color:GREEN;height:70px;width:145px>PINO 5 On</button>";
P(button2) = "<center><button name=tog2 value=2 type=submit style=font-weight:bold;color:red;height:70px;width:145px>PINO 5 Off</button>";
P(button3) = "<center><button name=tog3 value=3 type=submit style=font-weight:bold;color:GREEN;height:70px;width:145px>ABRIR PORTAOZINHO3</button>";
P(button4) = "<center><button name=tog4 value=4 type=submit style=font-weight:bold;color:red;height:70px;width:145px>ABRIR PORTAOZAO6</button>";
P(FORMCLOSE) = "</form>";
P(BODYCLOSE) = "</body>";
P(HTMLCLOSE) = "</html>";
server.printP(HTMLOPEN);
server.printP(background);
server.printP(helloMsg);
server.printP(FORMOPEN);
server.printP(button1);
server.printP(button2);
server.printP(button3);
server.printP(button4);
server.printP(FORMCLOSE);
server.printP(BODYCLOSE);
server.printP(HTMLCLOSE);
}
}
else
{
/* send a 401 error back causing the web browser to prompt the user for credentials */
server.httpUnauthorized();
}
}
void formCmd(WebServer &server, WebServer::ConnectionType type, char *url_tail, bool tail_complete)
{
if (server.checkCredentials("dXNlcjp1c2Vy"))
{
if (type == WebServer::POST)
{
bool repeat;
char name[16], value[16];
do
{
repeat = server.readPOSTparam(name, 16, value, 16);
/*Serial.print("name: ");
Serial.println(name);
Serial.print("value: ");
Serial.println(value);
*/
if (strncmp("tog1", name, 4) == 0)
{
Serial.println("Botao 1 acionado");
digitalWrite(5, HIGH);
tog1 = true;
break;
}
else if (strncmp("tog2", name, 4) == 0)
{
Serial.println("Botao 2 acionado");
digitalWrite(5, LOW);
tog1 = false;
break;
}
else if (strncmp("tog3", name, 4) == 0)
{
Serial.println("Botao 3 acionado");
digitalWrite(3, HIGH);
delay(1000);
digitalWrite(3, LOW);
tog3 = true;
break;
}
else if (strncmp("tog4", name, 4) == 0)
{
Serial.println("Botao 4 acionado");
digitalWrite(6, HIGH);
delay(1000);
digitalWrite(6, LOW);
tog4 = true;
break;
}
} while (repeat);
server.httpSeeOther(PREFIX "/private.html");
}
}
else
{
server.httpUnauthorized();
}
}
void setup()
{
pinMode(5, OUTPUT);
pinMode(3, OUTPUT);
pinMode(6, OUTPUT);
Serial.begin(115200);
Ethernet.begin(mac, ip);
webserver.setDefaultCommand(&defaultCmd);
webserver.addCommand("index.html", &defaultCmd);
webserver.addCommand("private.html", &privateCmd);
webserver.addCommand("formLogin.html", &formCmd);
webserver.begin();
}
void loop()
{
char buff[64];
int len = 64;
/* process incoming connections one at a time forever */
webserver.processConnection(buff, &len);
}
e o NO-IP é:
// Actualizacion de la IP publica con No-IP - http://url.josematm.com/S
// 2013 Josema - josematm.com
#include <SPI.h>
#include <Ethernet.h>
#include <EEPROM.h>
const char host[] = "xxxx"; //aqui vai meu usuario do no-ip
const char usuarioClave[] = "xxxxxx"; //aqui vai a senha
byte mac[] = { 0xAA, 0xAB, 0xAC, 0xAD, 0xAA, 0xAB };
IPAddress ipLocal(192, 168, 2, 133);
char servidorIP[] = "checkip.dyndns.org";
char servidorActualizacion[] = "dynupdate.no-ip.com";
IPAddress ipActual;
IPAddress ipUltimaEnviada;
void setup() {
Serial.begin(9600);
while (!Serial); // Solo para Leonardo
if (Ethernet.begin(mac) == 0) {
Serial.println("Error consiguiendo la IP por DHCP, intentando manualmente...");
Ethernet.begin(mac, ipLocal);
}
delay(1000);
for (byte n = 0; n <= 3; n++) ipUltimaEnviada[n] = EEPROM.read(n); // Cargamos de EEPROM la ultima IP que se envio.
Serial.print("La IP almacenada en la EEPROM es: ");
Serial.println(ipUltimaEnviada);
}
void loop() {
ipActual = compruebaIP();
if (ipActual != ipUltimaEnviada) {
Serial.print("Actualizando la IP en ");
Serial.print(servidorActualizacion);
Serial.println("...");
if (actualizaIPDynDNS(ipActual) == true){
for (byte n = 0; n <= 3; n++) EEPROM.write(n, ipActual[n]);
ipUltimaEnviada = ipActual;
}
} else {
Serial.println("No hacemos nada, la IP no cambiado desde la ultima vez. Esperando 15 minutos...");
}
delay (900000); // Y esperamos 15 minutos sentados para volver a comprobar la IP.
}
IPAddress compruebaIP() {
EthernetClient cliente;
String webIP;
int desde, hasta;
if (cliente.connect(servidorIP, 80)) {
cliente.println("GET / HTTP/1.0");
cliente.println();
webIP = "";
} else {
Serial.print(":( Conexion fallida con ");
Serial.println(servidorIP);
}
while (cliente.connected()) {
while (cliente.available()) {
webIP.concat((char)cliente.read());
}
}
cliente.stop();
desde = webIP.indexOf("Address: ") + 9;
hasta = webIP.indexOf("</body>");
return ipAIPAddress(webIP.substring(desde, hasta));
}
boolean actualizaIPDynDNS(IPAddress ip) {
EthernetClient cliente;
String webIP;
if (cliente.connect(servidorActualizacion, 80)) {
cliente.print("GET /nic/update?hostname=");
cliente.print(host);
cliente.print("&myip=");
cliente.print(ip);
cliente.println(" HTTP/1.0");
cliente.println("Host: dynupdate.no-ip.com");
cliente.print("Authorization: Basic ");
cliente.println(usuarioClave);
cliente.println("User-Agent: josematm.com - Wirduino - 0.1");
cliente.println();
} else {
Serial.print(":( Conexion fallida con ");
Serial.println(servidorActualizacion);
return false;
}
while (cliente.connected()) {
while (cliente.available()) {
webIP.concat((char)cliente.read());
}
}
Serial.println(webIP);
cliente.stop();
if (webIP.lastIndexOf("badauth") != -1) {
Serial.println("Error de de autentificacion. Comprueba usuario y clave");
return false;
} else {
return true;
}
}
IPAddress ipAIPAddress(String ipEnCadena){
IPAddress ipEnBytes;
char digitoIP[4];
byte cursorDigito = 0;
byte cursorIP = 0;
for (byte n = 0; n < ipEnCadena.length(); n++){
if (ipEnCadena.charAt(n) != '.') {
digitoIP[cursorDigito] = ipEnCadena.charAt(n);
cursorDigito++;
} else {
digitoIP[cursorDigito +1] = '\n';
ipEnBytes[cursorIP] = atoi(digitoIP);
cursorDigito = 0;
memset(digitoIP, 0, sizeof(digitoIP));
cursorIP++;
}
}
digitoIP[cursorDigito +1] = '\n';
ipEnBytes[cursorIP] = atoi(digitoIP);
return ipEnBytes;
}
Tags:
A resposta pra sua pergunta eu nao tenho... Mas quem sabe isso possa ajudar:
Normalmente o Noip ou Dyndns é configurado no Roteador.
Só ele realmente sabe o seu IP externo. La tb vc precisa mapear a porta de acesso para o IP interno.
Se vc puser ele pra fazer esse servico se livra dessa atividade.
O problema é que meu roteador usa o Dyndns e precisa pagar!
As portas já estão configuradas!
Já consegui unir os 2, porém tem um pequeno problema, no voidloop, a parte do webserver precisa sempre estar rodando e a parte do dns apenas a cada 15 minutos (se não bloqueia o serviço do noip). A questão é que no meu sketch ela está rodando com a função delay que trava o meu webserver. Eu precisava trocar essa função de forma que permitisse que a parte acima do delay sempre ficasse rodando e abaixo dele que só a cada quinze minutos rodasse. Alguém pode me ajudar? Pelo que li blink without delay faz isso, mas não tenho muita experiencia em programação e estou tendo dificuldades.
A parte do void loop está abaixo caso alguem possa me ajudar, obrigado.
void loop()
{
char buff[64];
int len = 64;
/* process incoming connections one at a time forever */
webserver.processConnection(buff, &len);
ipActual = compruebaIP();
if (ipActual != ipUltimaEnviada) {
Serial.print("Actualizando la IP en ");
Serial.print(servidorActualizacion);
Serial.println("...");
if (actualizaIPDynDNS(ipActual) == true){
for (byte n = 0; n <= 3; n++) EEPROM.write(n, ipActual[n]);
ipUltimaEnviada = ipActual;
}
} else {
Serial.println("No hacemos nada, la IP no cambiado desde la ultima vez. Esperando 15 minutos...");
}
delay (900000); // Y esperamos 15 minutos sentados para volver a comprobar la IP.
}
IPAddress compruebaIP() {
EthernetClient cliente;
String webIP;
int desde, hasta;
if (cliente.connect(servidorIP, 80)) {
cliente.println("GET / HTTP/1.0");
cliente.println();
webIP = "";
} else {
Serial.print(":( Conexion fallida con ");
Serial.println(servidorIP);
}
while (cliente.connected()) {
while (cliente.available()) {
webIP.concat((char)cliente.read());
}
}
cliente.stop();
desde = webIP.indexOf("Address: ") + 9;
hasta = webIP.indexOf("</body>");
return ipAIPAddress(webIP.substring(desde, hasta));
}
boolean actualizaIPDynDNS(IPAddress ip) {
EthernetClient cliente;
String webIP;
if (cliente.connect(servidorActualizacion, 80)) {
cliente.print("GET /nic/update?hostname=");
cliente.print(host);
cliente.print("&myip=");
cliente.print(ip);
cliente.println(" HTTP/1.0");
cliente.println("Host: dynupdate.no-ip.com");
cliente.print("Authorization: Basic ");
cliente.println(usuarioClave);
cliente.println("User-Agent: josematm.com - Wirduino - 0.1");
cliente.println();
} else {
Serial.print(":( Conexion fallida con ");
Serial.println(servidorActualizacion);
return false;
}
while (cliente.connected()) {
while (cliente.available()) {
webIP.concat((char)cliente.read());
}
}
Serial.println(webIP);
cliente.stop();
if (webIP.lastIndexOf("badauth") != -1) {
Serial.println("Error de de autentificacion. Comprueba usuario y clave");
return false;
} else {
return true;
}
}
IPAddress ipAIPAddress(String ipEnCadena){
IPAddress ipEnBytes;
char digitoIP[4];
byte cursorDigito = 0;
byte cursorIP = 0;
for (byte n = 0; n < ipEnCadena.length(); n++){
if (ipEnCadena.charAt(n) != '.') {
digitoIP[cursorDigito] = ipEnCadena.charAt(n);
cursorDigito++;
} else {
digitoIP[cursorDigito +1] = '\n';
ipEnBytes[cursorIP] = atoi(digitoIP);
cursorDigito = 0;
memset(digitoIP, 0, sizeof(digitoIP));
cursorIP++;
}
}
digitoIP[cursorDigito +1] = '\n';
ipEnBytes[cursorIP] = atoi(digitoIP);
return ipEnBytes;}
em vez de utilizar o delay, pense na função millis().. faça uma comparaçao entre o tempo que tem agora com o tempo que já passou se for superior ao tempo que deseja entao permite a chamada da funçao que precisa... caso a minha explicação nao tenha" aberto a porta" poderei deixa escrito como fazer...
Entao, eu tentei com a função millis, mas eu nao estou conseguindo!
Se puder me dar uma ajuda eu agradeço muito!
Você pode me enviar o código completo, estava precisando de algo assim...
Testa este código que eu fiz agora e me diz se funciona :)
unsigned long ultimomillis = 0;
unsigned long millisatual;
void setup() {
}
void loop() {
millisatual = millis();
if(millisatual - ultimomillis >= 900000){
//Faz o que você deseja aqui :)
}
}
Só faltou um pormenor... tens de actualizar o ultimomillis dentro do if
unsigned long ultimomillis = 0;
unsigned long millisatual;
void setup() {
}
void loop() {
millisatual = millis();
if(millisatual - ultimomillis >= 900000){
//Faz o que você deseja aqui :)
ultimomillis=millis(); // a actualização do ultimo millis para poder fazer as próximas comparações
}
}
Obrigado esqueci completamente, fiz com pressa para ajudar nosso amigo.
Essa ideia de atualizaro o noip foi fantástica.
A função que vc precisa usar é o blink without delay.
Olha o exemplo na ide do arduino.
Se não conseguir avisa que resolvemos isso.
Mas essa ideia já está descrita pelo Raphael afonso
Bem-vindo a
Laboratorio de Garagem (arduino, eletrônica, robotica, hacking)
© 2024 Criado por Marcelo Rodrigues. Ativado por