Test Foro de elhacker.net SMF 2.1

Informática => Electrónica => Mensaje iniciado por: arcross88 en 4 Mayo 2016, 01:39 AM

Título: Comunicacion Arduino-Servidor
Publicado por: arcross88 en 4 Mayo 2016, 01:39 AM
Antes que nada, perdon si estoy en la sección incorrecta. Mi objetivo es lograr que un sketch de Arduino ejecute un script php en un servidor y lea lo que este devuelve.
La idea es que el sketch mande un post con el estado de un led al servidor y que un script php lo reciba, actualice la base de datos segun el valor recibido y mande el valor de otro campo de la misma tabla.
La tabla con la que se interactua (nombrada control) tiene estos campos y entrada:




devicestatusaction
led100

El campo que se va a sobreescribir el status, mientras que el que se va a leer y devolver al arduino es action.

El script php (hardware.php) es:

require_once("connect.php");

$dev = $_POST['device'];
$value = $_POST['value'];

if ($value == "255") {
   $value = 255;
}
if ($value == "0") {
   $value = 0;
}

$db = "dbname";
mysqli_select_db($connection, $db);

$write = "UPDATE control SET status = $value WHERE device='$dev'";
$reswrite = mysqli_query($connection, $write);

$query = "SELECT * FROM control";
$result = mysqli_query($connection, $query);

while ($row = mysqli_fetch_assoc($result)) {
if($row['action'] == 0){
   echo 'a';
}
if($row['action'] == 255){
   echo 'b';
}
}

?>

El archivo incluido connect.php tiene la informacion de conexion a la base de datos y funciona correctamente.

El sketch de arduino es un ejemplo modificado:


#include <Ethernet.h>

int led1 = 8;

// assign a MAC address for the ethernet controller.
// fill in your address here:
byte mac[] = {
 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
};
// fill in an available IP address on your network here,
// for manual configuration:
//IPAddress ip(192, 168, 1, 177);

// fill in your Domain Name Server address here:
//IPAddress myDns(1, 1, 1, 1);

// initialize the library instance:
EthernetClient client;

char server[] = "SERVERNAME";
//IPAddress server(64,131,82,241);

unsigned long lastConnectionTime = 0;             // last time you connected to the server, in milliseconds
const unsigned long postingInterval = 1000L; // delay between updates, in milliseconds
// the "L" is needed to use long type numbers

void setup() {
 // give the ethernet module time to boot up:
 delay(1000);
 // start the Ethernet connection using a fixed IP address and DNS server:
 Ethernet.begin(mac);

 pinMode(led1, OUTPUT);
 digitalWrite(led1, HIGH);
 delay(1000);
 digitalWrite(led1, LOW);
 delay(1000);
}

void loop() {
 // if there's incoming data from the net connection.
 // send it out the serial port.  This is for debugging
 // purposes only:
 if (client.available()) {
   char c = client.read();
   if(c == 'a'){
     digitalWrite(led1, LOW);
   }
   if(c == 'b'){
     digitalWrite(led1, HIGH);
   }
 }

 // if ten seconds have passed since your last connection,
 // then connect again and send data:
 if (millis() - lastConnectionTime > postingInterval) {
   httpRequest();
 }

}

// this method makes a HTTP connection to the server:
void httpRequest() {
 // close any connection before send a new request.
 // This will free the socket on the WiFi shield
 client.stop();

 String stat;
 if(digitalRead(led1) == HIGH){
   stat+="";
   stat+="255";
 }
 if(digitalRead(led1) == LOW){
   stat+="";
   stat+="0";
 }
 String data;
 data+="";
 data+="device=led1&value=" + stat;

 // if there's a successful connection:
 if (client.connect(server, 80)) {
   // send the HTTP PUT request:
   client.println("POST /php/hardware.php HTTP/1.1");
   client.println("Host: HERE-WAS-THE-SERVERNAME");
   client.println("Content-Type: application/x-www-form-urlencoded");
   client.println("Connection: close");
   client.print("Content-Length: ");
   client.println(data.length());
   client.println();
   client.print(data);
   client.println();

   // note the time that the connection was made:
   lastConnectionTime = millis();
 } else {
   // if you couldn't make a connection:
 }
}


No logre que esto funcione y no pude identificar el error. Si pudiesen ayudarme o darme alguna sugerencia, consejo o pista sobre lo que va mal, estaria agradecido.
Gracias!
Título: Re: Comunicacion Arduino-Servidor
Publicado por: peter_lyon en 26 Junio 2016, 02:35 AM
Con esta librería puedes montar una API REST en un arduino, a través de cualquier forma de comunicación (serie, ethernet, wifi, xbee...).

Yo la he usado en proyectos similares, lo que hacíamos es lo siguiente:

- Usuario (navegador) manda petición web al servidor.
- El servidor web (python en nuestro caso) a su vez, hace una petición web a la ip en la que está el arduino, y recibe el estado del led, o lo cambia de estado.
- Con la información actualizada generas el html para la respuesta al cliente.
- Usuario (navegador) recibe la respuesta.

Yo lo tengo implementado en una aplicación Django (python), si quieres te la mando para que le eches un vistazo o la uses, te puede ser muy útil para domótica o sistemas industriales.