Internet de las Cosas: Controlando tu casa desde tu móvil

por | May 26, 2015 | Domótica | 0 Comentarios

El Internet de las cosas (IoT, Internet of Things) se refiere a la digitalización de los objetos que usamos a diario. Si todos los objetos cotidianos estuvieran conectados a Internet, podrían ser gestionados por otros equipos de igual forma que si lo manejáramos manualmente pero a distancia.

Este post va dirigido a controlar y saber el estado de todas las luces de nuestro hogar. Para ello utilizaremos un servidor online, https://thingspeak.com, cuya función es tenernos actualizados del estado de las bombillas en todo momento.

En primer lugar tenemos que registrarnos para poder utilizar dicho servidor online.

Una vez registrados, vemos que ha generado una key, la cual utilizaremos para poder ver el estado online de los dispositivos a través de la siguiente url: “https://api.thingspeak.com/channels/Channel_id/feed.json?key= api_key

Sustituimos en cada uno de los casos de la url nuestro canal y nuestra key. Podemos encontrar el id del canal en “channel setting” y las key en ”API Keys”, como se muestra en las siguientes imágenes.

Channel Setting

API Keys

Una vez obtenidos todos los datos hay que depurar un poco la url para que solo nos muestre el último estado obtenido. El resultado final de la url se muestra en la siguiente imagen:

URL estado


El siguiente paso que tenemos que dar es conseguir que nos muestre solo el 0 o 1 y una vez conseguido hacer que al recibir un 0 se muestre “Off” y al recibir un 1 se muestre “On”. Para ellos lo conseguimos con Javascript en el código html:

<script>

function updateData2(){

var xmlhttp = new XMLHttpRequest();

xmlhttp.onreadystatechange=function()

{

if (xmlhttp.readyState==4 && xmlhttp.status==200)

{

var JSONObject = JSON.parse(xmlhttp.responseText);

var jfeeds = JSONObject.feeds;

document.getElementById("estado").innerHTML =JSONObject.field1;

 

var result = JSONObject.field1;

if (result=="0"){

document.getElementById("estado").innerHTML = "OFF";

document.getElementById("myonoffswitch").innerHTML = $(myonoffswitch).prop("checked", false);

}else if (result=="1"){

document.getElementById("estado").innerHTML = "ON";

document.getElementById("myonoffswitch").innerHTML = $(myonoffswitch).prop("checked", true);

}else{

document.getElementById("estado").innerHTML = "ERROR";

}

}

}

xmlhttp.open("GET", "https://api.thingspeak.com/channels/XXXXX/feeds/last.json?key=XXXXXXXXXXXXXXXX",true);

xmlhttp.send();

}

window.onload = function() {

setInterval(updateData2, 1000);

}

</script>

En el anterior post sobre domótica vimos como conectar el modulo wifi ESP8266 a un Arduino y encender bombillas. Ahora vamos a ver los comandos que necesitamos para conectar el modulo wifi a la red donde tengamos la instalación y a su vez interactuar con el servidor online. Así vamos a saber siempre el estado de las luces.

#include <SoftwareSerial.h>

#define DEBUG true

SoftwareSerial esp8266(2,3);

int rele =10;
int estado;
void setup() {
Serial.begin(19200);
esp8266.begin(19200);
pinMode(10,OUTPUT);
digitalWrite(10,LOW);

sendData("AT+RSTrn",2000,DEBUG); // reset module
sendData("AT+CWMODE=1rn",2000,DEBUG); // configure as access point
//sendData("AT+CIFSRrn",000,DEBUG); // get ip address
sendData("AT+CIPMUX=1rn",2000,DEBUG); // configure for multiple connections
sendData("AT+CIPSERVER=1,80rn",2000,DEBUG); // turn on server on port 80
sendData("AT+CWLAPrn",2000,DEBUG);
sendData("AT+CWJAP='"'Wifi'"','"'MaestroYoda'"'rn",5000,DEBUG);
sendData("AT+CIFSRrn",2000,DEBUG);

}

void loop() {

if(esp8266.available()) // check if the esp is sending a message
{


if(esp8266.find("+IPD,"))
{
delay(1000); // wait for the serial buffer to fill up (read all the serial data)
// get the connection id so that we can then disconnect
int connectionId = esp8266.read()-48; // subtract 48 because the read() function returns
// the ASCII decimal value and 0 (the first decimal number) starts at 48

esp8266.find("pin="); // advance cursor to "pin="

int pinNumber = (esp8266.read()-48)*10; // get first number i.e. if the pin 13 then the 1st number is 1, then multiply to get 10
pinNumber += (esp8266.read()-48); // get second number, i.e. if the pin number is 13 then the 2nd number is 3, then add to the first number

digitalWrite(pinNumber, !digitalRead(pinNumber)); // toggle pin
if (pinNumber ==rele){
updateData();
}
// make close command
String closeCommand = "AT+CIPCLOSE=";
closeCommand+=connectionId; // append connection id
closeCommand+="rn";

sendData(closeCommand,1000,DEBUG); // close connection
}
}
}

void updateData(){
sendData("AT+CIPSTART=4,"TCP","184.106.153.149",80rn",1000,DEBUG);
estado = digitalRead(rele);
if(estado==HIGH){
80rn",1000,DEBUG);
sendData("AT+CIPSEND=4,45rnn",1000,DEBUG);
sendData("GET /update?key=8CQRGJU77FS0B1U3&field1=1rn",1000,DEBUG);
sendData("AT+CIPCLOSErn",1000,DEBUG);

}else{

80rn",1000,DEBUG);
sendData("AT+CIPSEND=4,45rn",1000,DEBUG);
sendData("GET /update?key=8CQRGJU77FS0B1U3&field1=0rn",1000,DEBUG);
sendData("AT+CIPCLOSErn",1000,DEBUG);
}
}
String sendData(String command, const int timeout, boolean debug)
{
String response = "";

esp8266.print(command); // send the read character to the esp8266

long int time = millis();

while( (time+timeout) > millis())
{
while(esp8266.available())
{

// The esp has data so display its output to the serial window
char c = esp8266.read(); // read the next character.
response+=c;
}
}

if(debug)
{
Serial.print(response);
}

return response;

}

Por último a través de la interfaz web,  hemos creado un botón para mandar la petición ON/OFF. Al pulsarlo enviamos al servidor una orden de cambio de estado.

Status

Una vez funcionando el servidor y la interfaz web correctamente configurada para funcionar también con el Arduino que controla la bombilla, ya podemos saber el estado de las luces de nuestro hogar en cualquier parte del mundo. Es sólo un pequeño paso para empezar con el uso del Internet de las Cosas.

0 comentarios

Enviar un comentario

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *

Conoce conceptos clave de la era digital en nuestro HUB

 

 

Descarga nuestro ebook con todo lo que necesitas saber sobre IoT Industrial.

Suscríbete a nuestra newsletter

Recibe las últimas noticias sobre innovación y nuevas tecnologías y mantente al día de los avances más destacados

Cesión de datos

Calle Factores 2, 41015 Seville

Phone: +34 618 72 13 58

Email: info@secmotic.com

MENU

We are

We do

Blog

Contact