Low-power Wireless ECG Monitoring System for Android Devices Sistema inalámbrico de bajo consumo para monitorización de electrocardiogramas desde dispositivos Android Pablo Fernández Vicente Rafael Basilio de la Hoz Sevilla Miguel Márquez Altuna Proyecto de Sistemas Informáticos, Facultad de Informática Universidad Complutense de Madrid Departamento de Arquitectura de Computadores y Automática Curso 2011/2012 Directores: Luis Piñuel Moreno Joaqúın Recas Piorno ii Abstract People affected by specific cardiovascular diseases require of a constant mon- itoring of their vital signs, to which end specialized, high priced and big sized equipment is employed. Reduction of the energetic requirements and improvement of the portability are the objectives for the next generation of monitoring systems. This document presents the development of a low-power wireless ECG monitor- ing system for Android devices. By using the mobile phone or tablet of the user the total amount of needed devices is limited, and the application of the 802.15.4 wireless communication standard substantially decreases the energetic consumption when compared to wider spread ones like Bluetooth. The development of an USB 802.15.4 receiver device and the Android monitoring application results in a system targeting an operation as unintrusive as possible. Systems like this one have proved to be highly useful and a generalization of their employment is to be expected. Keywords ECG, Android, MSP430, FreeRTOS, Shimmer, USB, 802.15.4 Las personas afectadas por ciertas enfermedades cardiovasculares requieren de una estrecha vigilancia de sus constantes vitales, lo cual supone el empleo de equipos especializados de elevado coste y tamaño. La reducción del consumo energético y el aumento de la portabilidad son los objetivos de la próxima generación de dispositi- vos de monitorización. En este documento se presenta el desarrollo de un sistema inalámbrico de monitorización electrocardiográfica portátil de bajo consumo para dispositivos Android. Al reutilizar el terminal del usuario se reduce el número de dispositivos necesarios, y la aplicación del estándar de comunicación inalámbrica 802.15.4 disminuye el consumo de enerǵıa de forma significativa respecto al uso de otras alternativas como Bluetooth, la más empleada en este ámbito. El desarrollo de un receptor USB 802.15.4 junto con la aplicación de monitorización para An- droid resulta en un sistema orientado a ser lo menos invasivo posible en la vida del usuario final. Sistemas de estas caracteŕısticas han desmostrado ser de gran utilidad y se espera un uso generalizado de los mismos en casos de necesidad de monitorización constante. Palabras clave ECG, Android, MSP430, FreeRTOS, Shimmer, USB, 802.15.4 iii iv Pablo Fernández, Rafael de la Hoz and Miguel Márquez authorize Com- plutense University of Madrid to spread and use this report and the asso- ciated code, multimedia content and its results with academical and non- comercial purposes, provided that its authors shall be explicitly mentioned. June 28, 2012 Pablo Fernández Rafael de la Hoz Miguel Márquez v vi To Carlos, for his mad soldering skills and wise guidance, to Fran because of his healthy support, and very special thanks to everyone that has been there, bearing with us. vii viii Contents Abstract iii List of Figures xiii Resumen en Español xv 1 Introduction 1 1.1 Project description . . . . . . . . . . . . . . . . . . . . . . . . 1 1.2 Project driver . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 1.3 State of the art . . . . . . . . . . . . . . . . . . . . . . . . . . 6 1.4 Document overview . . . . . . . . . . . . . . . . . . . . . . . . 10 2 Hardware and Communications 13 2.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 2.2 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14 2.3 Technology Research . . . . . . . . . . . . . . . . . . . . . . . 14 2.3.1 Google ADK & Arduino . . . . . . . . . . . . . . . . . 14 2.3.2 MSP430 . . . . . . . . . . . . . . . . . . . . . . . . . . 15 2.3.3 ShimmerTM . . . . . . . . . . . . . . . . . . . . . . . . 17 2.3.4 802.15.4 . . . . . . . . . . . . . . . . . . . . . . . . . . 18 2.3.5 FreeRTOS . . . . . . . . . . . . . . . . . . . . . . . . . 22 2.3.6 USB device & USB host . . . . . . . . . . . . . . . . . 22 2.4 Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23 2.5 Milestones . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25 2.5.1 Arduino for Android USB Device Comunication . . . 26 2.5.2 MSP430 for Android USB Host Comunication . . . . 27 2.5.3 USB in FreeRTOS . . . . . . . . . . . . . . . . . . . . 30 2.5.4 802.15.4 in FreeRTOS . . . . . . . . . . . . . . . . . . 32 2.5.5 802.15.4 & USB coexistence under FreeRTOS . . . . . 34 2.5.6 MSP430 based device design . . . . . . . . . . . . . . 36 ix 2.5.7 Final Validation and Release Candidate Version . . . 39 2.6 Closure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39 3 Software Development 41 3.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41 3.2 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42 3.3 Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . 43 3.3.1 Functional Requirements . . . . . . . . . . . . . . . . 43 3.3.2 Non-functional Requirements . . . . . . . . . . . . . . 43 3.4 Risk Analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . 44 3.5 Use Cases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49 3.5.1 UC1. View data from Bluetooth . . . . . . . . . . . . 50 3.5.2 UC2. View data from USB Receiver . . . . . . . . . . 51 3.5.3 UC3. View data from log file . . . . . . . . . . . . . . 52 3.5.4 UC4. Adjust view parameters . . . . . . . . . . . . . . 52 3.6 Design and Architecture . . . . . . . . . . . . . . . . . . . . . 53 3.6.1 View Package . . . . . . . . . . . . . . . . . . . . . . . 56 3.6.2 Data Management Package . . . . . . . . . . . . . . . 57 3.6.3 Utilities Package . . . . . . . . . . . . . . . . . . . . . 60 3.6.4 Data Flow Model Realizations . . . . . . . . . . . . . 61 3.7 Development Process . . . . . . . . . . . . . . . . . . . . . . . 65 3.7.1 Project Scheduling . . . . . . . . . . . . . . . . . . . . 65 3.7.2 Iteration 1 . . . . . . . . . . . . . . . . . . . . . . . . . 67 3.7.3 Iteration 2 . . . . . . . . . . . . . . . . . . . . . . . . . 69 3.7.4 Iteration 3 . . . . . . . . . . . . . . . . . . . . . . . . . 70 3.7.5 Iteration 4 . . . . . . . . . . . . . . . . . . . . . . . . . 72 3.7.6 Final Validation . . . . . . . . . . . . . . . . . . . . . 73 3.8 Closure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74 4 Results 77 4.1 Final state . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77 4.2 Potential additions and expansions . . . . . . . . . . . . . . . 78 4.3 Findings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82 A Budget Analysis 87 A.1 Project tasks and scheduling . . . . . . . . . . . . . . . . . . 88 A.1.1 Hardware project tasks . . . . . . . . . . . . . . . . . 88 A.1.2 Software project tasks . . . . . . . . . . . . . . . . . . 90 A.2 Asset cost . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94 x B Product Cost 95 C Receiver Specification Documents 99 C.1 Bill Of Materials . . . . . . . . . . . . . . . . . . . . . . . . . 99 C.2 Schematic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100 C.3 Printed Circuit Board Design . . . . . . . . . . . . . . . . . . 101 Bibliography 103 xi xii List of Figures 2.1 Superframe structure with GTSs . . . . . . . . . . . . . . . . 19 2.2 Communication to a coordinator in a beacon-enabled PAN . 20 2.3 Shimmer power consumption analysis, beacon reception . . . 21 2.4 Shimmer power consumption analysis, beacon reception and data transmission . . . . . . . . . . . . . . . . . . . . . . . . . 21 3.1 Architecture overview . . . . . . . . . . . . . . . . . . . . . . 54 3.2 Data-flow model realization . . . . . . . . . . . . . . . . . . . 56 3.3 DataManager interface . . . . . . . . . . . . . . . . . . . . . . 58 3.4 DataSourceThread class . . . . . . . . . . . . . . . . . . . . . 58 3.5 DataHolder interface . . . . . . . . . . . . . . . . . . . . . . . 59 3.6 Bluetooth Model Realization . . . . . . . . . . . . . . . . . . 62 3.7 File Reader Model Realization . . . . . . . . . . . . . . . . . 63 3.8 USB Model Realization . . . . . . . . . . . . . . . . . . . . . 64 xiii xiv Resumen en Español En este documento se expone la investigación realizada con el objetivo de desarrollar un receptor del estándar de redes de área personal inalámbricas 802.15.4 del IEEE para dispositivos Android a través de USB, aplicado a un sistema completo de monitorización electrocardiográfica (ECG), aśı como el proceso de desarollo del mismo. Este sistema se enmarca en el ámbito de la atención sanitaria personal: su principal aplicación es la montorización del estado del corazón por parte de un particular, eliminando la dependencia, respecto a esta tarea espećıfica, con los sistemas de atención sanitaria tra- dicionales. Recientemente ha surgido un gran interés, tanto en el ámbito académico como en el industrial, en la producción de sistemas de monitorización ECG portátiles y de bajo consumo, llegando a ser una de las principales aplica- ciones de las redes de sensores corporales inalámbricas. Para maximizar la portabilidad, en el desarrollo de estos sistemas se han empezado a emplear dispositivos móviles de gran capacidad de cómputo, particularmente smartphones, debido a la gran difusion que han tenido en los últimos años. En el 2011 se presentó un sistema, colaboración entre la Universidad Complutense de Madrid (UCM) y la École Polytechnique Fédérale de Lausanne (EPFL), para monitorización ECG de ámbito perso- nal empleando un iPhone como visualizador y Bluetooth como tecnoloǵıa de comunicación inalámbrica. De los resultados obtenidos por ese proyecto surge la presente iniciativa que trata de llevar al siguiente nivel las caracteŕısticas inherentemente buenas de bajo consumo y bajo coste del mismo mediante la aplicación del protocolo 802.15.4, de mucho menor consumo energético que la tecnoloǵıa Bluetooth, y la sustitución del dispositivo iOS por uno basado en Android, debido a su mayor accesibilidad y el menor coste, en general, de éstos. xv El sistema desarrollado en este proyecto presenta al usuario una represen- tación visual de su onda ECG en tiempo real, resaltando puntos relevantes para simplificar la compresión de los datos mostrados. También muestra in- formación sobre el ritmo cardiaco, y toda esta información es almacenada de forma transparente al usuario para su posterior consulta. Esta funcionalidad es posible gracias a la operación conjunta de los tres dis- positivos que forman el sistema de monitorización: el nodo de delineación ECG, el receptor 802.15.4 y el dipositivo Android que actúa de interfaz con el sistema. El nodo de delineación ECG va conectado a la red de sensores corporal del usuario y se encarga de la captura y posterior análisis de la onda ECG, aśı como de la codificación y env́ıo de la misma de forma inalámbrica. El receptor 802.15.4 conectado al sistema Android a través de USB controla la recepción de datos a traves de dicho protocolo y el env́ıo de la información recibida al dispositivo Android. Éste actúa como decodificador y visualiza- dor en tiempo real, y, como interfaz con el sistema, gestiona las conexiones inalámbricas y almacena y muestra los datos recibidos. Los objetivos del proyecto son, entonces, el desarrollo de la aplicación para dispositivos Android, la producción del receptor 802.15.4 y la comunicación de ambos con un nodo delineador ECG ya existente. La aplicación para dispositivos Android, como ya se ha mencionado, es la interfaz con la que el usuario interactúa con el sistema. Su diseño sigue las prácticas comunes de aplicaciones para este sistema operativo ya que el ob- jetivo es que la curva de aprendizaje sea, si no nula, muy suave. Los motivos para emplear Android como sistema operativo base son tres: la importancia de éste entre los sistemas operativos móviles, el mayor rango de precios de los terminales que lo soportan, que permite una mayor difusión del sistema debido a la existencia de dispositivos de precio más reducido, y la naturaleza libre y de código abierto del entorno de desarrollo, caracteŕıstica que facilita la posterior expansión del sistema. Todos estos motivos pueden resumirse en que el empleo de Android como sistema operativo permite el acceso de un mayor número de usuarios al mismo. En cuanto al nodo delineador de la onda ECG, el objetivo es emplear uno ya desarrollado para el proyecto. Esto es aśı porque tanto el nodo delineador como la red de sensores corporales que capturan la onda ECG son sistemas xvi especialmente complejos cuyos desarrollos ocupaŕıan, cada uno, un proyecto de la envergadura del actual. Es más, el nodo empleado es el resultado de la colaboración de dos universidades europeas y una nod tesis doctoral. El nodo delineador que se emplea en el proyecto es obtenido en el proyecto de la UCM y la EPFL antes mencionado. Este nodo se desarrolló inicial- mente como un delineador de electrocardiograf́ıa en tiempo real de bajo consumo con capacidad para env́ıar los datos de forma inalámbrica a través de Bluetooth. En otro esfuerzo conjunto entre la EPFL y la UCM se dotó al nodo de funcionalidad para el env́ıo empleando 802.15.4, pero tan sólo al nivel necesario para realizar algunas estimaciones de consumo. Incluso con la utilización real del estándar 802.15.4 estando aún por llegar, el nodo pre- senta las caracteŕısticas necesarias para convertirse en un excelente punto de partida para el alcance de los objetivos del proyecto. El componente más importante del sistema en cuanto a este proyecto se re- fiere es el receptor USB de 802.15.4 en tiempo real para dispositivos Android. Su desarrollo es una necesidad puesto que los dispositivos Android actual- mente no proporcionan soporte para el protocolo 802.15.4, aunque śı para otros como Bluetooth o Wi-Fi. Considerando que en el nodo delineador que se toma como punto de partida para el sistema la operación que supone mayor consumo de bateŕıa es la utilización de la infraestructura Bluetooth, como confirman los estudios realizados por la UCM y la EPFL, la produc- ción del receptor 802.15.4 es, pues, imperativa. La existencia de otros proyectos con el objetivo de la dotación a dispositi- vos móviles del estándar 802.15.4 es un hecho conocido desde el inicio del proyecto, aunque éstos no tengan como objetivo el campo de la biomedicina o la monitorización personal. El motivo para no apoyar o emplear alguno de ellos es doble: por un lado, al comienzo del proyecto éstas iniciativas se encuentran o bien inconclusas o bien paralizadas; más aún, todas son proyectos aislados, generalmente desarrollados por una única persona y sin ningún tipo de soporte oficial ni garant́ıas de finalización. Por otra parte, y siguiendo la idea de obtención de un sistema de tamaño reducido, el objetivo de este proyecto es emplear el dispositivo Android como maestro en la co- municación USB, de forma que el receptor 802.15.4 obtenga la alimentación a través de él, eliminando aśı la necesidad de emplear una bateŕıa que incre- mentaŕıa el tamaño del receptor. Ninguno de los proyectos existentes emplea la capacidad de los dispositivos Android para asumir el rol de maestro en la xvii comunicación, aśı que no son de utilidad real para el proyecto. El desarrollo del proyecto viene motivado por dos razones principales: la potencial utilidad que demuestra tener un sistema de estas caracteŕısticas y el interés que suscita a nivel académico. Según la Organización Mundial de la Salud (OMS), las enfermedades cardio- vasculares representan la principal causa de mortalidad a nivel mundial. Sin embargo, la vigilancia que requieren las personas afectadas no es asumible, por lo general, por los sistemas de sanidad tradicionales. La monitorización doméstica continua supondŕıa una gran ayuda para estas personas, pero to- dav́ıa se trata un objetivo a cumplir. En un escenario como este, las redes inalámbricas de sensores corporales (wireless body sensor networks, WBSN) se presentan como herramientas de monitorización eficientes y asumibles económicamente. Particularmente, las WBSN aplicadas a la monitorización electrocardiográfica son de gran utilidad en el seguimiento de enfermedades cardiovasculares. De hecho, pro- yectos como el de la UCM y la EPFL mecionado anteriormente promueven la expansión de sistemas como estos. Además, con el uso de dispositivos portátiles, en particular smartphones, para mostrar los resultados de la monitorización se persigue la expansión de estos sistemas en todos los ámbitos de la sociedad, ya que permiten integrar el sistema en dispositivos ampliamente utilizados, evitando aśı la necesidad de cargar con aparatos adicionales. La elección de Android como plataforma reponde a los factores de difusión y menor coste de los terminales que se mencionaron anteriormente, con el objetivo principal de maximizar la ex- pansión del sistema. Asimismo se busca el uso más extendido del sistema con el aumento de la duración de la bateŕıa y la reducción del tamaño de los nodos de monitori- zación: un consumo de bateŕıa menos exigente permite un número menor de interrupciones en la monitorización producidas durante el proceso de carga de la misma, mientras que el menor tamaño del dispositivo facilita el em- leo cont́ınuo del mismo. La utilización del estándar 802.15.4 responde a la búsqueda de la realización de estos objetivos. En conjunto, el uso de un dispositivo Android con capacidad de recepción xviii 802.15.4 en un sistema de monitorización electrocardiográfica continua re- baja los requisitos de consumo de bateŕıa y tamaño del sistema completo, y de esta forma mejora la posibilidad de ser transportado y relaja las restric- ciones en su aplicación. Desde un punto de vista académico, la principal motivación que plantea el desarrollo de este proyecto es el hecho de que reune prácticamente todas las áreas de la carrera de Ingenieŕıa Informática. Desde el mismo comienzo el proyecto implica desarrollo tanto software como hardware además de inves- tigación en ámbitos externos al alcance de la propia carrera, como tecno- loǵıas inalámbricas de bajo consumo o desarrollo para dispositivos móviles, aśı como tareas de diseño y desarrollo en un amplio rango de niveles de abstracción. Se espera también que las tecnoloǵıas basadas en la especificación del estándar 802.15.4 del IEEE como ZigBee verán incrementada su relevancia a medio plazo debido a sus potenciales aplicaciones en campos como la domótica y la biomedicina, entre otros. Además, tanto el desarrollo de aplicaciones como de accesorios para smartp- hones u otro tipo de dispositivos portátiles son unas de las prácticas más habituales hoy en d́ıa en el ámbito del desarrollo de sistemas informáticos, y representan algunas de las actividades más demandadas. Por tanto, entrar en contacto con ellas proporciona una experiencia adicional en un campo puntero que no hace sino ampĺıar nuestro rango de habilidades y, por consi- guiente, incrementa nuestro valor en el mercado laboral. Al comienzo del proyecto, evaluando los objetivos, se decide hacer una dis- tinción muy clara entre dos partes del proyecto: por un lado, el desarrollo de la aplicación para Android y por otro, la investigación orientada al posterior desarrollo del receptor 802.15.4 aśı como la correcta utilización del nodo de- lineador seleccionado incluyendo las modificaciones que hubiera que hacerle al mismo. El desarrollo la aplicación Android se trata de un proyecto de desarrollo software de tamaño manejable cuyo mayor riesgo consiste en la falta de formación del equipo en el ámbito del desarrollo de aplicaciones para dispo- sitivos móviles. xix Por su parte, el desarrollo del receptor 802.15.4 implica un esfuerzo de inves- tigación hardware importante, ya que la mayoŕıa de los objetivos planteados ni siquiera se sabe si son alcanzables. Es más, el desarrollo de dispositivos electrónicos al nivel requerido por el proyecto queda fuera del alcance de la formación recibida. Todo esto provee a la parte de desarrollo e investigación sobre hardware de un nivel de incertidumbre, tanto en la posibilidad real de alcanzar los objetivos propuestos, como en la capacidad del equipo para llevarlos a cabo, muy superior al existente en el desarrollo software. Esta situación propicia la división del proyecto en dos subproyectos a desa- rrollar de forma independiente pero teniendo en cuenta en todo momento la estrecha relación entre uno y otro. De esta forma en cada desarrollo se pue- den aplicar las metodoloǵıas, técnicas y planificaciones más apropiadas para el tipo de trabajo concreto a realizar. Atendiendo a la estrecha dependencia entre los dos proyectos, y buscando evitar grandes descompensaciones entre ambos, se fija una planificación común a todo el proyecto de forma que cier- tos hitos deben alcanzarse a la par en ambos desarrollos. De esta forma se asegura que la funcionalidad producida por un proyecto se completa en el otro mientras se deja libertad para aplicar el enfoque que se considere más efectivo en cada proyecto durante los ciclos de desarrollo. Además, dada la incertidumbre asociada a la investigación hardware, los pla- zos temporales para los hitos se asumen como variables y se manejan planes de actuación en la planificación del proyecto de desarrollo software para que el trabajo no se vea detenido por los potenciales retrasos. Se considera, en- tonces, que el camino cŕıtico del proyecto está definido por el proyecto de investigación y desarrollo hardware y el proyecto de desarrollo software debe adaptarse a sus necesidades. Aún y aśı en la planificación del primero no se dejan de tener en cuenta las posibles contingencias del desarrollo software. La tecnoloǵıa seleccionada para el desarrollo del proyecto es la siguiente: • El dispositivo móvil tipo tableta basado en Android Motorola Xoom Escogido entre otros modelos de terminales que soportan Android por su capacidad para asumir el rol de maestro en la comunicación USB. Además, la capacidad del procesador que incorpora y el hecho de in- tegrar una GPU lo hacen especialmente aplicable para la consecución del objetivo de mostrar los datos de la electrocardiograf́ıa en tiempo real. xx • Nodo delineador de ECG del proyecto de la UCM y la EPFL Este nodo se basa en la plataforma inalámbrica de sensores corpora- les Shimmer para la captura de la onda electrocardiográfica y realiza un análisis de la misma (denominado delineación), enviando los datos a través de Bluetooth o, potencialmente, 802.15.4. El firmware que ejecuta el nodo se encuentra completamente desarrollado y validado al comienzo del presente proyecto, salvo la funcionalidad de env́ıo a través de 802.15.4, que si bien está implementada en el dispositivo, no se ha probado de forma exhaustiva. • La familia de microprocesadores de 16 bits MSP430 de la firma Texas Instruments Su elección se realiza teniendo en cuenta tanto su reducido consumo de enerǵıa como la sencillez en su programación, que permite utilizar C y depurar a través del estándar JTAG; pero principalmente por el hecho de que el nodo delineador ECG a emplear en el sistema uti- liza esta misma familia de microprocesadores, y existe la posibilidad de reutilizar parte del código, especialmente el sistema operativo y la funcionalidad relacionada con env́ıo inalámbrico a través de 802.15.4. • Sistema operativo de tiempo real FreeRTOS para dispositivos empotra- dos El empleo de este sistema operativo viene determinado por la elección del nodo delineador, ya que éste emplea FreeRTOS y la implemen- tación de la capa MAC 802.15.4 para dicho sistema operativo se en- cuentra disponible y puede ser aplicada en el proyecto. Es más, dado que el microprocesador que llevará el receptor a desarrollar es muy similar al del nodo delineador, el sistema operativo puede ser utili- zado directamente en el receptor sin esperar la necesidad de muchas modificaciones. Como se menciona antes, la implementación de la ca- pa MAC 802.15.4 para FreeRTOS implementación no está totalmente completa, pero es un buen punto de partida. Cada tecnoloǵıa se aplica en uno de los subsistemas que forman el sistema completo. Aunque se ha trabajado también con otras tecnoloǵıas, éstas se irán mencionando a lo largo de la exposición del desarrollo del proyecto que se realiza a continuación, y por tanto se omite su enumeración en este pun- to. Se analiza primero el desarrollo relacionado con la parte de hardware del xxi proyecto. El subproyecto de hardware contempla dos fases: por un lado la investigación sobre la factibilidad y la forma de alcanzar los objetivos propuestos, y por otro el desarrollo necesario para alcanzar dichos objetivos. Los objetivos concretos de este subproyecto son: 1. Lograr la comunicación de un microprocesador MSP430 mediante USB con el dispositivo Android 2. Inclusión de capacidad de comunicación a través USB en FreeRTOS 3. Empleo de 802.15.4 en FreeRTOS en el procesador MSP430 seleccio- nado 4. Asegurar la correcta operación de los módulos USB y 802.15.4 sobre FreeRTOS 5. Diseñar el circuito impreso espećıfico para dispositivo receptor USB 802.15.4 6. Validación y producción del dispositivo receptor a partir del diseño Debido a las restricciones de tiempo y de disponibilidad del equipo al tener que hacer frente a este subproyecto en paralelo con el desarrollo software, se toma la decisión de establecer estos objetivos como los hitos para la planifi- cación, añadiendo uno extra que contempla una fase de prototipado inicial sobre una placa Arduino, que es bastante más sencillo que trabajar direc- tamente con un MSP430 y sirve como toma de contacto inicial. Como se menciona anteriormente, los plazos para estos hitos se establecen tentativa- mente debido a la incertidumbre de cada objetivo. Cabe mencionar que en lugar de separar las fases de investigación y desarro- llo asociadas a cada objetivo se opta por no establecer ĺımites fijos entre ellas, de forma que cada objetivo comienza con el planteamiento de las potenciales ĺıneas de investigación del mismo. Seguidamente comienza el desarrollo de una de las ĺıneas de investigación propuestas, y si se llega a un resultado negativo, se descarta el trabajo y se selecciona otra ĺınea de investigación. Este sistema, cercano a las metodoloǵıas de desarrollo extremas basadas en prototipos, junto con la flexibilidad de la planificación propuesta ha resul- tado ser clave para la correcta consecución de los objetivos del subproyecto xxii de hardware. Detallamos ahora el proceso de desarrollo del subproyecto de software. Sien- do este más cercano a un desarrollo tradicional, con menos incertidumbre en cuanto al resultado, se opta por aplicar una metodoloǵıa de desarrollo orde- nada con la que se asegure el cumplimiento de los plazos establecidos por el subproyecto de hardware. Debido a que se aplican las mismas restricciones temporales y de compartición de recursos que las expuestas anteriormente para el subproyecto de hardware, precisamente por la conducción de ambos en paralelo, se descarta la aplicación de metodoloǵıas de desarrollo con gran dependencia de la producción de artefactos, aśı como de metodoloǵıas que requieran planificaciones fijas. Se opta, entonces, por la aplicación de una metodoloǵıa h́ıbrida entre una metodoloǵıa iterativa y una metodoloǵıa de desarrollo rápido. Esto se tradu- ce en el establecimiento de una planificación inicial en base a los objetivos del subproyecto de hardware. Esta planificación empareja los hitos del desarrollo hardware con la funcionalidad correspondiente de la aplicación Android y, centrándose en construir la mayor cantidad de funcionalidad posible cuanto antes, distribuye el resto de objetivos del subproyecto software. Además es necesario asumir en todo momento la posibilidad de una modificación en las fechas. Para hacer frente a ese tipo de contingencias se decide aplicar técnicas pro- pias de metodoloǵıas iterativas como el análisis de riesgos y el desarrollo basado en casos de uso. De esta forma se mantiene el foco en el desarrollo de la funcionalidad clave aún cuando sea necesario un reajuste de los plazos o una mayor dedicación de recursos al subproyecto de hardware. Los casos de uso identificados para el sistema son los siguientes: • UC1. Visualizar datos obtenidos por Bluetooth • UC2. Visualizar datos obtenidos por receptor USB • UC3. Visualizar datos de un archivo de log • UC4. Ajustar parámetros de visualización Como el receptor USB 802.15.4 es la culminación de la investigación hard- ware, la planificación de los esfuerzos de desarrollo se plantea de forma que xxiii todo el resto de la funcionalidad se construya y valide mientras el subproyec- to de hardware desarrolla un prototipo del receptor, y una vez se tenga este prototipo se proceda a la implementación de la funcionalidad relacionada mientras se desarrolla la versión final. Gracias a este tipo de planificación y al minucioso análisis de riesgos llevado a cabo durante todo el desarrollo, los objetivos del subproyecto de software también han sido alcanzados de forma satisfactoria. Se ha logrado, entonces, la producción de un sistema de monitorización electrocardiográfica en tiempo real de bajo consumo y tamaño reducido em- pleando un dispositivo Android como interfaz con el usuario y el estándar 802.15.4 como protocolo de transmisión de datos inalámbrico. Este sistema provee toda la funcionalidad requerida: visualización de la onda ECG en tiempo real proveniente de nodos tanto 802.15.4 como Bluetooth, almacena- miento de ésta de forma permanente en archivos y su posterior visualización, aśı como capacidad para configurar los parámetros de la visualización tanto en tiempo real como de archivos. El sistema es, pues, una versión más acce- sible gracias al empleo de dispositivos Android y con un consumo energéti- co dos órdenes de magnitud menor del sistema producido en 2011 por la Universidad Complutense de Madrid y la École Polytechnique Fédérale de Lausanne, lo cual es el principal objetivo del proyecto. Este hito se alcanza gracias a la correcta finalización tanto del subproyecto de investigación hardware como del de desarrollo software en que se dividide el proyecto. Las diferencias en el enfoque requeridas por cada subproyecto sumadas a la estricta dependencia entre ambos resultaban una complicación añadida en la previsión del resultado de los dos desarrollos; pero, gracias a la aplicación de planificaciones flexibles pero de objetivos firmes en cada uno que no dejaban de tener en cuenta posibles complicaciones en el otro, y que contaban con planes tanto de contingencia como de actuación ante ellas, se manejaron correctamente ambos proyectos, dando lugar al actual estado de finalización satisfactoria del proyecto. En cuanto al subproyecto de hardware, la producción del receptor USB de 802.15.4 para dispositivos Android se ha llevado a cabo con éxito. El disposi- tivo ha evolucionado desde las primeras etapas donde se empleaba una placa de prototipado hasta llegar a ser un circuito integrado diseñado expresamen- te para el proyecto. Este circuito integrado está completamente diseñado y validado, que en el momento en el que se escribe este documento está en xxiv proceso de fabricación. En su lugar se ha utilizado un prototipo, de tamaño algo más reducido pero construido a partir del diseño final de la placa, para la validación del sistema. Las dimensiones del prototipo son 7.25 x 6.35 x 3.5 cm y necesita 3.3V de alimentación, aunque es utilizable a partir de 3.0V. La conexión USB es la que proporciona esta alimentación y además permite emplear el dispositivo en cualquier sistema capaz de comunicarse mediante HID, y ha sido proba- do con éxito tanto en dispositivos Android como en ordenadores ejecutando varias versiones de Windows. Con respecto a la aplicación para terminales Android producida en el sub- proyecto de software, proporciona toda la funcionalidad que entra dentro de los objetivos del proyecto de forma robusta y con un diseño similar al de las aplicaciones canónicas de Android. Es una aplicación, dentro del domi- nio espećıfico de la monitorización electrocardigráfica, con funcionalidad de propósito general, que requeriŕıa cierta especialización para ser realmente útil. Esta especialización deberá añadir funcionalidad para el escenario de aplicación particular, y el análisis de esos escenarios o la posible implemen- tación de alguno de ellos queda fuera de los objetivos del proyecto. En cualquier caso, siendo conscientes de la necesidad de especialización fu- tura de la aplicación, durante el diseño y desarrollo de la misma se puso un gran énfasis en que, además de ofrecer la funcionalidad requerida, pro- porcionase un conjunto de herramientas tal que pudiera actuar como un framework sobre el cual se pueda realizar el desarrollo de aplicaciones de monitorización ECG más espećıficas. Como detalle, mencionar que además de que el sistema está preparado para la inclusión sencilla de nuevas fuen- tes de datos además de Bluetooth, 802.15.4 y archivos, la fuente de datos de 802.15.4 en realidad es un dispositivo USB, en concreto el receptor, por lo que podŕıa emplearse cualquier otro periférico que enviase datos con la codificación esperada en su lugar. Esto da una idea de la flexibilidad buscada, y alcanzada, del sistema de mo- nitorización desarrollado. Apoyándose en ella, se plantean potenciales ĺıneas de trabajo futuro, distinguiendo entre las que se podŕıan realizar a corto plazo y las que seŕıan ya para un medio o largo plazo. Por un lado, un particular afectado de una enfermedad cardiovascular que xxv requiere de monitorización electrocardiográfica constante, observando los ob- jetivos y los resultados del proyecto actual, presentó al departamento un proyecto de especialización del sistema desarrollado para sus necesidades particulares, que son comunes al colectivo de afectados por dicha enfer- medad. Este nuevo sistema ha de incorporar, además de la funcionalidad presente en el actual, algunas caracteŕısticas nuevas: • Etiquetado de eventos durante la delineación, de forma que el usua- rio pueda indicar al sistema en qué momentos se encuentra mal y la información quede almacenada junto a la onda ECG. De esta forma podŕıa estudiarse posteriormente la información guardada de forma más detallada para mejorar la compresión del estado del paciente. • Adición de información temporal a los logs, de manera que el usuario pueda consultar directamente la onda ECG relativa a un momento concreto en el que se encontró mal, o que pueda saltar al momento indicado por un marcador de eventos. Esto facilitaŕıa la consulta y navegación por los datos almacenados. • Comandos de voz que permitan interactuar con el sistema sin nece- sidad de emplear las manos, ya que, ya sea por su estado de salud o porque las tenga ocupadas, es posible que el usuario no pueda manejar la aplicación. • Avisos automáticos en caso de que se produzca algún evento relevante relacionado con la salud del usuario, de manera que se pueda alertar al mismo, algún pariente o personal cualificado en caso de ser necesario. Además, estos avisos podŕıan hacerse de varias formas, ya sea a través de mensaje, correos electrónicos con localización GPS adjunta o incluso llamadas de voz automáticas directamente. Por otra parte, se contemplan una serie de expansiones del sistema más a largo plazo, debido sobre todo a que requieren de más tiempo y recursos, aparte de una planificación espećıfica. En primer lugar se proponen mejo- ras enfocadas a la monitorización de varios pacientes, para un entorno más profesional, en dos posibles versiones: • Dado que el receptor desarrollado también es compatible con disposi- tivos que soporten el protocolo HID, se propone utilizarlo conectado a un PC que actúe como servidor, recibiendo los datos ECG proce- dentes de los nodos de varios pacientes. Una vez estos datos están en xxvi el servidor, la propia aplicación Android permitiŕıa conectarse a este para descargarlos y visualizarlos en el dispositivo. • Teniendo en cuenta que la pantalla de un tablet es relativamente gran- de, se puede aprovechar para mostrar los resultados de la monitoriza- ción de varios pacientes a la vez. Como parte de esta nueva funcio- nalidad también se encontraŕıa la de cambiar entre la onda ECG de otros pacientes, guardado de logs simultáneo y subida a un servidor dedicado. También a largo plazo, aunque en el campo de la automonitorización, se plantea la adaptación del sistema a dominios particulares que imponen re- quisitos adicionales debido, sobre todo, al entorno en el que se utilizaŕıa. En este sentido, el director del Laboratorio de Sistemas Empotrados (ESL) de la EPFL (equipo responsable junto a la UCM del desarrollo del nodo delineador que se usa en este proyecto) ha mostrado interés en la aplicación de los bajos requisitos de consumo del sistema en otro proyecto de la EPFL con el que está colaborando, el Solar Impulse. Este proyecto en concreto trata de conseguir un vuelo alrededor del mun- do evitando el uso de carburantes de cualquier tipo, utilizando únicamente enerǵıa solar. El avión utilizado es de una única plaza, por lo que las cons- tantes vitales del piloto deben estar monitorizadas en todo momento. Por el momento, la monitorización electrocardiográfica se lleva a cabo utilizando el sistema desarrollado por la UCM y la EPFL, con la escasa duración de bateŕıa que ello implica. Teniendo en cuenta que el espacio dentro de la cabina es muy reducido, cualquier tarea debe ser llevada a cabo con especial cuidado y únicamente cuando sea absolutamente necesario. Es por ello que el intercambio de la bateŕıa del nodo delineador debe ser una tarea lo menos frecuente posible, entre otras razones porque interrumpe la monitorización en el proceso. Por tanto, la reducción del consumo de enerǵıa y el consiguiente aumento de la duración de la bateŕıa plantean un avance muy significativo para un proyecto como el del Solar Impulse, tarea que se puede conseguir mediante el empleo del estándar 802.15.4 como protocolo de comunicación inalámbrico. Llegados a este punto, con el proyecto finalizado y habiendo analizado el estado final del mismo, aśı como algunas de las potenciales ĺıneas de trabajo xxvii futuro, parece relevante plantear algunas conclusiones alcanzadas durante el desarrollo a modo de conclusión. En la fase de inicio del proyecto, incluso habiendo ya decidido el emplo de un dispositivo Android como la interfaz para mostar los datos en tiempo real, el equipo teńıa cierto recelo acerca de la aplicación de Android como base para el desarrollo de aplicaciones con las restricciones de tiempo real como las que impońıa el proyecto. Durante el proceso de desarrollo el hecho de que Android posiblemente no sea la plataforma más adecuada para es- te tipo de funcionalidad se hizo patente ya que, incluso con la potencia de cómputo y las capacidades gráficas de los dispositivos actuales, las restric- ciones impuestas por el sistema operativo complican considerablemente la implementación fiable de funcionalidad en tiempo real. En un sistema como el desarrollado en este proyecto el empleo de un dispo- sitivo especialmente dedicado a la visualización y almacenamiento de datos en tiempo real hubiera permitido un nivel mayor de fiabilidad, e incluso una representación más visualmente atractiva, cumpliendo además con las restricciones temporales, pero los beneficios de utilizar Android compensan ampliamente este tipo de carencias. Entre los más importantes de estos beneficios, al menos en el ámbito del proyecto, se encuentran la sencillez en el desarrollo de aplicaciones para Android, que simplifica la ampliación del sistema en el futuro, y, aún más relevante, la amplia difusión de estos dispositivos entre el público general, de forma que el sistema es mucho más accesible. Si bien estos beneficios se han tratado a lo largo de todo este documento, se antojaban merecedores de una última mención. La selección, pues, de Android como plataforma para la aplicación del sistema puede considerarse como una de las decisiones más acertadas del proyecto. Incluso con la sencillez que Android aporta a la parte de desarrollo softwa- re, procesos de desarrollo como el llevado a cabo en este proyecto, que dan lugar a subproyectos de diferentes caracteŕısticas y con dependencias entre ellos, pueden llegar a ser empresas inalcanzables si no se encaran de mane- ra adecuada. Más aún, en este caso concreto el carácter principalmente de investigación de la rama de desarrollo hardware no haćıa sino complicar el planteamiento del proceso. xxviii Durante el desarrollo del proyecto se han aplicado algunas técnicas que han probado ser de gran relevancia para la correcta finalización del mismo. Las más relevantes son, como se expone anteriormente, el empleo de una pla- nificación flexible que admita modificaciones, ya que debe basarse en supo- siciones la mayor parte del tiempo; la utilización de un proceso de gestión de riesgos minucioso para contrarrestar las dificultades producidas por los potenciales cambios en la planificación y el mantenimiento del foco sobre el objetivo actual, sus plazos y dependencias, gracias a una metodoloǵıa de desarrollo basada en casos de uso. Gran parte del éxito en la satisfacción de objetivos de este proyecto puede otorgarse a la aplicación rigurosa de las técnicas anteriores. La importancia de los sistemas de monitorización para colectivos afectados por enfermedades cardiovasculares espećıficas ha quedado patente durante el desarrollo del proyecto. Este área presenta un gran potencial de desarrollo, especialmente si se considera que estos sistemas van a ser utilizados en su d́ıa a d́ıa por la gente que los necesite. Los proyectos surgidos en este área deben considerar siempre al usuario final durante todo el proceso de desa- rrollo ya que un pequeño esfuerzo de cara a este, como reducir el número de operaciones requeridas para iniciar la visualización o simplificar la manera en que se interactúa con la aplicación, por pequeños que puedan parecer los efectos, puede mejorar sensiblemente la calidad de vida del usuario. Esto es aśı porque molestias aparentemente inocuas en la interfaz de usuario, por ejemplo, pueden convertirse en una fuente constante de frustración cuando la aplicación se utiliza d́ıa tras d́ıa. Mediante la producción de un monitor ECG de bajo consumo energético se contribuye a este fin disminuyendo la cantidad de interrupciones que sufre el proceso de monitorización debido a la necesidad de efectuar la carga de la bateŕıa del nodo delineador con la consiguiente alteración del ritmo de vida normal del usuario. Gracias a la aplicación del protocolo de comunicación inalámbrico 802.15.4 la vida de la bateŕıa se incrementa en dos órdenes de magnitud, lo cual se traduce en tener que cargarla una vez a la semana en lugar de dos veces al d́ıa. En la misma ĺınea, la utilización de Android en lugar de iOS permite que la aplicación de monitorización, que muestra y, más importante, almacena los datos de la onda ECG en tiempo real trabaje en segundo plano de forma que su ejecución no se ve interrumpida por eventos comunes como una llamada xxix telefónica entrante o la necesidad de buscar algo en Internet empleando el dispositivo. Otra caracteŕıstica importante que proporciona Android es la capacidad de las aplicaciones de continuar su ejecución cuando el dispositi- vo entra en modo de ahorro de enerǵıa, por ejemplo apagando la pantalla. Como antes, esto puede parecer algo anecdótico, pero para una persona que necesita monitorización constante se trata de caracteŕısticas de gran impor- tancia ya que afectan a la actividad que realiza en su vida diaria. Como confirmación de estas afirmaciones, durante las fases finales del desa- rrollo del proyecto, antes incluso de haber comenzado el proceso de valida- ción, el particular afectado de una enfermedad cardiovascular antes men- cionado contactó con el departamento en el que se desarrolla el proyecto y mostró gran interés en el mismo tras ser informado de los objetivos y resul- tados alcanzados. La interacción con esta persona produjo el proyecto futuro explicado anteriormente para la especialización del sistema desarollado a las necesidades de la enfermedad particular. Además, esta persona se encuentra actualmente realizando una prueba del sistema en un escenario de aplicación real como es su caso, los resultados aún por llegar en el momento de escri- bir el presente documento, y está dispuesto a colaborar en todo lo posible con el proyecto y sus futuras evoluciones, ya que le pueden ser de gran ayuda. Es más, como se menciona antes, el director del Laboratorio de Sistemas Empotrados (ESL) de la EPFL está interesado en los resultados del proyec- to para aplicarlos al proyecto Solar Impulse con el objetivo de monitorizar continuamente al piloto del aeroplano solar. La nave está equipada con un dispositivo tipo tablet para varios fines, y la utilización del mismo como visualizador de la monitorización, aśı como la reducción del consumo de bateŕıa del nodo delineador tanto como sea posible debido a lo cŕıtico del ahorro energético en el vuelo solar, constituyen un gran escenario para la aplicación de los resultados del proyecto. Es comprensible, entonces, que estas muestras de interés en el proyecto con- vierten el desarrollo en un éxito independientemente del resultado final. El hecho de que el trabajo realizado durante los últimos meses se confirme co- mo capaz de proporcionar beneficios reales a determinadas personas, lo cual era, en el fondo, el objetivo último del proyecto, hace que todas las dificul- tades del proceso sean meramente anecdóticas al compararlas con el orgullo personal que, en efecto, proporciona. xxx Chapter 1 Introduction 1.1 Project description This document exposes the research conducted for the development of an USB 802.15.4 receiver device for Android based systems employed in a fully functional electrocardiogram monitoring system encompassed in the field of in-home healthcare, as well as the development process involved in the re- alization of this whole system. Electrocardiogram (ECG) monitoring consists of the capture and interpre- tation of the activity of the heart during a period of time, and continuous, remote ECG monitoring has become one of the main applications of wireless body sensor networks. Great interest has arisen recently among industrial and academic research parties in production of low-power, ambulatory ECG monitoring systems. In order to maximize portability, such systems have started to employ the widely available smartphone devices as frontends, reducing the amount of extra devices carried by the user to just the ECG capturing node. In 2011 the Complutense University of Madrid (UCM) in collaboration with the École Polytechnique Fédérale de Lausanne (EPFL) presented a real-time personal ECG monitoring system which displayed data in an iPhone via Bluetooth [1]. Being inspired by the results obtained by the aforementioned project, this certain endeavour seeks taking the inherently good low cost and low power aspects of that to the next level by the employment of a less energy requir- ing wireless personal area network protocol, namely IEEE 802.15.4, and the 1 Introduction more accessible Android based platforms. The system which is to be developed in this project provides the user with a visual representation of his/her ECG wave in real-time highlighting relevant points of this in order to simplify its comprehension. Information about heart-beat-rate is also displayed. All this data is stored in a transparent to the user manner for later visualization with emphasis put in easy handling of the generated files. This functionality is provided by the three devices that are part of the sys- tem: the ECG delineation node, the USB 802.15.4 receiver and the Android device through the front-end application. The ECG delineation node is connected to the body sensor network and is responsible for capturing and analyzing the electrocardiogram wave, as well as encoding and wirelessly sending the data. The USB 802.15.4 receiver is plugged to the Android system and manages data reception following the aforementioned protocol. Finally the Android based application is the real-time data decoder and acts as the frontend to the user, managing connections and storing and display- ing received data. Development of the Android application, realization of the real-time USB 802.15.4 receiver device, employment of an already-existant ECG delineation node and successful intercommunication between all these elements are the project goals. As stated before, the Android application is the front-end with which the user interacts with the whole system. It is designed following Android com- mon practices as the objective is for it to be of simple use with a smooth, if not nil, learning curve. The decision to develop the application for Android platforms was made according to three main reasons: First, the fact that Android has been in the top three of the most used mo- bile operating systems rankings since 2010 [2] added to the recent growth of the availability of smartphone devices [3] makes targeting the Android platform a must when the objective is making the system reachable for as most people as possible. Second, and following the same line of reasoning, the lower cost, in general terms, of Android supporting devices, or at least the wide range of prices 2 Low-power Wireless ECG Monitoring System for Android Devices Project description of these, specially when compared to other operating systems supporting devices such as Apple’s range of iOS devices is to be taken into account. And finally the comfortable, high-level development environment available for Android application production [4] provides enough facilities for any- one interested in expanding or contributing code to the Android part of the project to do so in an easy way. Moreover, this environment is delivered free of charge and is of an open-source nature and multiplatform [5], whereas iOS platform development kits usage requires at least the ownership of an specific machine and operating system [6]. Regarding the ECG delineation node, it has been mentioned that the ob- jective of this project is the employment of an already existing one. That is so because both the delineator node and the body sensor network that captures the data are complex systems and the development of them would be the scope of a full project. Specifically the delineator node obtained in the aforementioned project [1], with modifications from another collabora- tion between the UCM and the EPFL [7], was applied. This node was originally developed as a ultra-lowpower real-time ECG de- lineator with the ability to wirelessly send data through Bluetooth protocol. The collaboration between UCM and EPFL, among other things, provided the node with functionality to send data using IEEE 802.15.4, but only at the level required to do some measurement and estimations [7]. Actual 802.15.4 utilization was yet to be a reality, but it was an excellent starting point towards the achievement of the current project objectives. The key part of the system and the most important risk involving objec- tive of the project is the real-time 802.15.4 USB receiver device for Android platforms. It is a necessity as Android devices generally have no support for low cost wireless communication protocols such as 802.15.4, while providing other higher-cost protocols such as Bluetooth or Wi-Fi. Development of an Android accesory providing the required functionality is, then, a must, as the most battery and time consuming operation in the delineator node is the utilization of the Bluetooth stack, as previously mentioned researches [1] and [7] concluded. Other projects exist with the objective of achieving 802.15.4 reception for Android devices, even if they are not targeted at the field of biomedics and Low-power Wireless ECG Monitoring System for Android Devices 3 Introduction personal monitoring. The reason for not following or employing those is twofold: first, at the time of the beginning of the project those initiatives were either unfinished or stalled (as it can be seen in [8]), furthermore they were isolated, generally single-man projects with no official backend or guar- antees of conclusion. Second, following the line of achieving a low energy, low sized device the Android system of this project is to act as the host de- vice in the USB communication, thus removing the size-increasing battery requirements for the receiver as the host role provides the power in such communications. None of these projects employed the host capability of Android devices, so they were of no use for the pursued objectives. In short, this project tries to advance a step further the availability of wire- less body sensor networks applied to personal electrocardiogram monitoriza- tion, by employing actual, already available, not-so-expensive technologies in an effective manner. That is necessarily good by nature, and the main motivation for braving with the project, aside from those, more pragmatic, exposed in the next section, is the wish for it to be useful, some day, for someone. 1.2 Project driver The motivation for the realization of this project comes from two different areas: the further potential utility of the project and the academic interest it involves. The potential utility of the project point of view is developed first. Cardiovascular diseases are the number one cause of death globally, accord- ing to the World Health Organization [9]. The level of supervision required by affected people is usually not assumible by traditional health care insti- tutions, and constant, in home monitorization is an objective yet to fulfill which can be of great help for affected inviduals. In such an scenario wireless body sensor networks (WBSN) prove to be inex- pensive, efficient monitoring tools. Specifically electrocardiogram monitor- ing applied WBSN are of great utility for constant tracking of cardiovascular diseases, and projects as the aforementioned UCM and EPFL collaboration pursue the realization of a wide employment of these systems. 4 Low-power Wireless ECG Monitoring System for Android Devices Project driver The employment of smartphone devices as the monitoring display of the system targets the wide spreading of the application of these systems, and reduces the amount of devices to be carried by the user. The selection of Android as the base platform for the display part this project, as ex- plained before, is made attending to two factors: the higher expansion of the Android operating system when compared to others, and the flexible, open-source nature of it. These are key for the further expansion and appli- cation of the system. Reducing battery and size requirements also targets a higher employment of the system by simplifying the usage procedure: lower battery requirements involve less monitoring interruptions due to the charging of the system and lower sized devices allow higher portabilty and more constant monitoriza- tion. The employment of the 802.15.4 wireless protocol seeks the fulfillment of this objectives. In conclusion, the employment of an 802.15.4 receiving enabled Android de- vice in a real-time, continous ECG monitoring system reduces the battery and size requirements for the system, maximizing portability and lessening the restrictions on the applicability of it. From an academic point of view, the main motivation for the development of this project is the fact that it means the gathering of almost every branch of the Computer Science and Engineering career. From its very beginning, the project involves both software and hardware development, researching on out of the scope of the career tools and platforms as well as high and low-level design and programming. It is also expected that technologies based on IEEE 802.15.4 specification like ZigBee will increase their importance in the medium term due to their potential applications in domotics (home automation) and other areas. In addition, both the development of applications and accessories for smart- phones or other portable devices are mainstream, highly demanded activities nowadays and getting in touch with these provides extra experience at lead- ing edge practices, which broadens our areas of expertise and, consequently, increment our value in the labour market. Low-power Wireless ECG Monitoring System for Android Devices 5 Introduction 1.3 State of the art • UCM and EPFL ECG monitoring Project As a precedent of the present project, the Complutense University of Madrid (UCM), along with the École Polytechnique Fédérale de Lausanne (EPFL) –represented by its Embedded Systems Laboratory (ESL)–, developed a wireless ECG monitoring system [1], similar to the one has been built up during this project. Just as ours, this system also used ShimmerTMas monitoring, trans- mitter platform (details about it can be found at subsection 2.3.3); and the obtained data could be displayed in portable computing de- vices. Nonetheless, the list of similarities ends there. The application responsible for rendering the ECG waves was meant to be used over iOS devices, particularly iPhone. This fact led to several additional restrictions, such as mandatory usage of Bluetooth as wireless trans- mission method as well as the need of “jailbreaking” the device itself. This process allows the user to gain root access to the OS, and it was needed in order that a explicitly installed Bluetooth stack allowed the device to receive the emitted data properly. However, according to the manufacturer [10], jailbreaking the device nulls its warranty. There- fore, the employment of Android in our project is partially motivated by this sort of limitations other platforms usually impose. Whereas the UCM was responsible of the delineation algorithm, the development of the iOS application was carried out by the EPFL, and thus the development of this project depended on the feedback and requirements (hardware and software) both of them provided. In fact, the aforementioned iOS application settled most of the requirements for the Android one in this project, although there were added some extra ones –such as making logs from received data so they can be read again later–. • IEEE 802.15.4 This standard describes the physical and Media Access Control (MAC) layers for low-rate wireless personal area networks. It is intended to be implemented into embedded devices, so as to build up short-range net- works –10 meters, typically– with narrow bandwith, up to 250kbps, 6 Low-power Wireless ECG Monitoring System for Android Devices State of the art among other possibilites with lower transfer rates. It is a relatively new standard since its first version was approved in 2003, although the following revision was employed during this development, which was approved in 2006 [11]. 802.15.4 is specially suitable for this kind of project due to its low power consumption. In fact, ZigBee, which uses this standard as its low-level layer, presents a series of advantages over Bluetooth, under- lying technology of the previously mentioned EPFL and UCM project: – Lower power consumption: without going into detail, it can be stated that Bluetooth requires more power than ZigBee does. For example, Bluetooth is constantly emitting information, con- sequently consuming power, while 802.15.4 allows to enable the radio only when it is needed. These statements are properly jus- tified and explained at subsection 2.3.4, 802.15.4. – Bandwidth: Bluetooth offers much wider bandwidth, up to 3Mbps, meanwhile ZigBee only offers up to 250kbps. This, how- ever, is not a relevant disadvantage because the requirements of the system are not so demanding. – Host number: ZigBee allows to build networks with up to 65535 hosts, subnetworks with 255 hosts. On the other hand, Bluetooth can only support as much as 8 hosts within a network. ZigBee, though, is not employed as a whole within this project, but 802.15.4 standard as its basis (its MAC layer, more precisely). Nev- ertheless, its advantages over Bluetooth remains the same, with the additional one that it does not compromise real-time developments as the complete stack does. • Android Accessory Development As of May, 2011, there were no easy nor official methods to develop accessories capable of communicating with Android running devices. At that certain time, the release of the Android Open Accessory De- velopment Kit (also known as “ADK”) [12] was announced in San Francisco, within the context of Google I/O, developers conference ar- ranged by Google [13]. Low-power Wireless ECG Monitoring System for Android Devices 7 Introduction ADK consists of an USB microcontroller board based on Arduino (Ar- duino Mega2560 to be precise) and a series of software libraries which add specific functionalities and support for other hardware add-ons, typically known as shields, that equip the accessory with sensors or in- teractive elements which broaden its capabilities. Shields are plugged to the board through its numerous input/output pins, which also al- low the connection of personally crafted hardware additions –allowing that way to create tailored behaviours, following the Arduino’s “Do It Yourself” (DIY) spirit. With the release of that kit, Android project opened itself to the de- velopment of all kind of new accessories which would add potential and functionalities it lacked. As well as this kit, the following release of Android 3.1 API version completed the accessory ecosystem with the inclusion of directly sup- ported host and device USB modes –this support was also backported to Android v2.3.4; only the device mode, though–. By doing so, Google completely cleared the way for the development of Android-compatible accessories, which was previously reduced to the underlying, quite complete but not enough, Linux kernel driver support. • ZigBee dongles In spite of the fact that there were available devices which implemented the complete ZigBee stack at the time of the start of this project, they were only designed for being connected to personal computers, some models with OS restrictions as well. A typical model of this sort is presented in [14]. Moreover, even if they were to be compatible with our target device, the only available dongles fully implemented the ZigBee stack, which also made them unsuitable for this project due to the relatively high la- tency that fact imposed –as it can be read at subsection 2.3.4, 802.15.4, real-time needs required the usage of the 802.15.4 MAC layer on its own–. • Communication with Android using ZigBee One year ago, around mid-2011, there were very few projects which were working on this sort of communication, between Android and 8 Low-power Wireless ECG Monitoring System for Android Devices State of the art 802.15.4 radio-equipped devices. Concretely, the only noticeable project of this kind was one from Texas Instruments, which was stated to be pioneer in this field (as it can be seen in [15]). Despite that, sev- eral differences stands between this project and the present one. For instance: – USB communication: Texas Instruments developed its own Android driver, namely “virtual COM port”, so they could di- rectly connect their ZigBee Network Processor (ZNP) to the An- droid device through USB. Instead, Android USB host mode is used in this project in order to establish the connection be- tween the receiver and the device. Because of using this method, USB communication between MSP430 microcontroller and the Android device has to be specifically implemented and tuned. – Android platform: TI’s project employed Android 2.2, while version 3.1 is the one employed in this present project, due to the aforementioned need of USB host mode support this API provides. In addition, received data is used by this Android ap- plication, while TI employed ZigBee communication for less spe- cific ends, such as controlling other devices like PCs, lamps or obtaining data from certain sensors. – Wireless communication: in order that the ECG delineation could be done in real-time, this project does not use the com- plete ZigBee stack, but its 802.15.4 MAC layer. This restriction requires the radio –in particular, TI CC2420 radio module– has to be programmed specifically. Meanwhile, Texas Instruments made use of its TI CC2530 system on chip (SoC), which fully implemented ZigBee stack. – USB dongle: as it was mentioned before, TI directly plugged their ZNP to an OMAP4 Blaze thanks to their driver. However, so that the same result could be obtained, the radio, CC2420 module, had to be connected to the MSP430 board, namely the MSP-TS430PZ100USB, which was equipped with a USB inter- face. Furthermore, miniaturisation of this board was designed afterwards to make it an usable dongle. In other words, Texas Instruments’ project was actually able to build up working communications of this kind by the time ours was starting; all the same, special requirements like real-time needs entail additional Low-power Wireless ECG Monitoring System for Android Devices 9 Introduction challenges for this project to overcome. 1.4 Document overview This document presents the process involved in the realization of the project objectives. Discrimination of the hardware and the software parts of this process is mandatory, as the approach for each one, the applied methodolo- gies and techniques as well as the development processes, differ. The first chapter, this introduction, gives a global view of the project. A description of the project providing a detailed depiction of the objectives pursued, as well as the inspiration for it’s development and an exposition of technologies applied is elaborated in section 1.1 Project description. The motivation leading to the undertaking of such project is presented then, ex- plaining the reasons both from the project potential utilization and the aca- demic interest of the project points of view. This explanation is conducted in section 1.2 Project driver. The next section, section 1.3 presents the state of the art regarding the technological fields and technologies involved in the project. The chapter concludes with this overview of the document in sec- tion 1.4 Document overview. The research and development of the hardware part of the project in order to obtain the 802.15.4 USB receiver is presented in chapter 2, Hardware and Communications. It begins exposing the specific objectives pursued by this part of the project and providing an overview of the chapter in sec- tion 2.1, Introduction and section 2.2, Overview. A detailed description of the technologies employed in the hardware development process is then pro- vided in section 2.3, Technology Research. The specific process, methods and techniques applied in the hardware development are presented in sec- tion 2.4, Description. The remaining part of the chapter is devoted to the description of the actual research and development conducted throughout the whole project time. First, an explanation of the project schedule, as well as the specific circumstances which led to it being as it is, is provided in sec- tion 2.5, Milestones, followed by detailed exposition of the development of each stage of this schedule. The chapter concludes with the analyisis of the final hardware product and an exposition of the conclusions obtained during the process in section 2.6, Closure. The third chapter, Software Development, explains the process followed for 10 Low-power Wireless ECG Monitoring System for Android Devices Document overview the production of the Android application which acts as the ECG moni- toring front-end employing artifacts from structured software development methodologies so as to provide an in-depth view of the software part of the project. In section 3.1, Introduction and section 3.2, Overview a brief description of the software project and an explanation of the information contained in the scope of the chapter are presented. The identified require- ments for the project, both functional and non-functional, are presented in section 3.3, Requirements. In the next section, Risk Analysis, the importance of the risk management for this particular project is demonstrated and the identified risks exposed, including their evolution throughout the project development. The analysis process view concludes with the exposition of the use cases for the system in section 3.5, Use Cases. The Design and Ar- chitecture section presents the architectural view of the system, explaining design considerations and system modules in a comprehensive manner. The project development process is exposed in section 3.7, beginning with an explanation of the software project schedule which is followed by detailed descriptions of each of the project scheduled iterations, including risk evo- lution and use case realization related information. The chapter concludes with a review of the software project development in section 3.8, Closure. In the final chapter of this document a review of the project as a whole is conducted. First, the final state of the system is presented in section 4.1, Final state, detailing the accomplishment of each project objective so as to evaluate the project outcome. Taking the final state of the project as the starting point, potential further work lines are proposed in section 4.2, Po- tential additions and expansions. Finally, as a closure to both the document and the project, section 4.3, Findings explains the conclusions drawn from the development of the project. Three appendices are attached to this document. The first of these, Ap- pendix A, Budget Analysis presents an estimation of the cost of the project including performed tasks and scheduling in section A.1, as well as a Gantt chart for this scheduling in subsection A.1.2, Software project tasks. The total cost of the development is exposed in section A.2, Asset cost. Appendix B, Product Cost refers the cost of the production of both a single unit and a batch of ten thousand units of the receiver device, the latter as an estimation of the costs in a mass production scenario. Low-power Wireless ECG Monitoring System for Android Devices 11 Introduction The documents produced in the process of design and development of the receiver device are presented in Appendix C, Receiver Specification Docu- ments with enough detail to allow custom production of the device. The bill of materials, the device schematic and the printed circuit board design are also included. 12 Low-power Wireless ECG Monitoring System for Android Devices Chapter 2 Hardware and Communications 2.1 Introduction The hardware research and development part of the project objective is covering a main need: production of an external device that enables com- munication between an Android system and a Shimmer through 802.15.4. Such a device should be a portable and low-powered device that can be plugged via the widely used USB On-The-Go (USB OTG) to a host An- droid system, acting the device as a slave. It has to be small sized because of the target application environment: a par- ticular who requires constant, in-home, ambulatory monitorization. In that scenario unobtrusive operation is a main need, and usual life style activity modification is to be minimized. And it has to be low-powered, because were the power cost of application higher than that of the Bluetooth technology, a main advantage of 802.15.4 is lost. The ability to communicate through USB is required because, at the time, it is the most low battery consuming method to interact with Android pow- ered platforms for any external device. And finally it should be able to act as the slave in the USB connection to avoid the need of an extra power source for the device that would increase the cost and size of the product. 13 Hardware and Communications In order to achieve such goals, and being aware of the substancial amount of research involved in this part of the project, the decision is made to adopt a milestone driven development which simplified scheduling and helped fo- cusing on specific tasks while maintaining a global view of the evolution and the objectives of the project. 2.2 Overview Before diving any further into the development a section describing technolo- gies involved in the research process is presented, as such information will be key to the understanding of the rest of the chapter and will be throughoutly referenced during the exposition. Then a description of the hardware research and development process is given, followed by detailed explanation of each projected milestone, includ- ing objectives pursued, lines of research developed, results of each one and conclusions obtained. Estimation based decision making being crucial for the correct outcome of the project, special care will be put to explain the mo- tivations for each decision made. The chapter concludes with an exposition of the results of the research and subsequent development. 2.3 Technology Research This part of the project involves a lot of terms and references a number of technologies and concepts which are important to be acquainted with in order to achieve a full understanding of the current chapter. These expla- nations will not be presented interlaced with the rest of the sections due to the unmanageable size they would acquire leading to a loss of focus which can only act against full comprehension of the exposed content. 2.3.1 Google ADK & Arduino Android Open Accessory Development Kit, referred as “Google ADK” or “ADK” for now on, is a tool set which allows the development of accessories capable of interacting with Android-running devices. It consists of an Ar- duino board (particularly MegaADK, which is based on the ATmega2560 board) and a series of libraries for interacting with an optional set of hard- ware add-ons (“shields”). There are other compatible kits with different 14 Low-power Wireless ECG Monitoring System for Android Devices Technology Research boards, like NXP-based mbed [16], yet Arduino MegaADK is the one used here. The Google ADK functioning is actually very simple. Regarding the soft- ware, it requires the development of both an Android application with ac- cessory communication capabilities and the proper firmware of the board, which models the behaviour of the accessory. Once the board is flashed with its firmware, it has to be connected to a power source (through a dedicated wire or Type-B USB) and the Android device. If everything is correct, the latter detects the former and, therefore, the accessory starts its operation. Typically, the capabilities of the Arduino board are broaden with the addi- tion of extra shields, so that way it can make use of external sensors and agents. The board has multiple input and output pins at the developer’s disposal as well, so unforeseen behaviours can be achieved. 2.3.2 MSP430 MSP430 refers to an entire family of 16-bit CPU microcontrollers from Texas Instruments [17]. Its most relevant features are: • Very low power consumption: its several low-power modes make the MSP430 family specially suitable for developing embedded sys- tems. Moreover, its brief wakeup transitions from this operating modes are also noteworthy, since these lapses stay around the microsecond (µs) range. • RISC-based Architecture: its instruction set is particularly narrow [18], and thus simple. Reduced instruction sets ease programming when compared to complex ones, yet this advantage is not too decisive because of the reason presented next. • Simple programming: Most family members are programmable trough JTAG, which makes the debugging process less difficult along with the possibility of swapping assembly for C. • Wide support and resources: Texas Instruments provides code examples, software IDEs and thorough documentation as well as it offers extra development tools like training boards. Low-power Wireless ECG Monitoring System for Android Devices 15 Hardware and Communications However, it also suffers from some lacks. For instance, MSP430 devices are not equipped with an external memory bus, what makes flash memory and RAM extensions impossible. In particular, the MSP430F66xx family, which the device used within this project belongs to, is provided with only 128- 256KB of flash storage and 16KB of RAM –with an extra of 2KB whenever it is not using USB [20, p. 2]–. This amount of RAM may be too limited for certain usages (not for this project’s particular requirements, though). Concretely, the microcontrollers and boards used in this project are: • Microcontrollers: MSP430F5438A vs. MSP430F6638 Both of them are characterized by their low power consumption as well as their voltage range, from 1.8V to 3.6V. Although they share most of their specs, there are some points where they differ: 1. System Clock Frequency: in the case of the MSP430F5438A microcontroller it is up to 25MHz, whereas MSP430F6638’s clock only reaches 20MHz. 2. Wakeup time lapse: meanwhile TI claims MSP430F5438A wakes from standby mode in less than 5µs, MSP430F6638 needs less than 3µs. However, the most important difference lies in the USB support the second microcontroller provides, which is the reason why it was chosen for the accessory development. At any rate, full technical specification can be found at [19] and [20] for MSP430F5438A and MSP430F6638, respectively. • Boards: MSP-EXP430F5438 vs. MSP-TS430PZ100USB MSP-EXP430F5438 [21] is a prototyping board designed to make use of microcontrollers from the family of MSP430F5438 and stands out for featuring the following sensors and input/output elements: USB, JTAG, 5-position joystick, 2 push-buttons, dot-matrix LCD display, accelerometer... (full list of features in [21]). Furthermore, it also equips the CC2420, 2.4 GHz 802.15.4 radio module, which make this board specially convenient for this project’s requirements. This mod- ule is directly connected to the microcontroller allowing their com- munication through SPI. In addition, its USB connectivity provides a very useful serial output for debugging. 16 Low-power Wireless ECG Monitoring System for Android Devices Technology Research Nonetheless, despite the wide possibilities the previous board offers, the MSP-TS430PZ100USB [22] is selected. This board lacks serial port output and CC2420 compatible sockets, so the connection is to be done by hand and nor any of the other aforementioned artifacts available in the MSP-EXP430F5438 is present. But it provides the key feature required by the project: the ability to communicate the microprocessor with the board’s USB connector. 2.3.3 ShimmerTM Shimmer [23] is a trade name which refers to a wireless sensor platform designed to obtain, deal and wirelessly transmit human biological metrics and several ambient and kinematic measures. The whole system consists of the Shimmer platform itself and a series of extensible sensor modules as its hardware part, an open source firmware library and software development tools. After its proper firmware programming, the platform is capable of retriev- ing the aforementioned data thanks to its expansion modules [24] so that the user can manage it as considers. Once the data is appropriately dealt, the Shimmer is able to wirelessly send it via Bluetooth or 802.15.4 to other receiver nodes, which may be Shimmers or another compatible device. In order to carry out its tasks, the baseboard of the Shimmer is powered with a MSP430F1611 microprocessor as CPU, which belongs to the MSP430 mi- crocontroller family previously detailed. Additionally, the Shimmer is also equipped with Bluetooth and 802.15.4 radio modules which perform the data sending as well as several input/output devices and sensors –three LEDs, one push button, accelerometer and a microSD socket, among others–. Its usage is typically focused on healthcare or remote patient monitoring applications due to its small size and weight and its relatively low power consumption (which strongly depends on the employment its resources are given). In fact, the manufacturer itself refers to the Shimmer as “wear- able wireless sensor platform”. In addition, its multiple sensors allow many other applications like athlete performance monitoring or ambient sensing solutions. This sort of platform is employed at the ECG monitoring project [1] de- Low-power Wireless ECG Monitoring System for Android Devices 17 Hardware and Communications veloped by the EPFL and UCM which, conveniently adapted, performs as the emitter part of the present project. In particular, the system described within this document makes use of the 802.15.4 communication capabilities the Shimmer platform provides, which mean a key feature of this project. 2.3.4 802.15.4 The 802.15.4 standard [11] was first developed by the Institute of Electrical and Electronics Engineers (IEEE) in 2003, and was updated with succes- sive revisions in 2006 and 2011. This standard sets the specification for the physical layer and Medium Access Control (MAC) of low-rate wireless per- sonal area networks (LR-WPANs [11, p. 13]). This sort of networks, in the same way that affects WPANs, involves little or no infraestructure, fact that allows the implementation of inexpensive and power-efficient solutions for devices of different kinds, when compared to more end-user oriented wireless local area networks (WLANs). As said, this sort of WPANs are intended to be used when having limited power and relaxed throughput requirements (concretely, narrow bandwitdth need, up to 250kbps), as they aim for simple, easy-to-install short-range networks with little power consumption and low budget. To meet these objectives and requirements, the 802.15.4 standard makes use of one or more of the following unlicensed bands: • 868-868.6MHz in Europe. • 902-928MHz in North America. • 2400-2483.5MHz can be employed worldwide. Two kind of devices are considered within the standard: full-function (FFD) and reduced-function devices (RFD). FFDs are capable of communicating with both other FFDs and RFDs, whereas RFDs can only communicate with FFDs (RFDs are supposed to have very simple responsibilities, minimal re- sources and, consequently, send little amounts of data). These devices are to be arranged in peer-to-peer or star topologies. Concretely, devices in this project are arranged using a star topology where Shimmer emmiter nodes are RFDs which communicate with the receiver node FFD, the MSP430- based device connected to the Android tablet. 18 Low-power Wireless ECG Monitoring System for Android Devices Technology Research Regarding the MAC layer, it allows the usage of superframes instead of discrete frames. A superframe is bounded between two beacons sent by the FFD coordinator, which also defines the format of the superframe. The lapse between two consecutive beacons is equally divided into 16 slots, and may or may not be divide into an active and an inactive period, in which the coordinator may enter a low-power mode. Particularly, in this project, part of the superframe is divide into portions called guaranteed time slots (GTSs), which form the contention-free period (CFP) at the end of the superframe, after the contention access period (CAP), as it is represented in Figure 2.1. One GTS can use more than one slot, but the emitter device has to ensure that its transfer is completed before the end of its GTS or the CFP. Figure 2.1: Superframe structure with GTSs Further information and thorough details about the MAC layer and its frames and superframes possibilities and formats can be found at [11, p. 67]. Depending on the direction of the data flow and the usage of beacons or their absence, there are three modes of data transferring [11, p. 18], with addi- tional variants according to the possible requirement of transfer acknowl- edgement. In the case of this project, whenever a emitter device has data to transfer, it listens the network waiting for a beacon and, once found, it syn- chronizes with the superframe, sending its information in its corresponding GTS. This process is illustrated in Figure 2.2 (notice that, in this particular case, acknowledgment is not employed). Due to the possibility of entering low-power mode this standard provides during the lapse of CAP, it allows significant power saving. In Figure 2.3 and Figure 2.4 it can be seen that the Shimmer’s power consumption significantly drops after the receiving of the beacon. Two and three clearly different phases, respectively, can be observed in both figures: 1. Beacon Reception: first part, which lasts 1.39ms and averages 72.39mW, corresponds to the radio entering reception mode when the beacon is expected. Second part consists of the beacon reception itself, Low-power Wireless ECG Monitoring System for Android Devices 19 Hardware and Communications Figure 2.2: Communication to a coordinator in a beacon-enabled PAN and it lasts 0.97ms and averages 82.59mW. 2. Low-power mode: the radio keeps its power consumption to a min- imum until its GTS, if any packet is to be sent, or till the following beacon. In this stage, the consumption averages 6.6mW when both the microcontroller and the radio are idle, and 16.8mW when the mi- crocontroller is active updating the tick counter. 3. Packet transmission: (only in Figure 2.4) first part is due to the sending of the package from the microcontroller to the radio chip, which is still idle (16.8mW, 2.85ms). Second part corresponds to the actual transmission of the packet, which averages 51.92mW for 4.51ms. Oscillations, or peaks, can be observed during the entire process and are due to the continuous tick counter update (every 0.32ms) the operating system carries out. These results were obtained by measuring the voltage at a re- sistor which was specifically placed in the emitter node’s power path, as it is detailed in [7, p. 860]. These low-power periods grant a much better battery life when compared to the one Bluetooh, as the wireless alternative Shimmer provides, allows because of the constant user and protocol data flow that it causes, fact that is aggravated by its much broader bandwitdth. Thus, it provokes that the average Shimmer battery life employing 802.15.4 is more than one order of 20 Low-power Wireless ECG Monitoring System for Android Devices Technology Research Figure 2.3: Shimmer power consumption analysis, beacon reception Figure 2.4: Shimmer power consumption analysis, beacon reception and data transmission magnitude higher than employing Bluetooth. For instance, a fully loaded battery would increase its life from about 4 hours and a half to almost four days, which would be particularly interesting as it would let its replacement not to be a constant nuisance. These calculations come from a 280mAh Li-ion battery @ 3.7V powering the same Shimmer device sending the same data through Bluetooth (4.41h, 235mW) or 802.15.4 (89.17h, 11.63mW). Particularly, using 802.15.4, in a period of almost 1 second (980ms), the reception of one beacon along with the sending of 7 packages takes place, which only lasts for 53.44ms. Thus, the device stays in low-power mode for all the time left, 926.56ms. In other words, power consumption is at its minimum for the 94.95% of the time, as opposed to Bluetooth, which always keeps it at its highest value. Low-power Wireless ECG Monitoring System for Android Devices 21 Hardware and Communications 2.3.5 FreeRTOS FreeRTOS is a real-time operating system specifically designed for embed- ded devices, and has been ported to 31 different architectures hitherto. Due to its real-time nature, it features small sized binary images and memory footprint, real-time tasks and co-routines, as well as communication and syn- chronization tools for tasks and interrupts (queues, semaphores, mutexes). So as to achieve this real-time suitable condition, it is predominantly written in C and carefully coded in order to guarantee its portability and compati- bility with different compilers. This project makes use of FreeRTOS so that it manages the receiver device’s resources and handles the data reception and beacon sending of its radio as well as the USB communication with the Android device. However, despite the self-claimed compatibility with MSP430 architecture, the official port of FreeRTOS was not compatible with the microcontrollers employed in this project (specified at subsection 2.3.2, MSP430) at the beginning because it did not support the newer members of the MSP430 microcontroller family (although it currently does). Therefore, the operating system had to be accordingly modified and sub- sequently ported in order to support the target MSP430F5438A microcon- troller. This task was carried out by one member of the department, and consisted of adding support for extra peripheral devices, such as radio, serial port, USB and clocks, and adapting the intern management of interrupts and routines of the system. This process has been conducted outside of the project scope. 2.3.6 USB device & USB host USB host [25], as opposed to USB accessory, is an operation mode which determines how a USB-equipped device interacts with another one. The two connected devices are differently named according to the role they assume in a host or accessory mode connection, namely USB host and USB device. This designation is based on the role each device is playing rather than the sort it belongs to. In particular, one end is named USB host if its apparatus is responsible of supplying power to the one at the other end. In relation to this project, the main difference between both modes lies 22 Low-power Wireless ECG Monitoring System for Android Devices Description within the direction the power supply follows or, more specifically, the role the Android running device adopts: Android device acts as host in USB host mode, whereas it acts as device in accessory mode. However, there is no difference in data transfer between them, as it remains bidirectional in both modes. It is typical for the device with larger power consumption (usually the Android device) to act as the USB host since it probably has a power source of any kind, although this is not always this way. In addition, when a device acts in USB host mode, creating the connection, that is, instantiating and initializing the proper sockets, between both ends is its responsibility, along with notifying the other end about the establish- ment of the communication. On the other hand, the process that the device role assuming system has to carry out is quite simpler, as it just consists of checking the availability of the previously created communication. Regarding this project, this matter applies in the way both the Android and the receiver devices are connected and which one assumes the USB host role. It would result particularly desirable that the Android device acted as host so that the receiver could be fed from its battery (which would make the collection really portable, non-dependent on the accessory power source). However, it depends on the specific platform that this arrangement can be possible. Although certain Android devices running version 2.3 were capable of offer- ing USB host support, this version only officially supports USB accessory mode; whereas USB host mode is only available by default since version 3.1. Thus, in order to get the required behaviour the usage of one of this special devices or, preferably, a device running a 3.1 Android version or newer. 2.4 Description The hardware related investigation is the main section of the research part of the project. Not that there wasn’t any research involved in other areas, but some critical elements of this part had never been researched before. At the beginning of the project specific objectives were established and main milestones elected, but absolutely no clue or direction for most of those mile- stones was available. Moreover, in some cases the feasibility of the proposed goals was unknown. Specifically the achievement of the very important ob- jective of USB communication between an MSP430 and an Android powered Low-power Wireless ECG Monitoring System for Android Devices 23 Hardware and Communications device assuming the latter the role of master and acting the former as a slave was something not done before and therefore no information was available even in the Texas Instrument support site. This whole development and research poses some quite interesting challenges as it involves working nearly at every abstraction layer present on device development, ranging from schematic capture and PCB design to operating system related development. The main issues to be resolved are: • 802.15.4 radio reception: data packets are emitted from the mon- itoring ShimmerTMand are to be received and dealt by the accessory. In order to do so, FreeRTOS has to be equipped with a working im- plementation of the radio stack, which involves implementing part of ZigBee’s MAC layer, described by IEEE 802.15.4, as it is the underly- ing standard which the emitter nodes are based on. • MSP430 USB handling: just as the radio stack, FreeRTOS is not prepared to make use of the USB interface with which the MSP430 board –namely TS430PZ100USB– is equipped. Thus, it is necessary to add the essential code in order to incorporate this functionality to the OS. This issue, in the same way as the previous one, is a critical part for the system to work properly since it may likely be a source of errors unless it is perfectly made –for instance, it could add transmission lags, packet corruption or even full package losses–. • MSP430-Android communication: this issue is particularly rele- vant as no project has ever claimed to feature this kind of connection before. Hence, it means an additional challenge to be overcome since it will involve the modification or complete development of an specific driver for the MSP430-equipped device. This challenge is imposed by choosing the USB host alternative so that the Android device powers the accessory. On the other hand, USB device may ease this issue due to the already resolved communication system with accessories made by Google, yet it implies the accessory will need an additional power source. Fortunately, it finally turned out not to be so tough as it was expected and the goals related to this issue were successfully fulfilled, as it can be read at subsection 2.5.2, MSP430 for Android USB Host Comunication. Over the following lines within the next section, the aforementioned chal- lenges are detailed in the context of their own development stages. In addi- 24 Low-power Wireless ECG Monitoring System for Android Devices Milestones tion, objectives and results of each one of these stages are also presented. 2.5 Milestones Due to the fair amount of time a essentially researching work like this hard- ware development requires, the foreseen schedule is subject to changes which may completely alter it regardless of how irrelevant they may seem, and thus avoid the success of the project. Keeping this risk in mind, the hardware development is planned as a se- quence of milestones, ordered by increasing complexity. Every milestone introduces a new technology, each one of them capable of covering the needs of the project in a more complete way. In other words, the previously pre- sented issues are to be resolved as these stages are overcome. The schedule, then, starts with the usage of the Google Open Accessory Development Kit, based on Arduino, in order to make a prototype as first approach and, in this way, be able to parallelize software and hardware de- velopment –notice that both of them depend on each other–. This choice is made because of the well-known soft learning curve Arduino presents as well as the already prepared connection the Google ADK provides between accessories and Android devices. The next step in the development, once the application has been proven to communicate with a data-providing accessory, consists of making Android capable of detecting and communicate via USB with an MSP430-equipped device. This stage can be qualified as very critical, since almost every part of the development depends on it. The following milestone arises as a consequence of the FreeRTOS port which was specified before: its target device, namely MSP430F5438A, does not support USB communication, and by extension the port itself. Thus, the work for this stage consists of providing FreeRTOS with USB support, which is to be employed with the new target device, MSP430F6638, which is mem- ber of the MSP430F66xx family with highest performance, along with USB support. Next, the planning sets the development of the communication between the emitter nodes and the device. The previously existing FreeRTOS port al- Low-power Wireless ECG Monitoring System for Android Devices 25 Hardware and Communications ready supports the IEEE 802.15.4 standard MAC layer, so the work in this milestone involves modifications in order to get the port to work properly with the new MSP430F6638 platform. Although the first versions of the schedule considered this next step at the same time of the previous one, in later revisions it was decided to keep them separated for the sake of the stability derived from isolating both developments. Due to the division between the two previous stages,