Full text
Author: César Godino Rodríguez Director: José Ignacio Hidalgo Pérez Final project for the Degree in Computer Science, Facultad de Informática, Universidad Complutense de Madrid Trabajo de fin de grado del Grado en Ingeniería Informática, Facultad de Informática, Universidad Complutense de Madrid Academic year: 2020/21 - June 2021
Index Abstract 3 Key words 4 1. Introduction 5 1.1 Goals 9 1.1.1 Main goals 9 1.1.2 Specific goals 9 1.2 A note of gratitude 10 2. State of the art apps to assist people suffering from diabetes 12 2.1 FreeStyle LibreLink 13 2.2 LinkBluCon 14 2.3 SocialDiabetes 15 2.4 glUCModel 1.0 16 2.5 Conclusions and motivation 17 3. glUCModel 2.0 18 3.1 Tools, sources and technology involved 19 3.2 General map of views 20 3.3 Functionalities per view (iOS) 22 3.3.1 Launch screen 22 3.3.2 Health permissions form 23 3.3.3 Login view 24 3.3.4 Sign up view 25 3.3.5 Information view 26 3.3.6 “Forgot your password?” view 27 3.3.7 “My glucose” view 29 3.3.8 “Upload data” view 33 3.3.9 “Prediction” view 35 3.3.10 “Settings” view 39 3.4 Functionalities per view (WatchOS) 53 3.4.1 Launch view 54 3.4.2 Login view 55 3.4.3 “My glucose” view 56 3.4.4 “Upload Health data” view 58 3.4.5 “Glucose prediction” view 59 3.4.6 “iPhone connectivity / Settings / About” view 61 4. Case of use 62 4.1 State of the app and the database before uploading new health data 63 4.2 State of the app and the database after uploading new health data 65 5. Conclusions and future goals 72 5.1 Challenges overcome 76 Bibliography 78 2
Abstract In this project, we have developed a new iOS and WatchOS version of glUCModel, a platform for diabetes and related data management. The main purpose is allowing its users to upload their health data samples to an external database[1] in order to further develop predictive models for blood glucose levels and keep such models updated, learning to improve themselves. Health data samples will be measured and obtained through smart devices, will be stored directly on the iPhone's Health app and, eventually, with beforehand explicit permission from the users, our app will process such samples to store them in the glUCModel external database. Users will be able to make use of pretrained models by requesting an estimate of their blood glucose levels, while being able at the same time to choose a model which feels more convenient to them at the time. Moreover, users will be able to monitor their blood glucose level by reading their samples from the same database, keeping track of its evolution throughout the last 24 hours along with the pertinent calculations to assure they are up to date with the current state of their glycemia every time they need it. Resumen En este trabajo, se han desarrollado versiones para iOS y WatchOS de glUCModel, una plataforma para la gestión de la diabetes y datos relacionados con ella. El principal objetivo es el de permitir a sus usuarios subir sus muestras de datos de salud a una base de datos externa para poder avanzar en el desarrollo de modelos de predicción de niveles de glucosa en sangre y mantener dichos modelos actualizados y aprendiendo a mejorarse a sí mismos. Las muestras de datos de salud serán medidas y recogidas a través de dispositivos inteligentes, almacenadas directamente en la app de Salud del iPhone y, finalmente, con previo permiso explícito por parte de los usuarios, nuestra app procesará dichas muestras para almacenarlas en la base de datos externa de glUCModel. Los usuarios podrán hacer uso de modelos previamente entrenados al solicitar una estimación de su nivel de glucosa en sangre, pudiendo a la vez elegir un modelo que les parezca más conveniente en el momento. Además, los usuarios podrán observar sus niveles de glucosa en sangre al leer sus muestras desde la misma base de datos, pudiendo realizar un seguimiento de su evolución durante las últimas 24 horas junto a los cálculos pertinentes para asegurar que puedan están al día con el estado actual de sus glucemias cada vez que lo necesiten. Key words Glucose, smart devices, health, Swift, iOS, WatchOS, glUCModel, predictive model, Artificial Intelligence, database. 3
Palabras clave Glucosa, dispositivos inteligentes, salud, Swift, iOS, WatchOS, glUCModel, modelo de predicción, Inteligencia Artificial, base de datos. 4
1. Introduction Diabetes[2] is a set of diseases whose symptoms mainly consist of high levels of blood glucose as a result of the pancreas inability to produce enough insulin (or any, at all) or the insulin not acting properly in the human body. To this day, according to the World Health Organization[3], about 422 million people worldwide suffer from diabetes, 10% among them being Type 1 diabetics who rely, mostly, on insulin shots. This type of diabetes is known for the pancreas’ beta cells not producing insulin, which usually starts at a young age, especially around the teen years. And then there is Type 2 Diabetes, which starts manifesting around the age of 50 onwards. Among its main sources are obesity and a sedentary lifestyle and, as a consequence of these, the body progressively builds up a resistance to insulin in a way that it no longer works in a proper manner, which ultimately leads to an imbalance in the blood glucose levels. The excessive amount of glucose in the blood for long periods of time leads to it piling up on the nerves and its crystallization, thereby affecting the organs and hence causing their fast deterioration and leading to heart diseases, limb amputations and sight and kidney problems. On the other hand of this imbalance, a very low level of glucose can lead to loss of conscience, diabetic coma and the death of the patient. Nowadays, due to the progress of modern technology, the monitoring of our health has improved to a whole new level, to the point in which we can rely on smart devices to do this automatically for us on a seamless daily basis. All it takes is having the proper device for whatever we would like to keep an eye on. Such new devices, as Fitbit and Apple Watch, keep track of a wide set of our vital signals with a very high precision, and arrange those sets of information in such a way that it is easy for us to take a quick peek at our statistics in the last few hours or days. Even though this information is processed for us for a good understanding and use of it, this being the case of iOS’ Health lately, it is usually always left for the user or a third-party app to give it a more specific treatment. Here is where we can step in to take a software-based approach towards the glucose levels matter. From the moment that our health data samples meet automatization through software, we aim to achieve the goal to help people suffering from diabetes through the development and use of predictive models. These adaptive systems are being developed within the HERACLES-II project. The predictive models are based on neural networks assembled systems, and its purpose is to make it easier for the patients using it to keep their glucose levels in check and inside a healthy range by the proactive use of such models. In order for the models to offer a better estimate, users must upload their health data samples 5
(as a sort of a two-way feedback). Also, the more variety of data the user chooses to share, the more variety of models will be able to be developed in the near future too, through AI and neural networks. In the context of this project, previous work had already been laid out with the models and the outlined idea of getting and uploading users’ data samples from the Health app[4], so this app serves as another piece of the puzzle, from which now both parts will complement each other. Through glUCModel’s iOS and WatchOS app and its web version[5], every user will be able to upload their health data samples, whilst the models are being hosted on Glucnet. Introducción La diabetes es un conjunto de enfermedades cuyos síntomas consisten principalmente en elevados niveles de glucosa en sangre como resultado de la incapacidad del páncreas para producir suficiente insulina (o nada en absoluto) o de que la insulina no no actúe de forma correcta en el cuerpo. A día de hoy, según la Organización Mundial de la Salud, alrededor de 422 millones de personas en el mundo padecen diabetes, teniendo el 10% de éstas diabetes de Tipo 1, con la que dependen la mayoría de las veces de dosis de insulina. Este tipo de diabetes se caracteriza por la carencia de producción de insulina por parte de las células beta del páncreas, lo cual suele darse a edades tempranas, especialmente durante la adolescencia. Y después tenemos la diabetes Tipo 2, cuyos síntomas empiezan a manifestarse alrededor de los 50 años en adelante. Entre sus principales causas están la obesidad y el sedentarismo y, como consecuencia de estos, el cuerpo va desarrollando resistencia a la insulina de forma que ésta ya no puede actuar adecuadamente, lo que finalmente conduce a un desequilibrio en los niveles de glucosa en sangre. Una cantidad excesiva de glucosa en la sangre durante prolongados periodos de tiempo hace que dicha glucosa se acumule en los nervios y se cristalice, afectando por tanto a los órganos, causando un rápido deterioro y causando enfermedades cardiovasculares, amputación de miembros y problemas oculares y renales. Mirando al otro extremo de este desequilibrio, unos niveles muy bajos de glucosa pueden provocar la pérdida de conciencia, un coma diabético y finalmente la muerte del paciente. Hoy en día, gracias al avance de la tecnología moderna, el llevar un seguimiento de nuestra salud ha mejorado con creces, hasta el punto en que podemos dejar que los dispositivos inteligentes hagan esto por nosotros automáticamente de forma diaria e ininterrumpida. Todo lo que hace falta es tener a mano el dispositivo apropiado para aquello que quisiésemos monitorizar. Estos dispositivos modernos, como los de Fitbit y los Apple Watch, llevan un registro de 6
una amplia variedad de nuestras constantes vitales con una alta precisión, y organizan esas cantidades de información de manera que nos resulte sencillo echar un vistazo rápido a nuestros datos de las últimas horas o días. Aunque este tipo de información se nos da procesada para que podamos comprenderla con claridad y darle uso, como es el caso de la app de Salud en iOS recientemente, por lo general terminan siendo los usuarios o una app de terceros los que deberán darle un uso más concreto. Es aquí donde nosotros podemos establecer un punto de partida para tratar el problema de los niveles de glucosa en sangre a través del software. Desde el momento en que nuestras muestras de datos de salud se ven automatizadas por software, pretendemos lograr el objetivo de ayudar a las personas que padecen diabetes mediante el desarrollo y uso de modelos de predicción. Estos sistemas adaptativos se están desarrollando dentro del proyecto HERACLES-II. Los modelos de predicción están basados en sistemas ensamblados de redes neuronales, y su objetivo es el de facilitar a los pacientes que los emplean el mantener a raya sus niveles de glucosa y en un intervalo saludable gracias al uso proactivo de dichos modelos. Para que los modelos puedan ofrecer una mejor estimación, los usuarios deben subir muestras de sus datos de salud (a modo de una retroalimentación bidireccional). Además, cuantos más tipos de categorías de datos quieran aportar los usuarios, más variedad de modelos se podrán desarrollar en el futuro cercano también, a través de la Inteligencia Artificial y las redes neuronales. En el ámbito de este proyecto, ya se cuenta con trabajo previamente realizado en cuanto a los modelos y la idea ya perfilada de recuperar y subir las muestras de datos de salud de los usuarios desde la app de Salud, por lo que la app actuará como una pieza más del puzle, y con lo cual, ahora ambas partes podrán complementarse entre sí. Mediante la versión web y la app de iOS y WatchOS para glUCModel, cada usuario podrá subir sus muestras de datos de salud, mientras que por otro lado los modelos estarán alojados en Glucnet. 7
1.1 Goals 1.1.1 Main goals The main goal of this project is developing an app for iOS and WatchOS that allows users to connect to an external database to perform several functionalities, such as: uploading their chosen health data, requesting an estimate of their blood glucose level on a close point in time from the AI predictive models and monitor their recent statistics on their blood glucose samples. To achieve these, we set out to undertake the following specific goals. 1.1.2 Specific goals ● Develop a versatile, user friendly and easy-to-use app for iPhone devices for patients to use their glUCModel accounts with. ● Develop a WatchOS version for glUCModel, with most of the iOS version functionalities, so that users can optionally use it more quickly and comfortably[6]. ● Give users a way to automatically get their health data samples from the iOS native Health, process them and upload them to glUCModel’s database. ● Show users their most recent glucose level samples in a detailed view along with their associated calculations to keep track of the state of their glycemia in the last available 24 hours. ● Provide users with an interface which will let them choose and make use of glUCModel’s predictive models. ● Create a view for users to check and manage their profile information so that they can provide more optional medical data to further improve the monitoring of their glucose and the estimated results of the models. ● Allow users to manage their account through the closing of their session, changing of their password or deleting their accounts to cease their participation with glUCModel. 8
1.2 A note of gratitude Before going deeper into the project, I would like to thank the ABSys research group for providing the models used in the prediction requests inside the app, and also the access to their server and database, so that I could join all of them to the app throughout its development. This app is also part of their major HERACLES-II project, thereby being part of a research framework funded by Ministeriod de Economía y Competitividad of Spain, under grant RTI2018-095180-B-I00, Eugenio Rodriguez Pascual Foundation, Madrid Regional Government and FEDER funds, under grants 2017/BMD3773(GenObIA-CM) and Y2018NMT- 4668 Micro-Stress-MAP-CM. 9
2.5 Conclusions and motivation After taking a look at the current state of the art, we can conclude that there are already some apps for iPhone and Apple Watch with similar functionalities and goals to the project for this report. Here is a list of reasons that motivated the need for the development of this project: ● Most apps for diabetes management are usually proprietary. ● Those apps which are not owned by the same companies that provide the sensors, glucose registers and insulin pumps come from particulars, and do not provide the reading and exporting of the data samples straight to an external database, and neither do they allow a more flexible use of such samples or their sharing. ● Apps that allow the exporting or sharing of the read samples do charge patients for the functionality. Still, the app developed in this project covers a feature which is not present in the other mentioned apps and it is what has led to the development of the glUCModel app for iPhone and Apple Watch: giving users an automatic way to provide the predictive models for blood glucose levels with their health data samples by processing and uploading them to an external database, thus making possible the further development and training of those models and making use of them. It is important to emphasize the need for us to have an app which joins the use of glUCModel, the models from Glucnet and the measuring from smart devices together, in a way that serves as a nexus point for the three of them with users. There is also the need for flexibility on the health data samples management, in terms of their processing after their retrieval, uploading or querying them from the database depending on the use we would like to make of them. Still, there will be much further developing work to do in the near future concerning the overall glUCModel system to keep improving and expanding it. 16
3. glUCModel 2.0 Since both iPhone and Apple Watch devices, in their recent iterations over the last few years, are able to provide users swiftly with health data of their everyday activities, an app for both of these devices seemed like the most obvious choice to start our path towards data collection, given especially how fairly easy it is to retrieve it from the iOS native Health app. For users to use this app is not strictly necessary, at all, to own an Apple Watch, since the latter’s main purpose in this is to provide the Health app with more health data. Users can still provide their data through other devices or by manually submitting it to the Health app. The reason why the counterpart WatchOS extension was developed alongside the main iOS app was because both share the very same programming language, Swift, and that way we can give users an optional and easier-to-use simplified version of the app that they can comfortably manage from their wrist in a matter of seconds with a couple of taps. Here is a quick summary of the main functionalities, in the developed app for this project, that we will be getting some insight into later: ● As every user will be connected to glUCModel’s database with their own account, they will be able to access their most relevant stored type of data: blood glucose. The app will display for them the information on their glucose from the last 24 hours in a way that they can inspect every sample, see its quantity, when it was taken and, according to their own health preferences, how this sample was qualified, and how close they might be to any risk level of hypoglycemia. ● With just a single tap of a button, users will check if there are any new health data samples in the Health app since they last uploaded them (taking first into consideration what was stored in the database to keep consistency) and then those will be processed in order to be uploaded to a then-updated database. ● Users will be able to make use of the available predictive models in Glucnet through the app. For every estimate request, they will need to have a form filled where they choose their convenient preferences, the model and their time horizon for the result. Now, let us delve deeper into the app for iOS and WatchOS: the tools used for its development, the maps of the views, its navigation and a detailed insight into the several functionalities each of them offer to the users. 17
3.1 Tools, sources and technology involved The main languages used for this project are Swift[11] on the iOS and WatchOS apps, PHP as a connection[12] between Swift and the database, and MySQL will be the language for the queries addressed to the database. At the moment of the completion and delivery of this project, the app is working through Apple’s flagship programming language’s latest release, Swift 5.4.1, building it on Xcode 12.5 for iOS 14.5.1 and WatchOS 7.5, all running and simulated initially on macOS Big Sur (11.4). PHP on the server side is working on version 8.0, the same as MySQL. Connections and development to the server side were made through SSH on macOS’ Terminal, and access and testing on the server’s database were performed through a phpMyAdmin online interface. The digital sources and material from which I have been able to learn Swift and the use of Xcode from scratch, or by specific cases of use[13] and provided code examples, are two of the books[14][15] by members from the RayWenderlich.com team, a YouTube channel specialized on iOS and Android coding[16] and two online courses[17][18] on the Udemy platform. The development and testing of the running app has been carried out on physical Apple devices, specifically on an iPhone X and an Apple Watch 5 (44mm). 18
3.2 General map of views Since the moment a new project is started from scratch on Xcode, the environment provides us with a blank storyboard which will serve as a desk for us to lay, edit and connect all the views we would like for our project to work with. Here are the storyboards with all the views included on glUCModel 2.0 for iOS and WatchOS: Full storyboard map of views for glUCModel on iOS 19
Full storyboard map of views for glUCModel on WatchOS While some of the views look odd or even incomplete in their initial state, this is because the storyboard settings do not always cover all the need of initial settings we may have to adjust for the visual look of the objects displayed, and it is up to us to polish those programmatically, in the first function of controller associated to each view, right before the view is ready to be loaded. Moreover, the iPhone version shows the light mode view as default, but the app is compatible with iOS’ dark mode, which is the mode we will be seeing enabled when reviewing every part of the app. 20
3.3 Functionalities per view (iOS) All the following screenshots were taken directly from an actual iPhone X device instead of the simulators provided by Xcode. 3.3.1 Launch screen This screen will be brought up, by default, each time the users are launching the app for the first time, after closing it through the multitask bar or after a period of inactivity in which the system decided to put it on hold and send it to a background mode along with other inactive apps. This view can also be programmed to redirect the users wherever they need to go based on if they were actually logged in or stayed in the login view. 21
3.3.2 Health permissions form This view, per se, is not presented by the app, but is rather presented by iOS after the app asks the system for it. This form will only be presented to the users once, after the launch screen fades out, on the very first time the app has been launched after being downloaded from the App Store. Its purpose is to ask users for their permission on which types of data from the Health app they wish for glUCModel to read from or write to. Be it reading or writing data, two messages are included so we can explain to them why and what we want their health data for. And since this form cannot be displayed more than once inside the app, users are told as well how to revisit these permissions inside the iOS Health app or the Settings app, in case they wish to grant or deny access to different types of data later in the future. 22
3.3.3 Login view After the launch screen, and assuming it is the first time opening the app or the user has not logged in yet, the screen will show a brief blur transition effect that ends up showing the login view. This will serve as a point where users can log in with their account, or switch accounts in case they were to have more than one. This also serves as a point where the user may seek for more help or information in case they would not know how to follow up. 23
3.3.4 Sign up view If the users tap the “Sign up” (“Registrarse”) button they will be prompted to a modal view with instructions on how to get an account created for them. Since glUCModel is not available to everyone yet, patients will have to check with their doctors or glUCModel personnel in order to have an account opened. If they would like to get in touch with glUCModel’s personnel, they tap on the email address and they will be prompted again to the system’s native Mail app from which they will write the email with the beforehand specified information. 24
3.3.5 Information view If users tap on the rounded information button, they will be prompted to a modal view which is an in-app browser whose default page is glUCModel’s website. That way, users can gather more information if needed, and also focus better on the text displayed if they tap on the magnifying-glass icon next to the exit icon. In this “reader” mode, they will also be able to copy the URL of the website, share it or even open it on Safari (or the default browser set in their current device). 25
whenever the users tap the button again, as seen in the fourth screenshot, if there is no new data to be read from the Health app, they will be told so. 32
3.3.9 “Prediction” view This view will allow the users to request an estimated level of their blood glucose in a near point in time, from the health data they have previously uploaded to glUCModel’s database and through predictive models. It basically consists of a short form of settings which users can edit in order to configure the model and data they would like to use for their upcoming prediction. Additionally, users can choose for the app to remember their current chosen settings for future requests, so that they do not have to go through them again. Plus, since this view for the Apple Watch version will be simplified, here they can already choose their options for the Watch to work with later. For our application we have adapted a model obtained following previous work of ABSys research group. In particular we include a neural network developed with Python, which takes as parameters the value of the time horizon for the estimated result and the most recent 25 values of the sample types depending on the selected model. 33
Filling in the form is quite easy since, for every row, the users will be given a “picker” with a limited number of choices. As seen in the first screenshot, there are 2 types of predictive models to choose from, the personal and the general ones. We could say that the personal model is bespoke, since it will take into account only what has been learned about the user asking for an estimated blood glucose, while the general one grows from data from every user who has been uploading their health data to glUCModel. As seen in the second screenshot, the samples for the prediction do not really have to be previously uploaded to the database, but users can actually choose to enter certain types of samples manually. The form works dynamically, so if users choose to provide their samples manually, the third row will be switched for another one that will allow them to enter said data, as seen in the last screenshot. 34
The three types of measures users can manually enter through pickers are glucose, bolus insulin and carbohydrates. The number of manual samples they can provide is discrete, so for each type they will be provided with a specific range of values and, as they enter them, a count will be shown above the current row in the form to let them know when they are finished. 35
Finally, the time horizon will determine how far ahead in time the users would like to place the estimated glucose level. They can request an estimated level for the current moment or for a maximum of 2 hours ahead. As seen in the second screenshot, for every single request users make, a warning message will be displayed, basically encouraging them not to make any important decisions based on the results of the prediction, since it is still a work in progress and not coming directly from a specialised doctor. The third screenshot shows how the result will be displayed every time the request is complete. It will tell the chosen time horizon, and so the target hour to make it more accessible, and then the level of glucose in mg/dL. In this case, the user chose to get the heart rate samples from the database, and since only a handful of those recent samples are needed for the model (25, to be precise), the app will show the range of dates belonging to the first and last of those used samples. If chosen to enter the samples manually, the result will end in the estimated glucose level. Users can repeat this request, and change its settings, as many times as they feel like in order to try and test the models. 36
3.3.10 “Settings” view The last of the four main sections in the app is the view for the Settings. These are grouped into three sections: account management, use preferences and more information. Let us get more into each of the different sections or functionalities for every row. 37
3.3.10.1 Profile data The last of the four main sections in the app is the view for the Settings. It is divided into 2 sections: personal data and medical data. Users can use this section to review the data in their profiles, also to add, edit or remove almost anything they would like, since all the data in the profile is entirely optional. By tapping “Edit” on the upper right corner of the view, all the editable rows from the form will get slightly bigger with a more transparent colour so that users know what they can work with. They will of course be able to cancel or save new changes at any moment. 38
3.3.10.2 Change password Users can change their password if they wish so. First, they will have to enter their original current password, which will be checked through the very same process as the login. In case users forgot their password, they can tap on the user with a question mark icon and a modal view (just like in the log in) will be shown with the instructions to get a new password. If the correct current password was entered, the user will proceed to the final step for setting a new one. 39
Users will have to enter the new password twice to confirm it. For security reasons, the new password will always need to conform to a minimum number of requirements, which the user can check by tapping on the underlined text saying so. Since this may be a tedious process for users, as they are coming up with a new password and manually typing it down in the text field they can bring up the requirements view as much as they need to to check how the entered password so far currently matches the requirements. Also, as typing a new and secure password may cause for some of the entered characters to miss the eye, users will be able to reveal the dot-covered character string by tapping on the eye icon beside the first text field. When all the requirements are green-checked in the list and repeated in the second text field correctly, users will only have to tap on the “Set new password” (“Establecer nueva contraseña”) button and confirm they do wish to set the new one. 40
3.3.10.3 Delete account Users who would like their participation with glUCModel to cease can delete their account from the app at any time. They will be first warned that, after deleting their account, they will no longer have access to it, plus all personal data will be deleted from the database, except for all the medical data and all the samples collected during their time using the app. In other words, their accounts are not really deleted, but their personal data is deleted from the database and their password is changed, in a way that the account is completely anonymized. This process is very similar to the login and the setting of a new password. Users will have to enter their current password first in order to confirm they want to proceed with the deleting. After confirming the current password, a red coloured button will take the place of the text field. After tapping it, they will be asked one last time if they really want to delete their account. If so, the server will apply the changes mentioned above and, right after that, the app will redirect the users to the login view, while deleting as well, from the phone’s storage, all personal data that the app would have had to save during the time the users were using it (such as last read glucose samples and their profile data). 41
3.3.10.8 Contact Even though users can start writing an email to glUCModel in case they would like to create an account or forgot their passwords, here they can also access the same email sheet view to contact the team for any reason they would like to. The screenshot shows a message suggesting the users what they possibly would like to write the team about. 48
3.3.10.9 Rate on App Store By tapping the row for this option, users will be redirected to this form on the App Store app, by which they can leave a score out of 5 stars along with a message, in order to help the app and its development to keep improving, fixing possible bugs and adding new features. Since the glUCModel app is not currently available to download from the App Store, this feature has been added as a sort of a placeholder, meaning that we will be redirected to rate the Complutense University official app instead, for now. This will eventually be substituted for the actual page of the glUCModel app once it has been officially released on the App Store. 49
3.3.10.9 About This view will always tell the users which version of the app they currently have installed on their iPhone, as well as the name of the people and entities involved in its development. 50
3.4 Functionalities per view (WatchOS) All the following screenshots were taken directly from an actual Apple Watch 5 (44mm) device instead of the simulators provided by Xcode. As Xcode itself describes it, the WatchOS version for glUCModel is nothing more than an “extension” of the main iOS version. Even though this version could have been made in a way that could work independently from the iOS version, it would be more tedious keeping them both synced. Besides, we need to keep in mind that, to this day, Apple Watch devices still have a battery which, luckily, may last a bit longer than 24 hours depending on the use people give to it during the day. The WatchOS version has been made to work in a way that is completely dependent on the iPhone, meaning that, to use it properly, the iPhone must be switched on and nearby, with glUCModel installed on it, with an account logged in and any sort of connection to the Internet available. The WatchOS version will mostly execute code regarding the visual elements on its views and the connectivity to the iPhone to exchange information. The WatchOS version consists of 4 main views, displayed in a horizontal navigation style, which can perform most of the same tasks the iOS version does, but still, it will simply reach out to the iPhone asking it to perform those tasks. This way, the latter does most of the work and then sends the results back to the Watch to display them. With that said, let us take a look at the view and functionalities of glUCModel for WatchOS. 51
3.4.1 Launch view Just like in the iOS version, this is the first thing users will see when they open the app on their Watch for the first time, or after some period of inactivity in which it has not been opened for a while. 52
3.4.2 Login view The login process on the WatchOS version will be much simpler than on the iOS version. Users do not have to enter their IDs nor passwords whatsoever using the tiny screen interface that the Watch provides to type. They only have to make sure their iPhone is nearby and with their session already open in the main glUCModel app. Then they will have to tap the “Done!” (“¡Hecho!”) button. The Watch will ask the iPhone app if there is already any session open, and it will reply with an answer. If the process is completed successfully, the users will be redirected to the main of the four views that make this app. After users have logged in, if they were to log out at any time from the iPhone app, the latter will send a message to the Watch app which will result in the closing of the session there as well, informing the user on the Watch that the session was closed on the iPhone. 53
3.4.3 “My glucose” view In a similar way as when users first log in on the iPhone app, the “My glucose” view will have no glucosa data loaded yet, and so there will be no calculations made, nor any percentages and nothing drawn on the graph. If users tap the button that reads “More information” (“Más información”) at the bottom of the view, the graph will show a new layer saying there are no samples, plus a paragraph below the graph that will explain them (in the very same way as in the iPhone app) how their glucose data will be loaded and managed. Lastly, they will be told how to make an update, which this time is done slightly differently than on the iPhone version. As seen in the first screenshot, users can tap on the first row at the top of the view, which can both reveal or hide an “Update” (“Actualizar”) button on top of it. After tapping it, the button will briefly read “Updating...” (“Actualizando...”) while the Watch is asking the iPhone app to perform the actual update. 54
Right after finishing the update, the Watch will store the results sent from the iPhone (stored there as well to keep them synced) and work on the view elements to update what is shown to the users, including the drawing of the graph. As seen in the first screenshot, users will now see all the recent available data in the view (which should be exactly the same if they were to check their iPhone after the update from the Watch). The rest of the view will work in the same way for the users as it did on the iPhone’s version. Users can tap on the coloured bar to display or hide a more detailed panel of the percentages calculated for every range of their glucose samples, as seen in the second screenshot. Regarding the graph, it will be drawn and coloured using the same axes, data and colours as on the iPhone app. Users can tap on the left or right half of the graph in order to inspect the samples a bit more, which will display the date of the sample and its quantity in mg/dL. If they would now like to know how many samples have been retrieved from the last available 24 hours, all they have to do is tap the “More information” button again and the graph’s upper layer will show the current count again. 55
3.4.4 “Upload Health data” view This view will work the exact same way as its version on the iPhone app. All users have to do in order to upload their latest Health data is tap the rounded white button. This will start spinning around as seen in the second screenshot, while the Watch is asking the iPhone to start the actual retrieving, processing and uploading of the samples in the Health app. If there were any samples to upload, once the iPhone has completed the uploading to the database successfully, it will send a message to the Watch informing of its success and the date when it was performed, as seen on the first screenshot of the second row. On the other hand, if no new samples were available to retrieve in the Health app, users will see (as on the iPhone version) a message that reads “No new data found to upload” (“No había datos nuevos a subir”). In any case, every time users return to this screen after at least one successful upload process, they will be shown when it was the last time they actually uploaded something to the database. 56
3.4.5 “Glucose prediction” view The “glucose prediction” view is a much simplified version than the one on the iPhone app, since we did not want the user having to deal with many settings on such a small screen. That is why almost all of the options chosen for the prediction on the Watch must be set beforehand on the corresponding view on the iPhone app. As seen in the first screenshot, the only thing users will have to set, if needed, before requesting a prediction is setting the time horizon for the result, starting from “Right now” (0 minutes) to a maximum of 120 minutes. After tapping the button that reads “Request” (“Solicitar”), the screen will swiftly dissolve into a new layer informing that the iPhone is requesting a result. In the second screenshot, we see how a result is displayed. Just as the iPhone version does, it will show users the hour the result has been predicted for, 57
64
Now I will check my new glucose from the app and we will see how the data in the graph and the calculations have changed since the last update (without new data). As we can see, due to an increase of new samples catalogued as hypoglycemia, a new color representing its corresponding percentage has appeared in the bar, and also has become the lower color of the gradient in the graph, meaning that the lowest sample (at least one) among the total was catalogued as hypoglycemia. We can also appreciate that now there are 194 samples instead of the 178 available before the update. 65
And right afterwards, if we request a new prediction based on the recent glucose levels, the range of the read samples for the prediction will show that it is indeed taking into account the new ones, compared to the last glucose-based prediction. 66
Now let us finish with the heart rate samples. The Apple Watch I have been wearing for about 3 hours has already measured enough new samples to show how they will be processed. These are the last samples my Health app reflected as available. I am about to collect, process and upload them, and we will also see how they are indeed stored in the database and how, after another attempt at uploading new data, the app will tell me there is no new data available to collect for now. So, according to our app and the Health app, there should be plenty of recent heart rate samples available now on the database, so we will take a look at my current user’s samples in the corresponding table. 67
The new heart rate samples measured by the Apple Watch have been indeed uploaded to the database and are available in their table. Note that the table will show both the real timestamp of every sample as well as its processed timestamp, because through the process before the upload we make sure that the samples are compartmentalized in segments of a minimum of 5 minutes, as we saw earlier in the functionality for the “uploading health data” view. 68
Finally, let us try a new request for heart-rate-based prediction. As we can see, the prediction result and its range of read samples are now different, for it has taken into account the most recent found heart rate samples in the database. 69
5. Conclusions and future goals All the main goals set at the beginning of the project were accomplished, given that we managed to retrieve the health data samples measured by the Apple Watch, process and upload them to glUCModel’s database, and use them right afterwards to request a glucose prediction, be it from the Watch or from the very own iPhone. Users can also keep track, with a simple tactile gesture, of their latest glucose samples after they have been uploaded to the database as well, while getting more insight into their stats, possible risks and percentages of said samples. As this new version of the app for iOS and WatchOS was developed completely from scratch and at the same time the database was being readjusted and the predictive models polished, there were some features that could not be completed nor included. For example, converting the mg/dL units to mmol/L for every view. The most important goal we are aiming for in the future is incorporating many more types of health data, such as track of sleep, burned calories and steps taken, to be retrieved from Health, processed and uploaded. There is a keen purpose in making use of iOS’ notification system for some of the functionalities in the app. For example, we could develop a “reminders” functionality by which users would be notified when they had not checked their glucose, in the main view, after 24 hours or had not uploaded new health data samples for a while. Assuming we can achieve the automatic refreshing of the app (while running in the background) of the latest glucose samples shown, users could also get notifications based on the last calculated risk of hypoglycemia or if their most recent read samples show an unusually high or low quantity. Since Spanish is the main and only language available on the app for now, we would like to at least include English as an option in order for the app to reach a wider range of users that may benefit from its use. We would like to keep a closer eye on the code-wise connectivity management between the Apple Watch and iPhone together with how iPhone works with running background tasks, since this is a delicate process to be tested under a considerable number of conditions and situations, to make sure users have the fastest and most comfortable experience of use from glUCModel’s WatchOS. Connections to the server are never a feature to be treated lightly. While most of the connections made to read data from the database are controlled so that the app is responsive to problematic situations (server is down, no signal or connection from the iPhone, etc.), there is still some work pending on the request connections and when reading the latest glucose samples. 70
Since the last development stages of the app were finished and tested more quickly than other features first developed, there is obviously work to be put into the code. As the app has been taking shape and molded more clearly towards the end of the development of this project, a lot of the code will most definitely be reviewed, restructured and optimized in order to avoid repeated lines, to make better use of the memory and Swift’s specific techniques, to become more errorproof and for the app to work better and faster We would like to learn how the new SwiftUI views work too, since it is made to work much faster, using as little code as possible, and Apple is slowly migrating its traditional views management towards this style, encouraging developers to create their new apps with it and aiming for it to be the main source for views on apps in the coming years. Last but not least, we are really aiming for the app to get officially released on the App Store, which will require first enrolling into Apple’s Developer Program annual membership[19], and then submitting the app for a review to ensure it meets all the requirements for its distribution. Conclusiones y próximos objetivos Todos los objetivos principales marcados al comienzo del proyecto se han completado, puesto que se han conseguido recoger las muestras de datos de salud medidas por el Apple Watch, procesarlas y subirlas a la base de datos de glUCModel, para después usarlas al solicitar una predicción de glucosa, ya sea desde el Watch o desde el propio iPhone. Los usuarios también pueden, con un sencillo gesto táctil, hacer un seguimiento de sus muestras más recientes de glucosa tras subirlas, también, a la base de datos, a la vez que obtienen más detalle sobre los datos de sus muestras, posibles riesgos y porcentajes calculados sobre dichas muestras. Puesto que esta nueva versión de la aplicación para iOS y WatchOS se ha desarrollado completamente desde cero y a la vez que la database se estaba reconfigurando y los modelos se estaban terminando de pulir, ha habido algunas características que no pudieron terminar de implementarse o incluirse. Por ejemplo, convertir las unidades de mg/dL a mmol/L para cada vista. El objetivo más importante que nos marcamos de aquí en adelante es el de incorporar muchos más tipos de datos de salud, tales como el registro de sueño, calorías quemadas y pasos, para recogerlos desde Salud, procesarlos y subirlos. Hay una firme intención de hacer uso del sistema de notificaciones de iOS de cara a algunas de las funcionalidades de la app. Por ejemplo, podríamos desarrollar una funcionalidad de “recordatorios” con la que los usuarios serían notificados 71
cuando no hubiesen comprobado su glucosa, en la vista principal, pasadas 24 horas, o cuando no hubiesen subido nuevas muestras de datos de salud en un tiempo. Suponiendo que se pudiese lograr la actualización automática de la app (funcionando en segundo plano) de las muestras de glucosa más recientes en pantalla, los usuarios también podrían recibir notificaciones basadas en el último riesgo de hipoglucemia calculado o si sus muestras más recientemente leídas tienen una cantidad anormalmente alta o baja. Como el castellano es el principal y único lenguaje disponible, por ahora en la app, nos gustaría incluir el inglés, por lo menos, como una opción más para que la app pueda llegar a una cantidad más amplia de usuarios que podrían beneficiarse de su uso. Nos gustaría también no perder de vista a la gestión de la conectividad entre el Apple Watch y el iPhone a través del código, junto con cómo trabaja el iPhone con las ejecución de tareas en segundo plano, puesto que estos procedimientos son delicados y deben probarse bajo una considerable cantidad de condiciones y situaciones para asegurar que los usuarios tengan la experiencia más rápida y cómoda durante el uso de glUCModel para WatchOS. Las conexiones al servidor no es algo que deba tratarse nunca a la ligera. Por un lado, la mayoría de las conexiones realizadas para leer datos de la base se están gestionando de modo que la app pueda reaccionar a situaciones de error (que el servidor esté caído, que el iPhone no tenga nada de señal o conexión, etc.), pero queda trabajo que hacer sobre las conexiones para las solicitudes y para la lectura de las muestras recientes de glucosa. Dado que las últimas etapas del desarrollo de la app se completaron más rápido que las primeras partes implementadas, obviamente hay trabajo que aplicar al código. Ya que la app ha ido tomando forma y definiéndose de forma más clara hacia las etapas finales del desarrollo de este proyecto, hay gran cantidad de código que definitivamente se someterá a revisión, reestructuración y optimización para evitar líneas repetidas, hacer un mejor uso de la memoria y de las técnicas propias de Swift, hacerse más resistente a los fallos y para que la app funcione más rápido y mejor. Nos gustaría aprender cómo funcionan las nuevas vistas con SwiftUI también, puesto que se ha diseñado para funcionar más rápido y usando el menor código posible, y Apple está poco a poco cambiando su gestión tradicional de las vistas en favor de este nuevo estilo, animando a los desarrolladores a que creen sus nuevas apps con ello y con el propósito de que sea la fuente principal de las vistas en las apps de los próximos años. 72
Por último, pero no menos importante, pretendemos con ahínco conseguir que se publique la app de forma oficial en la App Store, para lo cual hará falta primero inscribirse en el Programa de Desarrolladores de Apple con una membresía anual, seguido de una entrega de la app para someterse a una revisión que garantice que cumple todos los requisitos para su distribución. 73