Total Length (mm)May
T HE D EVELOPMENT OF T ECHNOLOGIES FOR T RIPLOID P RODUCTION AND V ERIFICATION
Una vez inicializado el Sensor Data Collect, la figura 3.15 muestra el gráfico de red que proporciona esta herramienta. Se debe tener en cuenta que esto muestra en tiempo real la conexión de los nodos de acuerdo al funcionamiento de RPL. Si algún nodo fuera desconectado de la red, entonces se apreciaría la reestructuración del DODAG construido por RPL.
Figura 3.15: Gráfico de red.
Se puede apreciar que el nodo 8 es uno de los más alejados del nodo sumidero y por lo tanto no está en cobertura mutua con este, por lo que existe una mayor probabilidad de que la mayor cantidad de paquetes que se pierdan sean los provenientes de este nodo.
La figura 3.16a muestra la cantidad de paquetes recibidos y perdidos para un instante determinado de tiempo, analizándose los 8 nodos que conforman la red. Por su parte la figura 3.16b muestra lo mismo pero analizándose el nodo 8 específicamente.
(a) (b) Figura 3.16: Cantidad de paquetes recibidos y perdidos.
Como se puede apreciar estos resultados corroboran lo anteriormente planteado, pues de los 957 paquetes recibidos de los ocho nodos, se perdieron 133 y de ese total de paquetes perdidos, 111 se perdieron provenientes desde el nodo 8.
Figura 3.17: Temperatura detectada por los nodos. Del mismo modo, la figura 3.18 muestra la cantidad de vecinos.
Figura 3.18: Cantidad de vecinos.
La métrica de ruteo es mostrada en la figura 3.19. Se puede apreciar que el nodo 8 mejora su métrica de ruteo una vez que el nodo 6 se incorpora a la red, pues el nodo 8 establece una conexión con este. El nodo 8 deja de enviar paquetes de datos al nodo 5 que está congestionado y ahora los pasa por el nodo 6 que está libre.
Figura 3.19: Métrica de ruteo.
3.5 Consideraciones finales
En este capítulo se ha realizado la implementación de tres ejemplos de WSN basados en ContikiOS utilizando COOJA y dispositivos reales. Se puede constatar las potencialidades de ContikiOS para comunicar a los nodos de WSN, y las de COOJA para simular WSN basadas en ContikiOS. Las ventajas que presenta COOJA son apreciables, pues el código que se prueba en este se puede desplegar en dispositivos reales. Además se destaca las posibilidades que ofrece la herramienta Sensor Data Collect, la que permite la monitorización dinámica en tiempo de ejecución de cualquier topología de WSN. Gracias a esta herramienta se puede analizar el desempeño de los nodos de la red.
75
CONCLUSIONES Y RECOMENDACIONES
Conclusiones
De la realización de la presente investigación se extraen las siguientes conclusiones finales: 1. Las WSN tienen características específicas en cuanto a disponibilidad de energía y
recursos computacionales y de radio, patrones de tráfico, e inestabilidad de los enlaces, que las diferencian notablemente de otras redes inalámbricas. Estas características tienen un impacto significativo en la capa MAC por ser la responsable de controlar la interfaz de radio que es el componente que consume la mayor parte de la energía de los nodos.
2. Los sistemas operativos permiten una gestión más apropiada del hardware de los nodos de WSN y, a la vez, facilitan el trabajo a los desarrolladores de aplicaciones de más alto nivel. La selección de ContikiOS está basada en sus características específicas, como el uso del protocolo IPv6 sobre IEEE 802.15.4, y la implementación del mecanismo Protothread. Por su parte, los simuladores constituyen una potente herramienta para probar el software diseñado para los nodos WSN. La selección de COOJA está basada en su flexibilidad, en su capacidad para simular a varios niveles de abstracción y por ser el simulador que proporciona ContikiOS. También es capaz de simular nodos que implementen otro sistema operativo.
3. Los ejemplos implementados de WSN demuestran las potencialidades de ContikiOS para implementar redes de este tipo, destacando especialmente el uso de RPL, pues generalmente el nodo sumidero no se encuentra localizado en la cobertura del nodo que realiza la medición. Por otra parte se pone de manifiesto las capacidades de
COOJA para simular y construir redes de WSN utilizando ContikiOS, pues permite la simulación antes del despliegue real en dispositivos, utilizando en dispositivos reales el mismo código empleado en la simulación. Además se evidencia que la herramienta Sensor Data Collect permite la monitorización dinámica en tiempo de ejecución de cualquier topología de WSN para analizar el desempeño de los nodos.
Recomendaciones
Con el objetivo de profundizar en el tema de las WSN y, específicamente, en el estudio de ContikiOS y de COOJA, los autores proponen las siguientes recomendaciones para investigaciones futuras:
1. Desplegar los resultados de la presente investigación en los cursos de postgrado y pregrado que se imparten en carreras afines a las telecomunicaciones.
2. Extender el empleo de ContikiOS y COOJA para la investigación en el área de las WSN dentro de nuestro país por ser una tecnología emergente con amplias posibilidades de investigación y desarrollo.
77
REFERENCIAS BIBLIOGRÁFICAS
[1] P. Magrassi, A. Panarella, N. Deighton, and G. Johnson, "Computers to acquire control of the physical world," Gartner, September, 2001.
[2] R. H. Weber, "Internet of Things–New security and privacy challenges," Computer Law & Security Review, vol. 26, pp. 23-30, 2010.
[3] R. Van Kranenburg, E. Anzelmo, A. Bassi, D. Caprio, S. Dodson, and M. Ratto, "The Internet of things," A critique of ambient technology and the all-seeing network of RFID, Network Notebooks, vol. 2, 2011.
[4] M. Avvenuti, P. Corsini, P. Masci, and A. Vecchio, "Increasing the efficiency of preamble sampling protocols for wireless sensor networks," in Mobile Computing and Wireless Communication International Conference, 2006. MCWC 2006. Proceedings of the First, 2006, pp. 117-122.
[5] W. Dargie and C. Poellabauer, Fundamentals of wireless sensor networks: theory and practice: John Wiley & Sons, 2010.
[6] J. M. Gilbert and F. Balouchi, "Comparison of energy harvesting systems for wireless sensor networks," International Journal of Automation and Computing, vol. 5, pp. 334-347, 2008.
[7] P. Huang, L. Xiao, S. Soltani, M. W. Mutka, and N. Xi, "The Evolution of MAC Protocols in Wireless Sensor Networks: A Survey," Communications Surveys & Tutorials, vol. 15, pp. 101-120, 2013.
[8] J. M. Gilbert and F. Balouchi, "Comparison of energy harvesting systems for wireless sensor networks," international journal of automation and computing, vol. 5, pp. 334- 347, 2008.
[9] E. J. García Davis, "Implementación de Protocolos de Transporte en Redes de Sensores," 2009.
[10] K. Langendoen, "Medium access control in wireless sensor networks," Medium access control in wireless networks, vol. 2, pp. 535-560, 2008.
[11] K. Langendoen, "Medium Access Control in Wireless Sensor Networks," in Medium Access Control in Wireless Networks, Volume II: Practice and Standards. vol. 2, H. Wu and Y. Pan, Eds., ed: Nova Science Publishers, 2008, pp. 535-560.
[12] A. Bachir, D. Barthel, M. Heusse, and A. Duda, "Micro-frame preamble mac for multihop wireless sensor networks," in Communications, 2006. ICC'06. IEEE International Conference on, 2006, pp. 3365-3370.
[13] E. E. Flores Carbajal, "Redes de Sensores Inalámbricas Aplicado a la Medicina," 2012.
[14] F. M. L. Fernández, "Soporte del tipo de mota AvrZigbit en el simulador Cooja," Proyecto Fin de Carrera, Dpto. de Ingeniería Telemática, Universidad de Sevilla, 2013.
[15] "Imote2 datasheet. high-performance wireless sensor network node," C. T. Inc., Ed., ed, 2014.
[16] C. M. G. Algora, "Análisis de desempeño del protocolo MAC del estándar IEEE 802.15.4," Departamento de Telecomunicaciones y Electr´onica, Universidad Central “Marta Abreu” de Las Villas, 2014.
[17] R. F. Martínez and J. O. Meré, "Francisco Javier Martínez de Pisón Ascacíbar, Ana González Marcos, Fernando Alba Elías, Rubén Lostado Lorza, Alpha Verónica Pernía Espinoza.“," Redes inalámbricas de sensores: teoría y práctica”. Universidad de la Rioja, 2009.
[18] P. Levis, S. Madden, J. Polastre, R. Szewczyk, K. Whitehouse, A. Woo, et al., "TinyOS: An operating system for sensor networks," in Ambient intelligence, ed: Springer, 2005, pp. 115-148.
[19] S. Bhatti, J. Carlson, H. Dai, J. Deng, J. Rose, A. Sheth, et al., "MANTIS OS: An embedded multithreaded operating system for wireless micro sensor platforms,"
Mobile Networks and Applications, vol. 10, pp. 563-579, 2005.
[20] A. Dunkels, B. Gronvall, and T. Voigt, "Contiki-a lightweight and flexible operating system for tiny networked sensors," in Local Computer Networks, 2004. 29th Annual IEEE International Conference on, 2004, pp. 455-462.
[21] T. Reusing, "Comparison of operating systems tinyos and contiki," Sens. Nodes- Operation, Netw. Appli.(SN), vol. 7, 2012.
[22] V. Reddy, P. Kumar, D. Janakiram, and G. A. Kumar, "Operating systems for wireless sensor networks: A survey," Int. J. Sens. Netw, vol. 5, pp. 236-255, 2009. [23] X. Chang, "Network simulations with OPNET," in Proceedings of the 31st
conference on Winter simulation: Simulation---a bridge to the future-Volume 1, 1999, pp. 307-314.
[24] F. Osterlind, A. Dunkels, J. Eriksson, N. Finne, and T. Voigt, "Cross-level sensor network simulation with cooja," in Local Computer Networks, Proceedings 2006 31st IEEE Conference on, 2006, pp. 641-648.
[25] P. Levis, N. Lee, M. Welsh, and D. Culler, "TOSSIM: Accurate and scalable simulation of entire TinyOS applications," in Proceedings of the 1st international conference on Embedded networked sensor systems, 2003, pp. 126-137.
[26] A. Varga, "The OMNeT++ discrete event simulation system," in Proceedings of the European simulation multiconference (ESM’2001), 2001, p. 65.
[27] (2010). NS, Network Simulator.
[28] C. P. Singh, O. Vyas, and M. K. Tiwari, "A survey of simulation in sensor networks," in Computational Intelligence for Modelling Control & Automation, 2008 International Conference on, 2008, pp. 867-872.
[29] B. Musznicki and P. Zwierzykowski, "Survey of simulators for wireless sensor networks," International Journal of Grid and Distributed Computing, vol. 5, pp. 23- 50, 2012.
[30] D. K. o. Patrik Moravek, Milan Simek, "Specifics of WSN simulations," vol. 2, SEPTEMBER 2011.
[31] M. A. C. Pérez, J. C. C. Quiñones, J. C. Madelayne Morales Rodríguez Cuéllar Quiñones, and J. D. T. Vanegas, Simulando con OMNET selección de la herramienta y su utilización: Universidad ICESI, 2013.
[32] A. Boulis and D. Pediaditakis, "Castalia A Simulator for WSNs," ed: National ICT Australia.[Online], 2008.
[33] A. Asensio González, A. Miguel Núñez, and J. Pascual García, "Diseño de un simulador para redes de sensores," 2009.
[34] E. Weingartner, H. Vom Lehn, and K. Wehrle, "A performance comparison of recent network simulators," in Communications, 2009. ICC'09. IEEE International Conference on, 2009, pp. 1-5.
[35] A. Dunkels, O. Schmidt, T. Voigt, and M. Ali, "Protothreads: simplifying event- driven programming of memory-constrained embedded systems," in Proceedings of the 4th international conference on Embedded networked sensor systems, 2006, pp. 29-42.
[36] N. Tsiftes and A. Dunkels, "A database in every sensor," in Proceedings of the 9th ACM Conference on Embedded Networked Sensor Systems, 2011, pp. 316-332. [37] M. Kovatsch, S. Duquennoy, and A. Dunkels, "A low-power CoAP for Contiki," in
Mobile Adhoc and Sensor Systems (MASS), 2011 IEEE 8th International Conference on, 2011, pp. 855-860.
[38] A. Dunkels, "The contikimac radio duty cycling protocol," 2011.
[39] M. Bezunartea, "Experimental evaluation of communication protocols for wireless sensor networks," 2014.
[40] M. Buettner, G. V. Yee, E. Anderson, and R. Han, "X-MAC: a short preamble MAC protocol for duty-cycled wireless sensor networks," in Proceedings of the 4th international conference on Embedded networked sensor systems, 2006, pp. 307-320. [41] A. Dunkels, "Towards tcp/ip for wireless sensor networks," Mälardalen University,
2005.
[42] A. Dunkels, "Rime—a lightweight layered communication stack for sensor networks," in Proceedings of the European Conference on Wireless Sensor Networks (EWSN), Poster/Demo session, Delft, The Netherlands, 2007.
[43] J. Schiller, H. Ritter, A. Liers, and T. Voigt, "Scatterweb-low power nodes and energy aware routing," in Hawaii International Conference on System Sciences, 2005. [44] J. E. Brittain, "Electrical Engineering Hall of Fame: Harald T. Friis [Scanning Our
Past]," Proceedings of the IEEE, vol. 97, pp. 1651-1654, 2009. [45] Zolertia, "Z1 Low-Power WSN Platform," 2014.
82
ANEXO A Ejemplo 7Clientes-Servidor
Anexo A.1. Códigos de programación para el servidor
#include "contiki.h" #include "contiki-lib.h" #include "contiki-net.h" #include "net/ip/uip.h" #include "net/rpl/rpl.h" #include "net/netstack.h" #include "dev/button-sensor.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include "dev/leds.h" #define DEBUG DEBUG_PRINT #include "net/ip/uip-debug.h"
#define UIP_IP_BUF ((struct uip_ip_hdr *)&uip_buf[UIP_LLH_LEN])
#define UDP_CLIENT_PORT 5000
#define UDP_SERVER_PORT 5000
#define UDP_EXAMPLE_ID 190
static struct uip_udp_conn *server_conn;
PROCESS(udp_server_process, "UDP server process"); AUTOSTART_PROCESSES(&udp_server_process); /*--- ---*/ static void tcpip_handler(void) { char *appdata; char buf[30];
if(uip_newdata()) {
appdata = (char *)uip_appdata; char seq[5]; int i=0; while (appdata[i] != '.'){ seq[i]=appdata[i]; i++; } seq[i]=0; //printf("%s\n", seq); unsigned int temp_raw=((int)appdata[1+i]-48)*1000 + ((int)appdata[2+i]-48)*100 + ((int)appdata[3+i]-48)*10 + ((int)appdata[4+i]-48); int16_t tempint; uint16_t tempfrac; uint16_t absraw; int16_t sign; char minus = ' '; sign = 1; //PRINTFDEBUG("Reading Temp...\n"); absraw = temp_raw;
if(temp_raw < 0) { // Perform 2C's if sensor returned
negative data
absraw = (temp_raw ^ 0xFFFF) + 1; sign = -1;
}
tempint = (absraw >> 8) * sign;
tempfrac = ((absraw >> 4) % 16) * 625; // Info in 1/10000 of degree
minus = ((tempint == 0) & (sign == -1)) ? '-' : '+'; appdata[uip_datalen()] = 0;
//PRINTF("DATA: '%s' from ", appdata); PRINTF("%s.Temperature at node %d",seq,
UIP_IP_BUF->srcipaddr.u8[sizeof(UIP_IP_BUF- >srcipaddr.u8) - 1]);
printf(" is %c%d.%04d degrees\n", minus, tempint, tempfrac); leds_toggle(LEDS_GREEN);
//#if SERVER_REPLY
//PRINTF("DATA sending reply\n");
uip_ipaddr_copy(&server_conn->ripaddr, &UIP_IP_BUF- >srcipaddr);
sprintf(buf, "%s", seq);
uip_udp_packet_send(server_conn, buf, strlen(appdata)); uip_create_unspecified(&server_conn->ripaddr);
leds_toggle(LEDS_BLUE); //#endif
} /*--- ---*/ static void print_local_addresses(void) { int i; uint8_t state;
PRINTF("Server IPv6 addresses: "); for(i = 0; i < UIP_DS6_ADDR_NB; i++) { state = uip_ds6_if.addr_list[i].state;
if(state == ADDR_TENTATIVE || state == ADDR_PREFERRED) { PRINT6ADDR(&uip_ds6_if.addr_list[i].ipaddr);
PRINTF("\n");
/* hack to make address "final" */ if (state == ADDR_TENTATIVE) { uip_ds6_if.addr_list[i].state = ADDR_PREFERRED; } } } } /*--- ---*/
PROCESS_THREAD(udp_server_process, ev, data) {
uip_ipaddr_t ipaddr;
struct uip_ds6_addr *root_if; PROCESS_BEGIN();
PROCESS_PAUSE();
SENSORS_ACTIVATE(button_sensor); PRINTF("UDP server started\n"); #if UIP_CONF_ROUTER
/* The choice of server address determines its 6LoPAN header compression.
* Obviously the choice made here must also be selected in udp- client.c.
*
* For correct Wireshark decoding using a sniffer, add the /64 prefix to the 6LowPAN protocol preferences,
* e.g. set Context 0 to aaaa::. At present Wireshark copies Context/128 and then overwrites it.
* (Setting Context 0 to aaaa::1111:2222:3333:4444 will report a 16 bit compressed address of aaaa::1111:22ff:fe33:xxxx)
* Note Wireshark's IPCMV6 checksum verification depends on the correct uncompressed addresses.
//#if 0
/* Mode 1 - 64 bits inline */
uip_ip6addr(&ipaddr, 0xaaaa, 0, 0, 0, 0, 0, 0, 1); //#elif 1
/* Mode 2 - 16 bits inline */
//uip_ip6addr(&ipaddr, 0xaaaa, 0, 0, 0, 0, 0x00ff, 0xfe00, 1); //#else
/* Mode 3 - derived from link local (MAC) address */ /* uip_ip6addr(&ipaddr, 0xaaaa, 0, 0, 0, 0, 0, 0, 0); uip_ds6_set_addr_iid(&ipaddr, &uip_lladdr); #endif*/ uip_ds6_addr_add(&ipaddr, 0, ADDR_MANUAL); root_if = uip_ds6_addr_lookup(&ipaddr); if(root_if != NULL) { rpl_dag_t *dag; dag = rpl_set_root(RPL_DEFAULT_INSTANCE,(uip_ip6addr_t *)&ipaddr); uip_ip6addr(&ipaddr, 0xaaaa, 0, 0, 0, 0, 0, 0, 0); rpl_set_prefix(dag, &ipaddr, 64);
PRINTF("created a new RPL dag\n"); } else {
PRINTF("failed to create a new RPL DAG\n"); }
#endif /* UIP_CONF_ROUTER */
print_local_addresses();
/* The data sink runs with a 100% duty cycle in order to ensure high
packet reception rates. */ NETSTACK_MAC.off(1);
server_conn = udp_new(NULL, UIP_HTONS(UDP_CLIENT_PORT), NULL); if(server_conn == NULL) {
PRINTF("No UDP connection available, exiting the process!\n"); PROCESS_EXIT();
}
udp_bind(server_conn, UIP_HTONS(UDP_SERVER_PORT));
PRINTF("Created a server connection with remote address "); PRINT6ADDR(&server_conn->ripaddr);
PRINTF(" local/remote port %u/%u\n", UIP_HTONS(server_conn- >lport), UIP_HTONS(server_conn->rport)); while(1) { PROCESS_YIELD(); if(ev == tcpip_event) { tcpip_handler();
PRINTF("Initiaing global repair\n"); rpl_repair_root(RPL_DEFAULT_INSTANCE); } } PROCESS_END(); }
Anexo A.2. Códigos de programación para el cliente #include "contiki.h" #include "lib/random.h" #include "sys/ctimer.h" #include "net/ip/uip.h" #include "net/ipv6/uip-ds6.h" #include "net/ip/uip-udp-packet.h" #include "sys/ctimer.h" #ifdef WITH_COMPOWER #include "powertrace.h" #endif #include <stdio.h> #include <string.h> #include "dev/leds.h" #include "sys/node-id.h" //Added to get temperature #include "dev/i2cmaster.h" #include "dev/tmp102.h" #define UDP_CLIENT_PORT 5000 #define UDP_SERVER_PORT 5000 #define UDP_EXAMPLE_ID 190 #define DEBUG DEBUG_PRINT #include "net/ip/uip-debug.h" #ifndef PERIOD
#define PERIOD 5 #endif
#define START_INTERVAL (15 * CLOCK_SECOND)
#define SEND_INTERVAL (PERIOD * CLOCK_SECOND)
#define SEND_TIME (random_rand() % (SEND_INTERVAL))
#define MAX_PAYLOAD_LEN 30
static struct uip_udp_conn *client_conn; static uip_ipaddr_t server_ipaddr;
/*--- ---*/
PROCESS(udp_client_process, "UDP client process"); AUTOSTART_PROCESSES(&udp_client_process); /*--- ---*/ static void tcpip_handler(void) { char *str; if(uip_newdata()) {
str = (char *)uip_appdata; str[uip_datalen()] = '\0'; //str[uip_datalen()] = 0; PRINTF("recv: %s\n", str); leds_toggle(LEDS_GREEN); } } /*--- ---*/
static unsigned int get_temperature() { int16_t raw; /*int16_t tempint; uint16_t tempfrac; uint16_t absraw; int16_t sign; char minus = ' '; sign = 1;*/ tmp102_init(); //PRINTFDEBUG("Reading Temp...\n"); raw = tmp102_read_temp_raw();
/*printf("Raw value: %u ", raw); absraw = raw;
if(raw < 0) { // Perform 2C's if sensor returned
negative data
absraw = (raw ^ 0xFFFF) + 1; sign = -1;
}
tempint = (absraw >> 8) * sign;
tempfrac = ((absraw >> 4) % 16) * 625; // Info in 1/10000 of degree
minus = ((tempint == 0) & (sign == -1)) ? '-' : ' '; PRINTF("Temp = %c%d.%04d\n", minus, tempint, tempfrac);*/ return raw; } /*--- ---*/ static void send_packet(void *ptr) {
static int seq_id;
char buf[MAX_PAYLOAD_LEN]; seq_id++;
//PRINTF("DATA send to %d 'Hello %d'\n",
//server_ipaddr.u8[sizeof(server_ipaddr.u8) - 1], seq_id);
PRINTF("SEND: %d\n", seq_id); unsigned int temperature; temperature=get_temperature();
sprintf(buf, "%d.%u", seq_id, temperature);
uip_udp_packet_sendto(client_conn, buf, strlen(buf), &server_ipaddr, UIP_HTONS(UDP_SERVER_PORT)); leds_toggle(LEDS_BLUE); } /*--- ---*/ static void print_local_addresses(void) { int i; uint8_t state;
PRINTF("Client IPv6 addresses: "); for(i = 0; i < UIP_DS6_ADDR_NB; i++) { state = uip_ds6_if.addr_list[i].state; if(uip_ds6_if.addr_list[i].isused &&
(state == ADDR_TENTATIVE || state == ADDR_PREFERRED)) { PRINT6ADDR(&uip_ds6_if.addr_list[i].ipaddr);
PRINTF("\n");
/* hack to make address "final" */ if (state == ADDR_TENTATIVE) { uip_ds6_if.addr_list[i].state = ADDR_PREFERRED; } } } } /*--- ---*/ static void set_global_address(void) { uip_ipaddr_t ipaddr; uip_ip6addr(&ipaddr, 0xaaaa, 0, 0, 0, 0, 0, 0, 0); uip_ds6_set_addr_iid(&ipaddr, &uip_lladdr); uip_ds6_addr_add(&ipaddr, 0, ADDR_AUTOCONF);
/* The choice of server address determines its 6LoPAN header compression.
* (Our address will be compressed Mode 3 since it is derived from our link-local address)
* Obviously the choice made here must also be selected in udp- server.c.
* For correct Wireshark decoding using a sniffer, add the /64 prefix to the 6LowPAN protocol preferences,
* e.g. set Context 0 to aaaa::. At present Wireshark copies Context/128 and then overwrites it.
* (Setting Context 0 to aaaa::1111:2222:3333:4444 will report a 16 bit compressed address of aaaa::1111:22ff:fe33:xxxx)
*
* Note the IPCMV6 checksum verification depends on the correct uncompressed addresses.
*/
//#if 0
/* Mode 1 - 64 bits inline */
uip_ip6addr(&server_ipaddr, 0xaaaa, 0, 0, 0, 0, 0, 0, 1); //#elif 1
/* Mode 2 - 16 bits inline */
//uip_ip6addr(&server_ipaddr, 0xaaaa, 0, 0, 0, 0, 0x00ff, 0xfe00, 1);
//#else
/* Mode 3 - derived from server link-local (MAC) address */ //uip_ip6addr(&server_ipaddr, 0xaaaa, 0, 0, 0, 0x0250, 0xc2ff, 0xfea8, 0xcd1a); //redbee-econotag
//#endif }
/*--- ---*/
PROCESS_THREAD(udp_client_process, ev, data) {
static struct etimer periodic; static struct ctimer backoff_timer; #if WITH_COMPOWER
static int print = 0; #endif
PROCESS_BEGIN(); PROCESS_PAUSE(); set_global_address();
PRINTF("UDP client process started\n"); print_local_addresses();
/* new connection with remote host */
client_conn = udp_new(NULL, UIP_HTONS(UDP_SERVER_PORT), NULL); if(client_conn == NULL) {
PRINTF("No UDP connection available, exiting the process!\n"); PROCESS_EXIT();
}
PRINTF("Created a connection with the server "); PRINT6ADDR(&client_conn->ripaddr);
PRINTF(" local/remote port %u/%u\n",
UIP_HTONS(client_conn->lport), UIP_HTONS(client_conn->rport)); #if WITH_COMPOWER powertrace_sniff(POWERTRACE_ON); #endif leds_on(LEDS_RED); etimer_set(&periodic, SEND_INTERVAL); while(1) { PROCESS_YIELD(); if(ev == tcpip_event) { tcpip_handler(); } if(etimer_expired(&periodic)) { etimer_reset(&periodic);
ctimer_set(&backoff_timer, SEND_TIME, send_packet, NULL); #if WITH_COMPOWER if (print == 0) { powertrace_print("#P"); } if (++print == 3) { print = 0; } #endif } } PROCESS_END(); }
Anexo A.3. Terminal de Linux
Figura 1: Interfaces por las que se conectan los tres primeros nodos.
Figura 3: Implementación del servidor.
94
ANEXO B Ejemplo RPL-Collect
Anexo B.1. Códigos de programación para el nodo sink
#include "contiki.h" #include "contiki-lib.h" #include "contiki-net.h" #include "net/ip/uip.h" #include "net/rpl/rpl.h" #include "net/linkaddr.h" #include "net/netstack.h" #include "dev/button-sensor.h" #include "dev/serial-line.h" #if CONTIKI_TARGET_Z1 #include "dev/uart0.h" #else #include "dev/uart1.h" #endif #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include "collect-common.h" #include "collect-view.h" #define DEBUG DEBUG_PRINT #include "net/ip/uip-debug.h"
#define UIP_IP_BUF ((struct uip_ip_hdr *)&uip_buf[UIP_LLH_LEN]) #define UDP_CLIENT_PORT 8775
#define UDP_SERVER_PORT 5688
static struct uip_udp_conn *server_conn;
PROCESS(udp_server_process, "UDP server process");
/*--- ---*/ void collect_common_set_sink(void) { } /*--- ---*/ void collect_common_net_print(void) { printf("I am sink!\n"); } /*--- ---*/ void collect_common_send(void) {
/* Server never sends */ } /*--- ---*/ void collect_common_net_init(void) { #if CONTIKI_TARGET_Z1 uart0_set_input(serial_line_input_byte); #else uart1_set_input(serial_line_input_byte); #endif serial_line_init(); PRINTF("I am sink!\n"); } /*--- ---*/ static void tcpip_handler(void) { uint8_t *appdata; linkaddr_t sender; uint8_t seqno; uint8_t hops; if(uip_newdata()) {
appdata = (uint8_t *)uip_appdata;
sender.u8[0] = UIP_IP_BUF->srcipaddr.u8[15]; sender.u8[1] = UIP_IP_BUF->srcipaddr.u8[14]; seqno = *appdata;
hops = uip_ds6_if.cur_hop_limit - UIP_IP_BUF->ttl + 1; collect_common_recv(&sender, seqno, hops,
} } /*--- ---*/ static void print_local_addresses(void) { int i; uint8_t state;
PRINTF("Server IPv6 addresses: "); for(i = 0; i < UIP_DS6_ADDR_NB; i++) { state = uip_ds6_if.addr_list[i].state;
if(state == ADDR_TENTATIVE || state == ADDR_PREFERRED) { PRINT6ADDR(&uip_ds6_if.addr_list[i].ipaddr);
PRINTF("\n");
/* hack to make address "final" */ if (state == ADDR_TENTATIVE) { uip_ds6_if.addr_list[i].state = ADDR_PREFERRED; } } } } /*--- ---*/
PROCESS_THREAD(udp_server_process, ev, data) {
uip_ipaddr_t ipaddr;
struct uip_ds6_addr *root_if; PROCESS_BEGIN();
PROCESS_PAUSE();
SENSORS_ACTIVATE(button_sensor); PRINTF("UDP server started\n"); #if UIP_CONF_ROUTER uip_ip6addr(&ipaddr, 0xaaaa, 0, 0, 0, 0, 0, 0, 1); /* uip_ds6_set_addr_iid(&ipaddr, &uip_lladdr); */ uip_ds6_addr_add(&ipaddr, 0, ADDR_MANUAL); root_if = uip_ds6_addr_lookup(&ipaddr); if(root_if != NULL) { rpl_dag_t *dag; dag = rpl_set_root(RPL_DEFAULT_INSTANCE,(uip_ip6addr_t *)&ipaddr); uip_ip6addr(&ipaddr, 0xaaaa, 0, 0, 0, 0, 0, 0, 0); rpl_set_prefix(dag, &ipaddr, 64);
PRINTF("created a new RPL dag\n"); } else {
}
#endif /* UIP_CONF_ROUTER */ print_local_addresses();
/* The data sink runs with a 100% duty cycle in order to ensure high
packet reception rates. */ NETSTACK_RDC.off(1);
server_conn = udp_new(NULL, UIP_HTONS(UDP_CLIENT_PORT), NULL); udp_bind(server_conn, UIP_HTONS(UDP_SERVER_PORT));
PRINTF("Created a server connection with remote address "); PRINT6ADDR(&server_conn->ripaddr);
PRINTF(" local/remote port %u/%u\n", UIP_HTONS(server_conn- >lport), UIP_HTONS(server_conn->rport)); while(1) { PROCESS_YIELD(); if(ev == tcpip_event) { tcpip_handler();
} else if (ev == sensors_event && data == &button_sensor) { PRINTF("Initiaing global repair\n");
rpl_repair_root(RPL_DEFAULT_INSTANCE); }
}
PROCESS_END(); }
Anexo B.2. Códigos de programación para el nodo sender #include "contiki.h" #include "net/ip/uip.h" #include "net/ipv6/uip-ds6.h" #include "net/ip/uip-udp-packet.h" #include "net/rpl/rpl.h" #include "dev/serial-line.h" #if CONTIKI_TARGET_Z1 #include "dev/uart0.h" #else #include "dev/uart1.h"