77
Alberto Sagredo Castro www.voipnovatos.es Domótica

V2 d2013 alberto sagredo - domótica

Embed Size (px)

Citation preview

Page 1: V2 d2013   alberto sagredo - domótica

Alberto Sagredo Castro

www.voipnovatos.es

Domótica

Page 2: V2 d2013   alberto sagredo - domótica

¿Quién soy? • Alberto Sagredo Castro

• @albersag

• Alicantino de adopción.

• Entusiasta de mi trabajo y autodidacta.

• Formación Asterisk, Kamailio.

• Consultoría e Ingeniería en VoIP.

• Más info http://www.linkedin.com/in/albersag

Alberto Sagredo Castro

www.voipnovatos.es

Page 3: V2 d2013   alberto sagredo - domótica

Tópicos de la domótica• La domótica es cara.

• La domótica es complicada.

• La domótica sólo la tiene Bill Gates en su casa.

• La domótica es exclusiva.

• La domótica es propietaria y cerrada.

www.voipnovatos.es

Alberto Sagredo Castro

Page 4: V2 d2013   alberto sagredo - domótica

Realidad de la domótica• La domótica NO es cara.

• La domótica NO es complicada.

• La domótica supone un coste de un 1 % de la vivienda.

• La domótica es de ámbito plural.

• La domótica puede ser lo abierta que queráis.

www.voipnovatos.es

Alberto Sagredo Castro

Page 5: V2 d2013   alberto sagredo - domótica

¿Para qué sirve?• Eficiencia y Ahorro energético

• Seguridad (Intrusión, inundación, incendio....)Accionamiento remoto de dispositivos

• Confort, control.

• Ocio/Comunicaciones Multimedia

• eSalud

• Robótica de servicios (limpieza, cortar césped.)

www.voipnovatos.es

Alberto Sagredo Castro

Page 6: V2 d2013   alberto sagredo - domótica

Historia de la Domótica

Page 7: V2 d2013   alberto sagredo - domótica

Protocolo X10 • Protocolo que nace en en los 70’s.

• Comunicación por los cables de electricidad (Powerline).

• Depende del cableado iba mejor o peor.

• Es el más “consolidado”.

• No hay “feedback” del estado del dispositivo.

• Usado mucho en entorno Industrial.

• Direccionamiento limitado de dispositivos (16 x 16 ).

Page 8: V2 d2013   alberto sagredo - domótica

Protocolo • Protocolo creado y controlado por Zensys. Comprado x Sigma Designs

• Comunicación Wireless en 868 Mhz (EU) 908 Mhz (USA)

• Red Mesh entre los dispositivos.

• El que mayor expansión y apoyo de fabricantes hoy en día.

• Hay feedback del estado del dispositivo.

• Fácil instalación y despliegue.

• Soporte Local de vendedores. (zwave.es)

• Opciones SW Libre Open-zwave. HW Zensys

• Bajo Consumo

• Zwave Alliance con más de 400 fabricantes y 900 dispositivos certificados.

• Interoperabilidad entre fabricantes buenísima

Page 9: V2 d2013   alberto sagredo - domótica

Protocolo • Especificación de 2004

• Banda ISM 2.4 Ghz (otra cosa más en esta banda). Aunque se permite en estándar 868 Mhz (EU) 915 Mhz (USA)

• Controlador de hasta 65535 nodos. (subredes de 255 nodos)

• Bajo Consumo

• Hasta 300 Kb/s

• Topología estrella, árbol o malla (la más usada).

• Se espera que sea la más usada o más barata.

• Pocos dispositivos. Usado por wattio (Startup Bilbaína)

• Interoperabilidad entre fabricantes por ver…

• Especificación IPV6 04/02/2013

Page 10: V2 d2013   alberto sagredo - domótica

Protocolo • IPV6 over Low Power Wireless Personal Area Network

• Tiene IPV6!! (Olle Johansson would like it!)

• Estándar del IETF

• Bajo Consumo

• Encriptación AES-CCM 128

• Topología Mesh

• Tráfico Bidireccional

• ¿Estándar de futuro?

• Muy pocos dispositivos. Dispositivos de Laboratorio.

• Conectado mundialmente a Internet o bien PAN controlada por router local.

• OS Contiki o tinyOS 6lowpan native.

Page 11: V2 d2013   alberto sagredo - domótica

Protocolo • Creado por Belkin

• Interfaz Wifi a dispositivos domóticos

• Actualmente tres dispositivos: Interruptor de pared, interruptor de enchufe y sensor de presencia

• Protocolo UnPn

• Todavía sin API abierta

• Afortundamente Ingeniería Inversa y Wemo Hacking

• Para Activar necesario iPhone // Android

• ¿Interoperabilidad? No pidáis peras al olmo

Page 12: V2 d2013   alberto sagredo - domótica

Protocolo • Creado por Phillips

• Interfaz Wifi a dispositivos domóticos

• Control y Color de luces. Orientado a Iluminación

• Protocolo UnPn

• API abierta (http://developers.meethue.com)

• IPhone / Android needed!

• Caro

Page 13: V2 d2013   alberto sagredo - domótica

Fabricantes Z-waveLos más conocidos:

• Fibaro

• Everspring

• Fortrezz

• Micasaverde (Vera)

• Zipato

• Aeon Labs

• Danfoss

Page 14: V2 d2013   alberto sagredo - domótica

Zipato• Fabricantes del Zipabox

• Gateway orientado a la “cloud”

• API muy abierta , JSON, REST-API

• Muy abiertos a resolución de bugs

• En el origen muy desconcertante

• Gestión y configuración mediante interfaz web. Rules Creator Gráfico

• 1 año escaso en el mercado

• Se ha consolidado como una opción a tener en cuenta

• Dispone de Addons para Zigbee, KNX, y Backup Module.

• Apps nativas para Android / Iphone

• Precio aprox 199 euros

Page 15: V2 d2013   alberto sagredo - domótica

Vera Lite • Fabricado por Micasaverde (USA)

• Gateway orientado a nube y local

• API JSON, XML , amplísimas opciones de integración

• UnPn

• Soporte de usuarios muy bueno (http://forum.micasaverde.com)

• Gran Cantidad de Plugins

• Interfaz Web local.

• Soporte remoto del fabricante cuando problemas de integración

• El que tiene más solera.

• En proceso de cambio. Mejorando web y más modelos de Vera

• Integración con otros protocolos mediante dongles USB o bien plugins (Wemo) (Phillips Hue)

• Apps compatibles iPhone/Android

• Lo puedes encontrar por 170 euros

Page 16: V2 d2013   alberto sagredo - domótica

Vera: Integración mediante HTTP

Documentados:

• http://wiki.micasaverde.com/index.php/Luup_Requests

!• ACTION: http://ip_address:3480/data_request?

id=action&output_format=xml&DeviceNum=6&serviceId=urn:upnp-org:serviceId:SwitchPower1&action=SetTarget&newTargetValue=1

!• RUN SCENE: http://ip_address:3480/data_request?id=lu_action&serviceId=urn:micasaverde-

com:serviceId:HomeAutomationGateway1&action=RunScene&SceneNum=<SceneNum>

!• VARIABLE GET: http://ip_address:3480/data_request?id=variableget&DeviceNum=6&serviceId=urn:micasaverde-

com:serviceId:DoorLock1&Variable=Status

!• VARIABLE SET : http://ip_address:3480/data_request?id=variableset&DeviceNum=6&serviceId=urn:micasaverde-

com:serviceId:DoorLock1&Variable=Status&Value=1

!• SNAPSHOT CAMERA: http://ip_address:3480/data_request?id=archive_video&cam=8&format=1

Page 17: V2 d2013   alberto sagredo - domótica

Alternativas “Do it yourself”

Page 18: V2 d2013   alberto sagredo - domótica

Raspberry PI

• Podemos usar un stick USB Zwave como AEON LABS y user z-wave me

!

!

• O bien usar una “mochila”

!

!

Page 19: V2 d2013   alberto sagredo - domótica

Z-wave Me

• Z-wave me lanzó un dispositivo Razberry conectado directamente al puerto GPIO de la Raspberry PI (http://razberry.z-wave.me)

• Puede usarse el USB de AEON LABS también

!

!

!

• http://en.z-wave.me/

Page 20: V2 d2013   alberto sagredo - domótica

Open Z-wave• Interfaz Open Source para Zwave

(https://code.google.com/p/open-zwave)

• Z-wave me lanzó un dispositivo Razberry conectado directamente al puerto GPIO de la Raspberry PI (http://razberry.z-wave.me)

• Controlar un interruptor con Open z-wave http://www.agilart.com/blog/open-zwave

!

!

Page 21: V2 d2013   alberto sagredo - domótica

Open Remote

• Open Source Automation Platform

http://www.openremote.org/display/HOME/OpenRemote

• Se integra con AMX, KNX, Lutron, Z-Wave, 1-Wire, EnOcean, xPL, Insteon, X10, Infrared, Russound, GlobalCache, IRTrans, XBMC, VLC, panStamps, Denon AVR, FreeBox, MythTV, and more.

• Cross Platform Windows, Linux, Mac, Raspberry Pi, Alix, Synology, ReadyNAS, QNAP and others.

Page 22: V2 d2013   alberto sagredo - domótica

Aplicaciones Smartphones

• Existen las propias aplicaciones de los fabricantes (Zipato, Vera).

• Las de Android más “potentes” que las que rondan por Apple Store.

!

!

!

Page 23: V2 d2013   alberto sagredo - domótica

Demo #1 : Home Automation Phone System

Elementos Inteligentes:

- Zipato

- Asterisk

- Raspberry Pi

-

- Instalador

Page 24: V2 d2013   alberto sagredo - domótica

Demo #1 : Home Automation Phone System

Sensores:

- Fibaro Wall Plug

- Fortrezz Siren

!

Page 25: V2 d2013   alberto sagredo - domótica

Demo #1 : Home Automation Phone System

Esquema de Funcionamiento:

my.zipato.com

Page 26: V2 d2013   alberto sagredo - domótica

Demo #1 : Home Automation Phone System

Page 27: V2 d2013   alberto sagredo - domótica

Demo #1 : Home Automation Phone System

Dialplan Asterisk: [ivr] !exten => s,1,Answer() exten => s,n,Background(demovoipnovatos) exten => s,n,Wait(5) exten => s,n,agi(speech-recog.agi,es) exten => s,n,Set(PrimeraWord=${CUT(${utterance},\x20,1)}) exten => s,n,Set(SegundaWord=${CUT(${utterance},\xNN,2)}) exten => s,n,GotoIf($["${utterance}" = "encender luz"]?encenderluz) exten => s,n,GotoIf($["${utterance}" = "apagar luz"]?apagarluz) exten => s,n,GotoIf($["${utterance}" = "encender sirena"]?encendersirena) exten => s,n,GotoIf($["${utterance}" = "encender wemo"]?encenderwemo) exten => s,n,GotoIf($["${utterance}" = "apagar wemo"]?apagarwemo) exten => s,n,Verbose(1,El texto reconocido es: ${utterance}) exten => s,n,Verbose(1,Con una probabilidad de acierto: ${confidence}) exten => s,n,Verbose(1,La primera palabra es ${PrimeraWord} y la segunda palabra es ${SegundaWord} ) exten => s,n,Hangup ;exten => 800,n(encenderluz),Set(foo=${CURL(http://lampara.voip2day.voipnovatos.es/encender)}) exten => s,n(encenderluz),System(wget "http://lampara.voip2day.voipnovatos.es/encender") exten => s,n,Playback(luzencendida) exten => s,n,Hangup() ;exten => 800,n(apagarluz),Set(foo=${CURL(http://lampara.voip2day.voipnovatos.es/apagar)}) exten => s,n(apagarluz),System(wget "http://lampara.voip2day.voipnovatos.es/apagar") exten => s,n,Playback(luzapagada) exten => s,n,Hangup() exten => s,n(encendersirena),System(wget "http://sirena.voip2day.voipnovatos.es/encender") exten => s,n,Playback(sirenaencendida) exten => s,n,Hangup() exten => s,n(encenderwemo),System(wget "http://wemo.voip2day.voipnovatos.es/enchufe/encender") exten => s,n,Playback(wemoencendido) exten => s,n,Hangup() exten => s,n(apagarwemo),System(wget "http://wemo.voip2day.voipnovatos.es/enchufe/apagado") exten => s,n,Playback(wemoapagado) exten => s,n,Hangup()

Page 28: V2 d2013   alberto sagredo - domótica

Demo #1 : Home Automation Phone System

Dialplan Asterisk:

root@raspberrypi:/var/lib/asterisk/agi-bin# ls -al total 16 drwxr-xr-x 2 root root 4096 oct 17 17:56 . drwxr-xr-x 12 asterisk asterisk 4096 nov 2 17:06 .. -rwxr-xr-x 1 root root 7517 oct 17 17:56 speech-recog.agi root@raspberrypi:/var/lib/asterisk/agi-bin#

exten => 1,1,System(wget "http://lampara.voip2day.voipnovatos.es/encender") exten => 1,n,Playback(luzencendida) exten => 1,n,Hangup() !exten => 2,1,System(wget "http://lampara.voip2day.voipnovatos.es/apagar") exten => 2,n,Playback(luzapagada) exten => 2,n,Hangup() !exten => 3,1,System(wget "http://sirena.voip2day.voipnovatos.es/encender") exten => 3,n,Playback(sirenaencendida) exten => 3,n,Hangup() !exten => 4,1,System(wget "http://wemo.voip2day.voipnovatos.es/enchufe/encender") exten => 4,n,Playback(wemoencendido) exten => 4,n,Hangup() !exten => 5,1,System(wget "http://wemo.voip2day.voipnovatos.es/enchufe/apagar") exten => 5,n,Playback(wemoapagado)

Page 29: V2 d2013   alberto sagredo - domótica

Demo #1 : Home Automation Phone System

Configuración Apache: <VirtualHost [2001:b18:406a::10]:80> ServerAdmin webmaster@localhost ServerName lampara.voip2day.voipnovatos.es DocumentRoot /var/www/lampara ! <Directory /var/www/lampara/> Options Indexes FollowSymLinks MultiViews AllowOverride None Order allow,deny allow from all </Directory> ! ErrorLog ${APACHE_LOG_DIR}/error.log ! # Possible values include: debug, info, notice, warn, error, crit, # alert, emerg. LogLevel warn ! CustomLog ${APACHE_LOG_DIR}/access.log combined </VirtualHost>

Page 30: V2 d2013   alberto sagredo - domótica

Demo #1 : Home Automation Phone System

Script Encendido PHP

<html> <head> <title>Encendido Lampara IDC IPV6</title> </head> <body> <?php echo file_get_contents('https://my.zipato.com/zipato-web/remoting/attribute/set?serial=XXXXXXXXXXXXXX&ep=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx&apiKey=xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxx&state=true'); ?> </body> </html>

Page 31: V2 d2013   alberto sagredo - domótica

Demo #1 : Home Automation Phone System

Configuración Zipato

Page 32: V2 d2013   alberto sagredo - domótica

Demo #1 : Home Automation Phone System

Configuración FIBARO Virtual Switch

Page 33: V2 d2013   alberto sagredo - domótica

Demo #1 : Home Automation Phone System

Page 34: V2 d2013   alberto sagredo - domótica

Demo #2 : Teleasistencia

Elementos Inteligentes:

- Zipato

- Asterisk

- Raspberry Pi

- Instalador

Page 35: V2 d2013   alberto sagredo - domótica

Actuadores:

- Fibaro Key Fob

- Fortrezz Siren

Demo #2 : Teleasistencia

Page 36: V2 d2013   alberto sagredo - domótica

Esquema de Funcionamiento:

my.zipato.com

Demo #2 : Teleasistencia

Page 37: V2 d2013   alberto sagredo - domótica

Configuración Zipato

Demo #2 : Teleasistencia

Page 38: V2 d2013   alberto sagredo - domótica

Configuración FIBARO Keyfob

Demo #2 : Teleasistencia

Los HTTP Request son realizados localmente

Page 39: V2 d2013   alberto sagredo - domótica

Configuración Fortrezz Siren

Demo #2 : Teleasistencia

Los HTTP Request son realizados localmente

Page 40: V2 d2013   alberto sagredo - domótica

Regla

Demo #2 : Teleasistencia

Page 41: V2 d2013   alberto sagredo - domótica

PHP .call file :

Demo #2 : Teleasistencia<html> <head> <title>Llamada Asterisk IPV4</title> </head> <body> <?php $numbertocall = "CALLCENTER"; $context="extensiones"; $extension="105"; $vars = ""; $touchtime = ""; $time = time(); $callfile = "call_" . $time . ".call"; $startcallfile ="/tmp/" . $callfile; $endcallfile = "/var/spool/asterisk/outgoing/" . $callfile; !$cfile = fopen($startcallfile,"ab"); fwrite($cfile,"Channel: SIP/Vozcom/" . $numbertocall . "\n"); fwrite($cfile,"MaxRetries: 1\n"); fwrite($cfile,"RetryTime: 60\n"); fwrite($cfile,"WaitTime: 30\n"); fwrite($cfile,"Context: " . $context . "\n"); fwrite($cfile,"Extension: " . $extension . "\n"); if ($vars != "") { fwrite($cfile,"Set: " . $vars . "\n"); } fclose($cfile); !chmod($startcallfile,0777); if ($touchtime != "") { list($hour,$minute,$second,$month,$day,$year) = split('-',$touchtime); $ctime = mktime($hour,$minute,$second,$month,$day,$year); touch($startcallfile,$ctime,$ctime); } rename($startcallfile,$endcallfile); !! ?> </body> </html>

Page 42: V2 d2013   alberto sagredo - domótica

Configuración Apache:

Demo #2 : Teleasistencia

<VirtualHost *:8082> ServerAdmin webmaster@localhost ServerName asterisk.voip2day.voipnovatos.es DocumentRoot /var/www/asterisk <Directory /var/www/asterisk/llamar> Options Indexes FollowSymLinks MultiViews AllowOverride None Order allow,deny allow from all </Directory> <Directory /var/www/asterisk/alarma> Options Indexes FollowSymLinks MultiViews AllowOverride None Order allow,deny allow from all </Directory> ! ErrorLog ${APACHE_LOG_DIR}/error.log ! # Possible values include: debug, info, notice, warn, error, crit, # alert, emerg. LogLevel warn ! CustomLog ${APACHE_LOG_DIR}/access.log combined </VirtualHost>

Page 43: V2 d2013   alberto sagredo - domótica

PHP Encendido / Apagado

Demo #2 : Teleasistencia

<html> <head> <title>Encendido Lampara IDC IPV6</title> </head> <body> <?php echo file_get_contents(‘https://my.zipato.com/zipato-web/remoting/attribute/set?……………………..’); !! ?> </body> </html>

Page 44: V2 d2013   alberto sagredo - domótica

Dialplan Asterisk

Demo #2 : Teleasistencia

exten => 105,1,SIPAddHeader(Call-Info:;Answer-After=0) exten => 105,n,Dial(SIP/${EXTEN}) exten => 105,n,Hangup

Page 45: V2 d2013   alberto sagredo - domótica

Demo #3 : Energy Call Generator

Elementos Inteligentes:

- Zipato

- Asterisk

- Raspberry Pi

- Instalador

Page 46: V2 d2013   alberto sagredo - domótica

Sensores:

- Fibaro Wall Plug

- Fortrezz Siren Alarm

!

Demo #3 : Energy Call Generator

Page 47: V2 d2013   alberto sagredo - domótica

Esquema de Funcionamiento:

Demo #3 : Energy Call Generator

my.zipato.com

Page 48: V2 d2013   alberto sagredo - domótica

Configuración Zipato

Demo #3 : Energy Call Generator

Page 49: V2 d2013   alberto sagredo - domótica

Regla Zipato. Forma fácil

Demo #3 : Energy Call Generator

Page 50: V2 d2013   alberto sagredo - domótica

O bien haremos consultas mediante JSON

Demo #3 : Energy Call Generator

<?php #include ("config.php"); $url = 'http://my.zipato.com:8080/zipato-web/json/Initialize'; $username = 'username; $password = 'password'; $json = json_decode(file_get_contents($url)); $sid = 'jsessionid'; $none = 'nonce'; $id = $json->{$sid}; $nonce = $json->{$none}; $temp = sha1 ($password); $temp2 = $nonce.$temp; $pass = sha1($temp2); $data = array("username" => "$username", "password" => "$pass", "method" => "SHA1" ); $data_url = "username=$username&password=$pass&method=SHA1"; $ch = curl_init('http://my.zipato.com:8080/zipato-web/json/Login'); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_COOKIE, 'JSESSIONID='.$id); curl_setopt($ch, CURLOPT_POSTFIELDS, $data_url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $output = curl_exec($ch); $c = curl_init(); curl_setopt($c, CURLOPT_URL, "http://my.zipato.com:8080/zipato-web/rest/meters/values/"); curl_setopt($c, CURLOPT_RETURNTRANSFER, true); curl_setopt($c, CURLOPT_COOKIE, 'JSESSIONID='.$id.'; Path=/zipato-web/; HttpOnly'); curl_setopt($c, CURLOPT_HEADER, false); $output = curl_exec($c);

Page 51: V2 d2013   alberto sagredo - domótica

O bien haremos consultas mediante JSON

Demo #3 : Energy Call Generator

$c = curl_init(); curl_setopt($c, CURLOPT_URL, "http://my.zipato.com:8080/zipato-web/rest/meters/"); curl_setopt($c, CURLOPT_RETURNTRANSFER, true); curl_setopt($c, CURLOPT_COOKIE, 'JSESSIONID='.$id.'; Path=/zipato-web/; HttpOnly'); curl_setopt($c, CURLOPT_HEADER, false); $output = curl_exec($c); $json = json_decode ($output,true); $timestamp = time(); $date = $today = date("Y-m-d H:i:s"); !foreach ($json as $meter) { //var_dump($meter); $name = $meter['name']; foreach ($meter['attributes'] as $attribute) { if ($attribute['definition']['name'] == "CURRENT_CONSUMPTION") { $consumo = round($attribute['value'],2); } } !//echo ($consumo); !system("asterisk -rx 'database put consumo lampara $consumo'"); !}

Page 52: V2 d2013   alberto sagredo - domótica

Dialplan Asterisk [extensiones] !!exten => _9X.,1,Dial(SIP/vozcom/${EXTEN}) exten => _9X.,n,Hangup !exten => _6X.,1,Dial(SIP/vozcom/${EXTEN}) exten => _6X.,n,Hangup !exten => locucion,1,Answer() exten => locucion,n,Wait(2) exten => locucion,n,Playback(Alarma en ventana) exten => locucion,n,Hangup !exten => checkconsumo,1,GotoIf($[${DB(consumo/lampara)} > 0]?ok:nook) exten => checkconsumo,n(ok),Dial(SIP/vozcom/666777111,20,tTrR) exten => checkconsumo,n(nook),Hangup

Demo #3 : Energy Call Generator

Page 53: V2 d2013   alberto sagredo - domótica

Crontab

Demo #3 : Energy Call Generator

*/1 * * * * php /var/www/sensor/vera/datos/captura.php */1 * * * * php /var/www/sensor/zipato/datos/captura.php */1 * * * * /usr/sbin/asterisk -rx "console dial checkconsumo@extensiones"

Page 54: V2 d2013   alberto sagredo - domótica

Elementos Inteligentes:

- Wemo Switch

- Asterisk

- Raspberry Pi

- Instalador

Demo #4 : Wemo Phone System

Page 55: V2 d2013   alberto sagredo - domótica

Demo #4 : Wemo Phone System

Esquema de Funcionamiento:

Page 56: V2 d2013   alberto sagredo - domótica

El encendido y Apagado lo haremos mediante PHP y un script en bash

Demo #4 : Wemo Phone System

<html> <head> <title>Encendido Lampara IDC IPV6</title> </head> <body> <?php System ("/var/www/wemo/enchufe/encender/wemo.sh 10.0.1.105 ON") ?> </body> </html>

Es importante saber la dirección IP del WEMO y el puerto que levanta. Lo localizaremos mirando el DHCP Server y el puerto con nmap

Page 57: V2 d2013   alberto sagredo - domótica

Demo #4 : Wemo Phone System#!/bin/sh

# # WeMo Control Script # # [email protected] # # Usage: ./wemo_control IP_ADDRESS ON/OFF/GETSTATE/GETSIGNALSTRENGTH/GETFRIENDLYNAME # # !IP=$1 COMMAND=$2 !#PORTTEST=$(curl -s $IP:49152 | grep "404") !#if [ "$PORTTEST" = "" ] # then PORT=49153 #else # PORT=49152 #fi !if [ "$1" = "" ] then echo "Usage: ./wemo_control IP_ADDRESS ON/OFF/GETSTATE/GETSIGNALSTRENGTH/GETFRIENDLYNAME" else ! if [ "$2" = "GETSTATE" ] ! then ! curl -0 -A '' -X POST -H 'Accept: ' -H 'Content-type: text/xml; charset="utf-8"' -H "SOAPACTION: \"urn:Belkin:service:basicevent: 1#GetBinaryState\"" --data '<?xml version="1.0" encoding="utf-8"?><s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"><s:Body><u:GetBinaryState xmlns:u="urn:Belkin:service:basicevent:1"><BinaryState>1</BinaryState></u:GetBinaryState></s:Body></s:Envelope>' -s http://$IP:$PORT/upnp/control/basicevent1 | grep "<BinaryState" | cut -d">" -f2 | cut -d "<" -f1 | sed 's/0/OFF/g' | sed 's/1/ON/g' ! elif [ "$2" = "ON" ] ! then

Page 58: V2 d2013   alberto sagredo - domótica

Demo #4 : Wemo Phone System

! curl -0 -A '' -X POST -H 'Accept: ' -H 'Content-type: text/xml; charset="utf-8"' -H "SOAPACTION: \"urn:Belkin:service:basicevent: 1#SetBinaryState\"" --data '<?xml version="1.0" encoding="utf-8"?><s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"><s:Body><u:SetBinaryState xmlns:u="urn:Belkin:service:basicevent:1"><BinaryState>1</BinaryState></u:SetBinaryState></s:Body></s:Envelope>' -s http://$IP:$PORT/upnp/control/basicevent1 | grep "<BinaryState" | cut -d">" -f2 | cut -d "<" -f1 ! elif [ "$2" = "OFF" ] ! then ! curl -0 -A '' -X POST -H 'Accept: ' -H 'Content-type: text/xml; charset="utf-8"' -H "SOAPACTION: \"urn:Belkin:service:basicevent: 1#SetBinaryState\"" --data '<?xml version="1.0" encoding="utf-8"?><s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"><s:Body><u:SetBinaryState xmlns:u="urn:Belkin:service:basicevent:1"><BinaryState>0</BinaryState></u:SetBinaryState></s:Body></s:Envelope>' -s http://$IP:$PORT/upnp/control/basicevent1 | grep "<BinaryState" | cut -d">" -f2 | cut -d "<" -f1 ! elif [ "$2" = "GETSIGNALSTRENGTH" ] ! then ! curl -0 -A '' -X POST -H 'Accept: ' -H 'Content-type: text/xml; charset="utf-8"' -H "SOAPACTION: \"urn:Belkin:service:basicevent:1#GetSignalStrength\"" --data '<?xml version="1.0" encoding="utf-8"?><s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"><s:Body><u:GetSignalStrength xmlns:u="urn:Belkin:service:basicevent:1"><GetSignalStrength>0</GetSignalStrength></u:GetSignalStrength></s:Body></s:Envelope>' -s http://$IP:$PORT/upnp/control/basicevent1 | grep "<SignalStrength" | cut -d">" -f2 | cut -d "<" -f1 ! elif [ "$2" = "GETFRIENDLYNAME" ] ! then ! curl -0 -A '' -X POST -H 'Accept: ' -H 'Content-type: text/xml; charset="utf-8"' -H "SOAPACTION: \"urn:Belkin:service:basicevent: 1#ChangeFriendlyName\"" --data '<?xml version="1.0" encoding="utf-8"?><s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"><s:Body><u:ChangeFriendlyName xmlns:u="urn:Belkin:service:basicevent:1"><FriendlyName>Pool Filter</FriendlyName></u:ChangeFriendlyName></s:Body></s:Envelope>' -s http://$IP:$PORT/upnp/control/basicevent1 | grep "<FriendlyName" | cut -d">" -f2 | cut -d "<" -f1 ! else

Page 59: V2 d2013   alberto sagredo - domótica

Demo #4 : Wemo Phone System

else ! echo "COMMAND NOT RECOGNIZED" echo "" echo "Usage: ./wemo_control IP_ADDRESS ON/OFF/GETSTATE/GETSIGNALSTRENGTH/GETFRIENDLYNAME" echo "" ! fi !fi

Page 60: V2 d2013   alberto sagredo - domótica

Dialplan Asterisk: [ivr] !exten => s,1,Answer() exten => s,n,Background(demovoipnovatos) exten => s,n,Wait(5) exten => s,n,agi(speech-recog.agi,es) exten => s,n,Set(PrimeraWord=${CUT(${utterance},\x20,1)}) exten => s,n,Set(SegundaWord=${CUT(${utterance},\xNN,2)}) exten => s,n,GotoIf($["${utterance}" = "encender luz"]?encenderluz) exten => s,n,GotoIf($["${utterance}" = "apagar luz"]?apagarluz) exten => s,n,GotoIf($["${utterance}" = "encender sirena"]?encendersirena) exten => s,n,GotoIf($["${utterance}" = "encender wemo"]?encenderwemo) exten => s,n,GotoIf($["${utterance}" = “apagar wemo"]?apagarwemo) exten => s,n,Verbose(1,El texto reconocido es: ${utterance}) exten => s,n,Verbose(1,Con una probabilidad de acierto: ${confidence}) exten => s,n,Verbose(1,La primera palabra es ${PrimeraWord} y la segunda palabra es ${SegundaWord} ) exten => s,n,Hangup ;exten => 800,n(encenderluz),Set(foo=${CURL(http://lampara.voip2day.voipnovatos.es/encender)}) exten => s,n(encenderluz),System(wget "http://lampara.voip2day.voipnovatos.es/encender") exten => s,n,Playback(luzencendida) exten => s,n,Hangup() ;exten => 800,n(apagarluz),Set(foo=${CURL(http://lampara.voip2day.voipnovatos.es/apagar)}) exten => s,n(apagarluz),System(wget "http://lampara.voip2day.voipnovatos.es/apagar") exten => s,n,Playback(luzapagada) exten => s,n,Hangup() exten => s,n(encendersirena),System(wget "http://sirena.voip2day.voipnovatos.es/encender") exten => s,n,Playback(sirenaencendida) exten => s,n,Hangup() exten => s,n(encenderwemo),System(wget "http://wemo.voip2day.voipnovatos.es/enchufe/encender") exten => s,n,Playback(wemoencendido) exten => s,n,Hangup() exten => s,n(apagarwemo),System(wget "http://wemo.voip2day.voipnovatos.es/enchufe/apagado") exten => s,n,Playback(wemoapagado) exten => s,n,Hangup()

Demo #4 : Wemo Phone System

Page 61: V2 d2013   alberto sagredo - domótica

Dialplan Asterisk:

root@raspberrypi:/var/lib/asterisk/agi-bin# ls -al total 16 drwxr-xr-x 2 root root 4096 oct 17 17:56 . drwxr-xr-x 12 asterisk asterisk 4096 nov 2 17:06 .. -rwxr-xr-x 1 root root 7517 oct 17 17:56 speech-recog.agi root@raspberrypi:/var/lib/asterisk/agi-bin#

exten => 1,1,System(wget "http://lampara.voip2day.voipnovatos.es/encender") exten => 1,n,Playback(luzencendida) exten => 1,n,Hangup() !exten => 2,1,System(wget "http://lampara.voip2day.voipnovatos.es/apagar") exten => 2,n,Playback(luzapagada) exten => 2,n,Hangup() !exten => 3,1,System(wget "http://sirena.voip2day.voipnovatos.es/encender") exten => 3,n,Playback(sirenaencendida) exten => 3,n,Hangup() !exten => 4,1,System(wget "http://wemo.voip2day.voipnovatos.es/enchufe/encender") exten => 4,n,Playback(wemoencendido) exten => 4,n,Hangup() !exten => 5,1,System(wget "http://wemo.voip2day.voipnovatos.es/enchufe/encender") exten => 5,n,Playback(wemoapagado)

Demo #4 : Wemo Phone System

Page 62: V2 d2013   alberto sagredo - domótica

Demo #5 : Phone Call Alarm

Elementos Inteligentes:

- Vera Lite

- Asterisk

- Raspberry Pi

- Instalador

Page 63: V2 d2013   alberto sagredo - domótica

Actuadores:

- Fibaro Door Sensor

- Everspring Motion Sensor

Demo #5 : Phone Call Alarm

Page 64: V2 d2013   alberto sagredo - domótica

Esquema de Funcionamiento:

Demo #5 : Phone Call Alarm

Page 65: V2 d2013   alberto sagredo - domótica

Configuración Vera Lite

Demo #5 : Phone Call Alarm

Page 66: V2 d2013   alberto sagredo - domótica

Localizar ServID y ID de dispositivo a consultar

Demo #5 : Phone Call Alarm

http://x.x.x.x:3480/data_request?id=user_data2&output_format=xml

http://x.x.x.x:3480/data_request?id=user_data2&output_format=json

https://sta1.mios.com/locator_json.php?username=xxx

{“units”:[{“serialNumber":"xxxxxxx","FirmwareVersion":"1.5.622","name":"MTX","ipAddress":"x.x.x.x","users":

["username"],"active_server":"fwd7.mios.com","forwardServers":[{"hostName":"fwd7.mios.com","primary":true},{"hostName":"fwd5.mios.com","primary":false}]}]}

Page 67: V2 d2013   alberto sagredo - domótica

Acceso Remotamente

Demo #5 : Phone Call Alarm

https://fwdx.mios.com/username/password/IDUNIT/data_request?id=lu_status&output_format=json

Page 68: V2 d2013   alberto sagredo - domótica

PHP Polling Script

Demo #5 : Phone Call Alarm

<?php !$url = 'http://10.x.x.x:3480/data_request?id=variableget&DeviceNum=148&service !$abierta = file_get_contents('http://10.x.x.x:3480/data_request?id=variableget !if ($abierta == "0") { echo ("\n\nNo esta Abierta la Ventana. No hacemos nada\n\n"); } !else{ !echo ("\n\nEsta abierta la ventana. LLamamos al movil\n\n"); echo file_get_contents('http://10.x.x.x/asterisk/llamar'); !} !?>

$url = 'http://10.x.x.x:3480/data_request?id=variableget&DeviceNum=148&serviceId=urn:micasaverde-com:serviceId:SecuritySensor1&Variable=Tripped';

Page 69: V2 d2013   alberto sagredo - domótica

PHP LastTime Tripped Script

Demo #5 : Phone Call Alarm

<?php !$url = 'http://10.x.x.x:3480/data_request?id=variableget&DeviceNum=148&service $unixtime = time(); !$abierta = file_get_contents('http://10.x.x.x:3480/data_request?id=variableget !$diftiempo=$unixtime - $abierta; !echo ($diftiempo); !if ($diftiempo > 60 ) { echo ("\n\nNo esta Abierta la Ventana. No hacemos nada\n\n"); } !else{ !echo ("\n\nEsta abierta la ventana. LLamamos al movil\n\n"); echo file_get_contents('http://10.x.x.x/asterisk/llamar'); !}

Page 70: V2 d2013   alberto sagredo - domótica

Configuración Apache: <VirtualHost [2001:b18:406a::11]:80> ServerAdmin webmaster@localhost ServerName sensor.voip2day.voipnovatos.es ! DocumentRoot /var/www/sensor <Directory /var/www/sensor/datos> Options FollowSymLinks AllowOverride None </Directory> <Directory /var/www/sensor> Options Indexes FollowSymLinks MultiViews AllowOverride None Order allow,deny allow from all </Directory> ! ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/ <Directory "/usr/lib/cgi-bin"> AllowOverride None Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch Order allow,deny Allow from all </Directory> ! ErrorLog ${APACHE_LOG_DIR}/error.log ! # Possible values include: debug, info, notice, warn, error, crit, # alert, emerg. LogLevel warn ! CustomLog ${APACHE_LOG_DIR}/access.log combined </VirtualHost> !

Demo #5 : Phone Call Alarm

Page 71: V2 d2013   alberto sagredo - domótica

PHP .call file :

<html> <head> <title>Llamada Asterisk IPV4</title> </head> <body> <?php $numbertocall = "MOVIL"; $context="extensiones"; $extension="locucion"; $vars = ""; $touchtime = ""; $time = time(); $callfile = "call_" . $time . ".call"; $startcallfile ="/tmp/" . $callfile; $endcallfile = "/var/spool/asterisk/outgoing/" . $callfile; !$cfile = fopen($startcallfile,"ab"); fwrite($cfile,"Channel: SIP/Vozcom/" . $numbertocall . "\n"); fwrite($cfile,"MaxRetries: 1\n"); fwrite($cfile,"RetryTime: 60\n"); fwrite($cfile,"WaitTime: 30\n"); fwrite($cfile,"Context: " . $context . "\n"); fwrite($cfile,"Extension: " . $extension . "\n"); if ($vars != "") { fwrite($cfile,"Set: " . $vars . "\n"); } fclose($cfile); !chmod($startcallfile,0777); if ($touchtime != "") { list($hour,$minute,$second,$month,$day,$year) = split('-',$touchtime); $ctime = mktime($hour,$minute,$second,$month,$day,$year); touch($startcallfile,$ctime,$ctime); } rename($startcallfile,$endcallfile); !! ?> </body> </html>

Demo #5 : Phone Call Alarm

Page 72: V2 d2013   alberto sagredo - domótica

Dialplan Asterisk

[extensiones] !!exten => _9X.,1,Dial(SIP/vozcom/${EXTEN}) exten => _9X.,n,Hangup !exten => _6X.,1,Dial(SIP/vozcom/${EXTEN}) exten => _6X.,n,Hangup !exten => locucion,1,Answer() exten => locucion,n,Wait(2) exten => locucion,n,Playback(Alarma en ventana) extne => locucion,n,Hangup !

Demo #5 : Phone Call Alarm

Page 73: V2 d2013   alberto sagredo - domótica

Seguridad• Si nuestra casa se puede abrir, se puede controlar como consume

energía, hay que tener cuidado y no dejarlo abierto a cualquiera (Sentido Común)

• Si usamos sistemas cloud, creemos en el cloud… con todo lo que ello conlleva.

• Si usamos Apache para HTTP request, poner contraseñas o certificados (Lo mostrado aquí es una forma didacta exenta de seguridad)

• Zwave implícitamente lleva seguridad. Sobre todo dispositivos de apertura de puertas.

• http://research.sensepost.com/cms/resources/conferences/2013/bh_zwave/Security%20Evaluation%20of%20Z-Wave_WP.pdf

www.voipnovatos.es

Alberto Sagredo Castro

Page 74: V2 d2013   alberto sagredo - domótica

Futuro• Esta por ver que protocolo se llevará el gato al agua.

• Seguramente coexistencia de muchos de ellos, y el integrador jugará a integrar y pelearse para hacerlos funcionar.

• 6LowPAN interesante ver como evoluciona el mercado.

• 6LowPAN y Zigbee soporte IPV6 (armados para el futuro).

• ¿Wemo abrirá su API?

• ¿Phillips Hue más dispositivos?

www.voipnovatos.es

Alberto Sagredo Castro

Page 75: V2 d2013   alberto sagredo - domótica

¿Preguntas?

www.voipnovatos.es

Alberto Sagredo Castro

Page 76: V2 d2013   alberto sagredo - domótica

Gracias• A Voip2day por invitarme un año más.

• A mis hijos y esposa por hacerme féliz y darme razones para luchar por ellos.

• A mi mujer por aguantar los cables y las ondas que instalo en casa.

• A vosotros por la presencia y atención.

• A los visitantes de voipnovatos.es por su fidelidad.

• A voz.com por su apoyo incondicional.

• A zwave.es por el asesoramiento en domótica.

www.voipnovatos.es

Alberto Sagredo Castro

Page 77: V2 d2013   alberto sagredo - domótica

@ albersag

www.voipnovatos.es

Alberto Sagredo Castro