BLE Beacons in the modern hospital reception desks by Jacek Adamczyk

Page 1

Bluetooth Low Energy Beacons in the modern hospital re c e p t i o n desks



Poznan University of Technology Faculty of Electronics and Telecommunications Information and Communication Technology

Bluetooth Low Energy Beacons in the concept of modern hospital reception desks

inż. Jacek Adamczyk

Master Thesis under supervision of dr inż. Adrian Kliks Poznań 2014



Abbreviations AES - Advanced Encryption Standard AJAX - Asynchronuous JavaScript and XML BLE - Bluetooth Low Energy CRUD - Create, Read, Update, Delete EDR - Enhanced Data Rate HTTP - Hyper Text Transfer Protocol IEEE - Institute of Electrical and Electronics Engineers IETF - Internet Engineering Task Force IO - Input / Output ORM - Object-relational Mapping OS - Operating System QoS - Quality of Service SLA - Service Level Agreement SQL - Structured Query Language URI - Uniform Resource Identifier

5



Abst ra c t



Abstract This paper is the quintesence of the present, modern approach of designing and implementing web applications - it will provide a comprehensive knowledge from area of databases, web applications, using the wireless short-range communications standards (e.g. Bluetooth Low Energy - BLE), native mobile devices applications with Google Android OS. The main aim of the project part of this thesis is to create a software system supporting patient registration in a private clinics, with the specific use case at one of such clinics located in the city of Śrem, Greater Poland.

Abstrakt Praca będzie możliwą kwintesencją aktualnego, nowoczesnego podejścia do pisania aplikacji internetowych – będzie połączeniem wiedzy z zakresu baz danych, aplikacji webowych, wykorzystaniu komunikacji bezprzewodowej małych odległości (Bluetooth Low Energy - BLE) oraz natywnej aplikacji z przeznaczeniem użytkowania na urządzeniach mobilnych z systemem operacyjnym Google Android. Celem pracy jest stworzenie informatycznego systemu wspomagającego rejestrację pacjentów w prywatnych przychodniach medycznych, z potencjalnym wykorzystaniem systemu w jednym z prywatnych gabinetów medycyny pracy działającym w Szpitalu Miejskim w Śremie (Wielkopolska).

9


Streszczenie

Praca została podzielona na dwie części: praktyczną, która stanowi implementację konceptu „rDesk” - elektronicznej rejestracji pacjentów - oraz pisemną, w której zawarty będzie opis teoretyczny i techniczny wspomnianego projektu. Druga z wspomnianych części została natomiast podzielona odpowiednio na pięć następujących sekcji: • Wstęp teoretyczny - Zawiera teoretyczny opis technologii zawartych w pracy. • Koncept Systemu - implementacja systemu w ujęciu ogólnym. Opis pomysłu, użytych technik i zaproponowanej architektury programistycznej. • Cel pracy - opis działań, które skłoniły autora do podjęcia tematu, celem stworzenia wartościowego i kompletnego dokumentu. • Idea - opis założeń opartych na wstępnym szkicu systemu. Warstwy aplikacji, kategorie użytkowników i sposoby interakcji pomiędzy oba tymi obszarami. • Aplikacja internetowa i mobilna jako propozycja rozwiązania problemu - krótka dyskusja na temat znaczenia Internetu, urządzeń mobilnych i aplikacji hybrydowych łączących oba te podejścia oraz w jaki sposób mogły zostać użyte podczas implementacji założeń projektowych. • Spektrum technologii - przedstawienie aktualnie dostępnych rozwiązań, z pośród których został wybrany zestaw narzędzi użyty podczas rozwoju projektu. • Architektura systemu - podrozdział przeznaczony dla głębszego spojrzenia w pojęcia aplikacji internetowych działających w czasie rzeczywistym, asynchronicznej natury środowiska serwerowego NodeJS, wzorca programistycznego „Model-Widok-Kontroler”, oraz całej gamy innych użytych w projekcie narzędzi (np. Grunt, AngularJS, MongoDB). • Wykorzystane standardy - praca korzysta z osiągnięć wielu standardów IEEE, IETF, ECMA, takich jak: Bluetooth Low Energy, komunikacji bezprzewodowej 802.11, protokołu HTTP, skryptowego języka programowania JavaScript. W tym podrozdziale zawarte będzie krótkie wprowadzenie na ich temat. • Implementacja - szczegóły kodu źródłowego, użyte w nim techniki i wzorce.

10


Koncept systemu Cel pracy Gwałtowne zmiany we wszystkich częściach branży IT podczas ostatniej dekady, zwłaszcza w dziedzinie rozwiązań internetowych, nabrały tempa, które przestaje pozwalać na ich swobodne identyfikowanie. Dziesiątki kompletnych i innowacyjnych produktów, zarówno z technicznego jak i ekoonomicznego punktu widzenia, wychodzą na światło dzienne każdego dnia, a nawet i godziny. Coraz to więcej „białych plam” na mapie świata zostaje podłączonych do globalnej sieci Internetu. Daje to dostęp powiększającej się części ludzkości do wolnej wiedzy, komunikowania się, kreowania nowych modeli biznesowych (np. SaaS, PaaS, IaaS - Software - , Platform - , Infrastructure as a Service), lub nawet możliwość zakładania w całości wirtualnych przedsiębiorstw. Równolegle z wcześniej wspomnianymi zmianami w rozwiązaniach internetowych, technologie bezprzewodowe krótkiego zasięgu (do 100m) doświadczyły również wysokiego tempa zmian. Część z nich, niegdyś niezbędnych do „codziennego życia”, miało przewidywaną świetlaną przyszłość. Niestety, zostały już dawno wyparte i zastąpione przez nowsze rozwiązania (np. przypadek komunikacji w podczerwieni - IrDA [1] w konfrontacji z technologią Bluetooth). W momencie tworzenia pracy, a więc w drugiej połowie 2014 roku, standard Bluetooth 4.0+ Smart / Low Energy, zyskał największą popularność w ostatnich miesiącach pośród urządzeń mobilnych, których całkowita ilość wspierająca ów standard wraz z poprzednimi wersjami wzrosła z 10% w roku 2011, przez 80% w roku 2012, do 85% w roku 2013 [2]. W raz ze wzrostem zainteresowania tą technologią, na rynku wzrosła liczba produktów korzystających z Bluetooth Low Energy (BLE), takich jak: Fitbit - bezprzewodowy monitor aktywności i snu [3] , The Tile [4] - lokalizator zagubionych rzeczy osobistych, Estimote - wspomaganie systemów sprzedażowych poprzez kontekstową personalizację oferty dla klienta [6]. Urządzenia Estimote zostały wykorzystane w części projektowej pracy. Badanie przeprowadzone przez firmę FORTINET w styczniu 2014 roku [6] na temat gotowości placówek polskiej służby zdrowia do wprowadzenia „pełnej, lub prawie pełnej gotowości” do wdrożenia systemu elektronicznego raportowania zdarzeń medycznych P1 wskazuje, że jedynie 10% z nich jest gotowych do przeprowadzenia informatyzacji. W rzeczywistości, ich liczba może być nawet niższa. Autor pracy postanowił zmierzyć się z tym tematem i pokazać, że wspomniany problem może być rozwiązany w innowacyjny i nietuzinkowy sposób, a implementacja takiego rozwiązania nie musi zajmować okresu czasu liczonego nawet w latach. Pod uwagę zostały wzięte również następujące czynniki: • Duże inwestycje sektora IT w obszar związany z komunikacją bezprzewodową krótkich odległości standardu Bluetooth Low Energy. Dynamika powstawania nowych (w tym polskich) firm zajmujących się rozwijaniem wspomnianej technologii (np. Estimote, Roximity, Kontakt.io)

11


Figure 1: Graficzny interfejs użytkownika projektu „rDesk” (source: J.Adamczyk).

Figure 2: Widoki interfejsu użytkownika w aplikacji mobilnej (source: J.Adamczyk). 12


• Chęć stworzenia produktu/usługi internetowej w oparciu o dostępne obecnie szerokie spektrum rozwiązań i narzędzi deweloperskich - od bazy danych, aplikację serwerową, po aplikację kliencką dostępną z poziomu przeglądarki interetowej oraz natywną aplikację mobilną dla systemu Google Android OS. • Wnioski wyciągnięte z obserwacji pracy publicznych placówek medycznych i prywatnych przychodni lekarskich - możliwość stworzenia oprogramowania umożliwiającego drastyczne skrócenie czasu poświęcanego na wykonywanie powtarzalnych zadań we wspomnianych jednostkach. Pożądanym rezultatem wprowadzenia takiego rozwiązania byłoby skrócenie oczekiwania w często obecnie długich, szpitalnych kolejkach.

Proponowane rozwiązanie Projekt noszący nazwę rDesk, stanowiący drugą część pracy wykorzystuje nowoczesne podejście łączenia kilku technologii w jeden, kompletny produkt/usługę: komunikację bezprzewodową krótkich odległości, mobilną aplikację internetową oraz „cloud computing”1. System ma za zadanie ułatwić korzystanie z usług medy cznych obu stronom będących ich częścią - pacjentom oraz personelowi medycznemu. Ilustracja 1 przedstawia jedną z możliwości implementacji takiego systemu w ujęciu uwzględniającym warstwy aplikacji: 1. entry (wejściowa) - poszczególne grupy użytkowników mogą nawiązywać interakcję z systemem poprzez przeglądarkę internetową lub aplikację mobilną, z różnymi szczeblami dostępu: • pacjenci, mają możliwość zarejestrowania się do danego gabinetu/przychodni poprzez stronę internetową lub aplikację mobilną, w drugim przypadku będąc w bezpośrednim położeniu danej jednostki medycznej, korzystając z wirtualnego zaproszenia wysłanego przez system poprzez urządzenia nazwane Estimote Beacons, firmy Estimote2, wykorzystujące standard Bluetooth Low Energy. Cała komunikacja pomiędzy tymi urządzeniami a systemem obsługiwana jest prez aplikację napisaną pod system operacyjny Google Android, w wersji 4.3 lub wyższej. • personel medyczny, posiada możliwość uzyskania dostępu do systemu aż do poziomu administratora. Jest upoważniony do tworzenia, odczytywania, uaktualniania oraz usuwania danych pacjentów3, wizyt, przepisanych badań itp.

1 cloud computing (ang.) - określenie wzorców tworzenia aplikacji/systemów rozproszonych oraz ich instalacji w tzw. „chmurze”, platformie serwerowej utrzymywanej przez zewnętrzną firmę, dynamicznie udostępniającą swoje zasoby pod potrzeby instalowanej w niej aplikacji (np. Amazon Web Services, Heroku, OpenStack) 2 Estimote Inc. - http://estimote.com/ 3 CRUD - Create, Read, Update and Delete - czyli tworzenie, odczytywanie, aktualizowanie i usuwanie rekordów z bazy danych należącej do danego systemu informatycznego

13


2. logic (logika systemowa) - warstwa odpowiadająca za weryfikowanie i autoryzację użytkowników, zarządzanie sesjami, ale również za wszelkie operacje wykonywane na przesyłanych do serwera danych z warstwy wejściowej. W dzisiejszych rozwiązaniach dążących do rozdzielania poszczególnych modułów systemowych tworząc z nich niezależne jednostki, aplikacje serwerowe są używane jako elementy pokrywające praktycznie wszystkie wcześniej wymienione aktywności. 3. storage (przechowywanie danych) - dane wynikowe, „płynące” z warstwy logiki systemowej mogą być zapisywane zarówno lokalnie (na maszynie, w której uruchomiona jest aplikacja), bądź w formie rozproszonej, która zyskuje w dzisiejszych czasach gigantyczną popularność przez koncept „chmury obliczeniowej”, gdzie większość operacji bazodanowych i biznesowych wykonywanych jest przez zewnętrzne serwisy, z określoną jakością i standardem obsługi (QOS -Quality of Service oraz SLA - Service Level Agreement). Praca ta, będąca pierwszą wersją systemu, będzie przechowywać dane lokalnie.

Implementacja Implementacja konceptu rDesk, obejmuje dwa obszary: stronę serwerową (ang. backend ), oraz kliencką (ang. front-end ). Na ostatni wymieniony przypadek składają się z kolei: natywna aplikacja mobilna dla systemu Google Android, oraz aplikacja działająca w dowolnej nowoczesnej przeglądarce internetowej, np. Google Chrome, Mozilla Firefox, Opera, Safari).

Aplikacja serwerowa Część odpowiedzialna za „backend” została oparta na multi-platformowym serwerze NodeJS - pozwalającym na uruchamianie kodu JavaScript. Kluczową cechą tego środowiska jest operowanie na zdarzeniach (ang. events) - w przeciwieństwie do innych popularnych środowisk serwerowych, NodeJS zarządza uruchomionymi aplikacjami jednowątkowo, nie powodując przy tym blokady zasobów wejściowych lub wyjściowych [7] (ang. non-blocking IO). Aplikacje napisane dla NodeJS charakteryzują się kodem asynchronicznym, którego nierozerwalną część stanowią wywołania zwrotne (ang. callback): 1. var myCallback = function(data) { 2. console.log('got data: '+ data); 3. }; 4. 5. var usingItNow = function(callback) { 6. //inne operacje... 7. callback('get it?'); 8. }; 14


9. 10. usingItNow(myCallback); Listing 1: Przykład asynchronicznego wywołania zwrotnego w języku JavaScript.

Zadeklarowana funkcja myCallback zostaje przekazana jako funkcja wywołania zwrotnego podczas wywołania funkcji usingItNow. Idea takiego wywołania opiera się zwykle na wykonaniu kodu zawartego w funkcji usingItNow, a na końcu przekazania wynikowych danych do funkcji wykonania zwrotnego, w powyższym przypadku myCallback, np. celem prezentacji ich użytkownikowi. Aby aplikacja mogła przyjmować żądania protokołu HTTP i na nie odpowiadać, należy określić ścieżki, które przekierują odpowiednie żądanie do danego kontrolera, który z kolei wywoła odpowiednie funkcje reprezentujące logikę biznesową. Zestaw takich ścieżek jest możliwy do określenia dzięki narzędziu ExpressJS, które pracuje jako jeden z dostępnych modułów NodeJS: 1. var express = require('express'), 2. app = new express(), 3. http = require('http'); 4. 5. 'app.get'('/', function(req, res) { 6. res.send('Welcome!'); 7. }); 8. app.get('/pacjenci', function(req, res) { 9. res.send('Jan Kowalski!'); 10. }); 11. app.post('/pacjenci', function(req, res) { 12. console.log(res.body); 13. }); 14. http.createServer(app).listen(3000, function(){ 15. console.log('Express server listening on port' + 3000); 16. }); Listing 2: Express routes.

Jak widać, na żądanie HTTP skierowane do głównej relatywnej ścieżki serwisu (np. rdesk.pl/, mojgabinet.com/) serwer odpowie wiadomością „Welcome!”. Warto zauważyć „podwójną” deklarację ścieżki /pacjenci. Różnią się one w rzeczywistości metodą, które wykorzystuje żądanie HTTP. Wysłane metodą GET (ang. pobierz, zdobądź), zwróci dane „Jan Kowalski!”, natomiast żądanie POST (wykorzystywane do przekazywania danych użytkownika do serwera, np. po wypełnieniu formularza), a konkretnie jego przesłana zawartość, zostanie wyświetlona w konsoli (console.log(res.body)); Taki styl programowania interfejsów serwerowych, gdzie na żądanie HTTP wysłane na dany adres URL (ang. Uniform Resource Locator), przypada wiele sposobów jego interpretacji, w zależności od metody wysyłki (GET, POST, PUT, DELETE) nazywamy programowaniem interfejsu REST. 15


Aplikacja kliencka Aplikacja dedykowana obsłudze przez przeglądarki (tzw. webowa), przeznaczona do użytku personelu medycznego rejestrującego wizyty pacjentów, została zaprogramowana z użyciem frameworka AngularJS, implementującego architektoniczny wzorzec oprogramowania Model-Widok-Kontroler. Warstwa Modelu odpowiada za reprezentację danych w aplikacji, Widok natomiast stanowi reprezentację tych danych w formie dostarczonej użytkownikowi, a więc w formie grafik, tekstu, tabel, wykresów, itd. Nad wszystkim czuwa Kontroler, warstwa odpowiedzialna za współpracę obu wcześniej wymienionych warst. Dba o to, aby reprezentacja Modelowa i jej potencjalne zmiany były zawsze odwzorowane w Widoku. AngularJS to otwarty (ang. open-source) framework stworzony przez Google, adaptujący wzorzec MVC. Jego kluczowe, odróżniające od konkurencji cechy to: • dynamiczne szablony - tworzone po stronie przeglądarki, odświeżane dynamicznie przez zapytania AJAX (Asynchronuous JavaScript and XML) celem pominięcia pobierania danej strony w całości z serwera. Dynamiczne zmienne w szablonie są deklarowane za pomocą podwójnych nawiasów klamrowych i odpowiadają zmiennym w zakresie zmiennych danego kontrolera/dyrektywy: <ng-directive>foobar</ng-directive> • dwukierunkowe połączenie danych (ang. two-way data-binding) - synchronizacja pomiędzy Modelem a Widokiem, bez rejestrowania dodatkowych elementów nasłuchujących zmian w obu warstwach. Każda zmiana połączonego obiektu/zmiennej w Widoku jest natychmiast odzwierciedlona w Modelu i odwrotnie. • „Wstrzykiwanie zależności” (ang. dependency injection) - używanie wbudowanych i zewnętrznych komponenentów w AngularJS ogranicza się do zadeklarowania ich jako zależności danego modułu. Programista nie musi się martwić o to jak instancja danego modułu została stworzona ani jak jest wywoływana. • Dyrektywy - rozszerzenie składni HTML, rozpoznawane w trakcie kompilowania widoku przez AngularJS pod jedną z trzech postaci: - elementu DOM (Document Object Model), <ng-directive></ng-directive> - atrybutu takiego elementu, <span ng-directive></span> - klasy przypisanej do tego elementu: <span class=”ng-directive”></span> Każda dyrektywa może posiadać własny zakres zmiennych (ang. scope), szablon HTML i własną logikę.

16


W projekcie rDesk zastosowano kilka charakterystycznych tylko dla tego projektu dyrektyw, m.in. przełącznik dat, estetyczne menu kontekstowe, slider boczny, listy pacjentów [..]. Graficzny interfejs użytkownika (ang. GUI - Graphical User Interface) został stworzony z myślą o użytkowaniu aplikacji na wszystkich urządzeniach korzystających z Internetu: od komputery klasy PC po tablety i smartphone’y. Każde z tych urządzeń wyświetla interfejs aplikacji w swój własny określony sposób. Technika „responsywnego” projektowania interfejsów graficznych (ang. RWD - Responsive Web Design) pozwoliła uzyskać taki efekt, zachowując na każdym z urządzeń czytelność, a zarazem komfort i szybkość działania (Figure 3). Aplikacja kliencka - urządzenia mobilne Przeznaczona dla grupy użytkowników będących pacjentami, stworzona na platformę Google Android w wersji 4.3 (Jelly Bean), lub wyższej. Dzięki bibliotekom udostępnionym dla programistów przez firmę Estimote, możliwym było stworzenie aplikacji reagującej na znalezienie się w pobliżu urządzeń tej firmy, korzystających ze standardu Bluetooth Low Energy. Aplikacja zareaguje powiadomieniem o możliwości zarejestrowania się w danym gabinecie lekarskim, powiadomi o pomyślnym procesie rejestracji i przypomni o niej, gdy dany pacjent nieopatrznie znajdzie się poza zasięgiem urządzeń Estimote.

Przyszłość projektu Praca ma za zadanie pokazać, że ułatwienie funkcjonowania placówek medycznych poprzez skorzystanie z najnowszych technologii może wydawać się trudnym, aczkolwiek możliwym do zrealizowania zadaniem, nawet w okresie krótszym niż liczonym w latach. Możliwości rozszerzania działania systemu rDesk są praktycznie nieograniczone: zaawansowane zarządzanie danymi pacjentów i wizyt, powiadamianie pacjentów czekających w kolejce o prawdopodobnym czasie oczekiwania i obsługi, wymiana informacji pomiędzy poszczególnymi placówkami i gabinetami medycznymi, stworzenie historii wizyt pacjenta, umożliwienie dostępu do tych danych online i wiele, wiele więcej. Wdrożenie powyższego rozwiązania i sukcesywne wprowadzanie jego możliwych rozszerzeń w formie przedstawionej w pracy bądź podobnej, na szczeblu krajowej służby zdrowia jest wyzwaniem koniecznym do podjęcia i stanowi niewątpliwie przyszłość opieki medycznej naszego kraju i podniesienia jej obecnych standardów.

17



Table of contents

Streszczenie .................................................................................................

10

1. Introduction ..............................................................................................

21

2.System Concept .......................................................................................

25

2.1 Motivation .....................................................................................

27

2.2 Idea ...............................................................................................

28

2.3 Web and Mobile Applications as the solution idea .......................

29

2.4 ’’State-of-the-art’’ technologies to choose between ....................

29

2.5 System architecture ......................................................................

32

2.5.1 Client-Side ........................................................................

32

2.5.2 Serwer-Side ......................................................................

37

3. Used Standards .......................................................................................

43

3.1 Bluetooth Low Energy ..................................................................

45

3.2 HTTP Protocol ..............................................................................

49

3.3 JSON - JavaScript Object Notation .............................................

52

3.4 REST - Representational State Transfer ......................................

54

4. Implementation ........................................................................................

57

4.1 Project Structure ..........................................................................

58

4.2 Using the repository ......................................................................

58

4.3 rDesk - app repository structure ...................................................

61

4.4 Server-Side Application ................................................................

66

4.5 Client-Side, Web-browser-based Front-End Application .............

78

4.6 Client-Side - Native, mobile Google Android OS application ......

88

4.6.1Environment .......................................................................

88

4.6.2 Project Structure ...............................................................

88

4.6.3 Activities ...........................................................................

91

4.6.4 AndroidManifestes.xml .....................................................

93

4.6.5 Application deployment ....................................................

94

4.7 Project state, Use Cases and Future Improvements ...................

95

4.7.1 Project State and Use Cases ...........................................

97

4.7.2 Future Improvements .......................................................

97

5. Conclusion ...............................................................................................

99

19



1. In trodu ction



1. Introduction This paper has been divided into two main parts: theoretical description and the technical details of the project alongisde with the project (implementation) itself. Respectively, first part has been divided into 5 sections, each consisting of its own set of subsections: Introduction Sheoretical introduction about technologies used in paper. System Concept Designed and implemented system as a whole. Description of idea, techniques used and software architecture solution introduced in the project. Motivation Author’s motivation to challenge this thesis topic in order to create valuable and comprehensive paper. Idea Description of the notion, based on the scheme. Software layers, user categories and ways of interaction between both mentioned. Web and Mobile Application as the solution idea A short dispute about what web, mobile, hybrid applications are and how they can become a part of the proposed solution. State-of-the-art technologies to choose between A part denoted to show and compare the solutions being used nowadays. Main aspect, about why the given set of tools and technologies have been chosen to be used, will be also covered. System architecture Subsection created in the sake of deeper dig into the concept of real-time, asynchronous nature of NodeJS, model-view-controller JS framework, as well as vast of other tools used, like MongoDB noSQL database, Grunt Task Runner, etc. Used standards This paper takes benefit of a vast of IEEE, IETF standards like Bluetooth Low Energy, 802.11 wireless communication, HTTP Protocol. Hence, a short digest of those has to be provided and this part of the thesis stands for that. Implementation Source code details. Description of programming and styles followed.

23



2. Sy stem Conc ept



2.1 Motivation Rapid changes in all existing IT branches in the last decade, especially in the area of web-based solutions, made it almost impossible to track, identify or categorize each one of them. Dozens of truly complete, innovative products, from the technical and economical, as well as marketing point of view, reach the global and local markets every single day. By connecting constantly more households and covering more and more areas so far ’IT technology untouched’, World-Wide-Web gave the ability to almost everybody to gain the knowledge, communicate with people around the globe, creating new business models (e.g SaaS, PaaS, IaaS - Software - , Platform - , Infrastructure as a Service) or even establish a totally virtual companies, without even a single physically existing client service point, at the same time drastically changing the way people see business, entertainment or public services. Alongside with previously described changes of web solutions, a short-range wireless technologies (domestic user - up to 100 m) have also experienced the high pace of changes and some of them, besides a great future and massive amount of appliances predicted, did not handle the pressure of the newer notions (e.g., IrDA - [1] vs. Bluetooth). Right now, at the half of 2014, wireless standard for short ranges called Bluetooth 4.0+ Smart, or Low Energy, has gained the biggest attention among the last months and the adoption yields rose up from 10% in 2011 (among the all devices supporting Bluetooth legacy standards), through 80% in 2012, to 85% in 2013 [2]. Hence, remarkably big amount of products wants to be the part of that success, redefining already existing ideas or creating a new consumer needs (Fitbit - fitness activity tracker [4], The Tile - lost and found things tracker [4], Estimote - lightweight-message retail support). According to the study conducted by FORTINET in January 2014, only 10% of Polish healthcare units are ready to manage their medical records fully digital, with the proper data format and connection to such national counterpart. In fact, these numbers can be even lower. Author’s motivation to challenge this thesis topic in order to create valuable and comprehensive paper was as follows: • Big IT sector investments in the area connected with new wireless transmission standard called Bluetooth Low Energy. Dynamics of either already created, as well as just establishing (also polish) new companies with the aim of using previously mentioned technology (e.g., Estimote, Roximity, Kontakt.io). • A willing to create the product, which would use a wide technological spectrum of solutions/tools - from the database, server-side part - to the native mobile application denoted for devices with the Google Android OS. 27


• Conclusions made during the observation of Polish present medical, public health consulting rooms and small companies, ability to create a piece of software to enable those facilities to drastically shorten the time of making repeatable and long tasks, during the process of handling the patients waiting usually in a long queues.

2.2 Idea Due to factors mentioned in previous subsection, the necessity of creating reliable and alongside innovative software systems in polish healthcare units was never more up-to-date than now and stands for the last reason, which has connected the main technological aspects and the functional challenge of this paper into the one, cohesive document. The concept project called rDesk aims to use the modern approach of connecting three state-of-the-art technologies - short-range, low-energy wireless communication, mobile web applications and cloud computing - as the elements of one, comprehensive solution desired to give the benefits of using it by both sides of every healthcare system - patients and medical staff. Figure 5 shows the sketch of the potentially possible use-case of such system, distinguished to following layers: 4. entry - both user groups are able to interact with the system by web browser or mobile application, but with different access levels: • patients will be able only to indicate their willing of visiting particular clinic by registering the visit through the website / mobile app or in the direct area of clinic’s location, by respond to the invitation sent by the system through Bluetooth Low Energy Beacons to the mobile app installed on the user’s smartphone with Google Android OS • medical staff will be able to have access grants assigned up to administrative level - therefore they will be able to create, read, update and delete4 records of patients, visits, prescribed examinations, etc. 5. logic - this layer is responsible for managing authentication, authorization, logging sessions, but also acts like a middleware for parsing, wrapping, concatenating the data provided by entry layer. Nowadays, when software sys4 CRUD - Create, Read, Update and Delete - operations performed on the particular database unit denoted to be the part of given software system

28


tems tend to be as loosely-coupled as possible, web servers are used as the implementation of unit desired to cover all the previously mentioned activities. 6. storage - result data provided by the logic layer can be stored either locally or in the distributed way, but the second option is a global „cloud computing” trend right now, where majority of computational and storing operations are performed by a third-party services, with the prescribed QoS and SLA (time of potential service outage, response speed, etc.) However, due to the law and functional issues, first part of the system presented in this paper will store the data locally.

2.3 Web and Mobile Applications as the solution idea A Web application (Web app) is an application program that is stored on a remote server and delivered over the Internet through a browser interface. Within the mobile computing sector, Web apps are sometimes contrasted with native apps, which are applications that are developed specifically for a particular platform or device and installed on that device. However, the two are not mutually exclusive because many applications contain elements of both native and Web apps. Programs that combine the two approaches are sometimes referred to as hybrid applications.

2.4 ’’State-of-the-art’’ technologies to choose between Databases are the foundation for any dynamic business. Whether it’s e-commerce, software-as-a-service (SaaS) or internal customer service tools, the database drives all data. Databases need power, and data centers in the cloud can provide that power. 29


The two popular database platforms are NoSQL and MySQL. Each has pros and cons, but your business model determines which one is better. NoSQL is more useful for large data stores, argue most developers today. But although there is more flexibility, there is more room for error. There are fewer admins familiar with NoSQL than MySQL, so it can be more difficult to find support. However, NoSQL is easily scalable horizontally. Horizontal scalability means NoSQL can store data across multiple servers, which improves performance on large queries. For most applications, MySQL has enough power and flexibility. Most admins are familiar with MySQL, so it’s the obvious choice. However, if the business plans to use big data or large record sets, NoSQL is better for data analysis with millions of records. NoSQL is also more flexible for businesses that plan to grow and need better performance than MySQL can offer. Node.js is relatively young with only three years since its first commit, but it’s already the fastest growing platform by the pace of contributions (the absolute number will surpass other languages in a few years). The fact that JavaScript language is the most popular language in the world and has the biggest runtime internment of course attributed to that. Many tools are ported to Node.js with small or no modification from the browser environment. Node.js is very efficient and great for building real time, NoSQL oriented and scalable systems. MVC Frameworks - Backbone.js is a JavaScript library with a RESTful JSON interface and is based on the model–view–presenter (MVP) application design paradigm. Backbone is known for being lightweight, as its only dependency is on one JavaScript library, Underscore.js. It is designed for developing single-page web applications, and for keeping various parts of web applications (e.g. multiple clients and the server) synchronized. AngularJS - open-source web application framework, maintained by Google and community, that assists with creating single-page applications, one-page web applications that only require HTML, CSS, and JavaScript on the client side. Its goal is to augment web applications with model–view–controller (MVC) capability, in an effort to make both development and testing easier. EmberJS - MVC framework strongly relying on client-side dynamic HTML rendering library Handlebars, which binds the template variable to the values available in Controller through previously specified data Models. Hence, web browser user gets the feeling of ’on-the-fly’ changes in the application just like it happens during the work with regular desktop applications. Framework takes the benefit of URL Routes, which play a crucial role on specifying current application state. Many EmberJS applications uses a data persistence library called Ember Data, which plays a similar role to many server-side ORM systems and act as a seamless middleware between client and server data objects/structures [11], providing API to store 30


and retrieve resources independently whether they are fetched with standard HTTP requests or Web Sockets, etc.

Figure 3: One of the first prototype schemes of the system concept made (source: J.Adamczyk). 31


2.5 System architecture 2.5.1 Client-Side Model-View-Controller - software architectural pattern for implementing user-interface applications. It divides a given software application into three interconnected layers, so as to separate internal representations of data (Model) from the ways that information is presented to or accepted from the user (View). First component, the Model, consists of application data, business rules, logic and functions. A View can be any output representation of information, such as a table, plot, etc. It takes the values from the Model and presents them to the user. The third part, the controller, plays an itermediary role between previously mentioned layers[7]. It reacts for a Model or View changes (in unidirectional or bidirectional manner - AngularJS, EmberJS feature) and performs necessary logic between those two layers to keep the Model and View data representation, which usually drastically differs. In AngularJS applications, these three cores are represented as follows: • Model - JavaScript Object Properties • View - Document Object Model (DOM) • Controller - JavaScript Classes ANGULARJS According to the rule „Don’t reinvent the wheel”, among the whole spectrum of the MVC JavaScript frameworks available, AngularJS has been chosen. It’s key feature called two-way data binding, truly MVC layers separation, dependency injection, dynamic HTML templating, easiness to adapt, short learn curve, good documentation and the enormous community with the vast of ’take-and-use’ examples available convinced the author to make it a core tool during implementing the client-side application of the project this paper is focusing on. Therefore, a deeper look at the one of the most famous JS framework nowadays is needed. AngularJS is an open-source framework crafted in the labs of Google Inc., introducing a set of concepts providing the easiness of creating, testing, extending and mantaining web applications without focusing on inner requirements of currently available web browsers on the market [8]. Client-side templating As many multi-page web applications focus on preparing the data with their visual HTML representation on the server-side, AngularJS approaches this problem from another point of view. For desktop-like, single-page application, very often a vast of AJAX requests is being sent to the application server, so there is no point to return in the response the whole HTML template at every single time. Instead, HTML template 32


is assembled in the browser and filled out (statically or dynamically) with data fetched from the server, appropriate for particular variables in the template. 1. <html ng-app> 2. <head> 3. <script src=”angular.js”></script> 4. <script src=”controllers.js”></script> 5. </head> 6. <body> 7. <div ng-controller=’HelloController’> 8. <p>{{greeting.text}}, World</p> 9. </div> 10. </body> 11. </html> Listing 3: Sample AngularJS dynamic HTML template - hello.html.

Template variables are sorrounded with double curly-brackets, notation known from e.g. Handlebars Templating Engine5, however they are used in a complete different way and should not be treated as similar templating solutions (see: Data Binding paragraph in this section, specific for AngularJS). 1. function HelloController($scope) { 2. $scope.greeting = { text: ’Hello’ }; 3. } Listing 4: Sample AngularJS Controller - controllers.js.

As it is clearly seen, $scope.greeting is interpolated to the {{ greeting.text }} variable view. This is the result of the following flow: 1. User requests the page of the application by providing an URL, clicking the appropriate link, etc. 2. The client (web browser, curl6 command) creates an HTTP request 3. After loading the page, Angular engine looks for the tag with ng-app attribute, to define the boundaries of the application and to load the first view template according to current URL route 4. Then, every registered binding and directive is found during the traversal process through the DOM boundaries set before. Now, registration of DOM listeners take place, as well as fetching data from the server, if needed.

5 6

Handlebars Templating Engine website - http://handlebarsjs.com/ curl - command-line tool to transfer data to a server, using a variety of popular web protocols

33


5. Fetched binding values are combined with the template and presented in the final form to the user. Afterwards, additional data could be fetched from the server within AJAX requests. Data Binding Declarative synchronization between given view variable (in fact a specific DOM element) and model object. Worth to notice, there are no event listeneres nor callbacks declared in the controller, which itself doesn’t have to be instantiated in Angular, everything is available ’out-from-the-box’. In most of templating systems binding is performed only in one direction. Model value is combined with the view at compilation time and then presented to the user. Unfortunately, any change caused by user is not reflected in the model and developer is forced to write code (most often not trivial) constantly synchronizing model with the view, and the opposite way [9] (Figure 4). Templating in AngularJS creates a live view after template compilation in a browser. Then, all the changes in the view element(s) binded with the model are reflected in a model itself immediately. Respectively, all the changes occured in a model are propagated to the view, making it an instant projection of a model 5. Dependency Injection Referring to Listing 4, an argument $scope has been passed to the controller constructor, giving it the access to create/manipulate/delete models within given controller’s scope. We can also request the access to many other built-in Angular components by only passing them as arguments to given controller’s constructor. How given object is constructed, initiated and invoked does not interest the developer of given controller and lets him fully focus on the logic needed to be implemented in current controller. We request the access to given objects, instead of creating dependency list. Such a mechanism is called dependency injection and lets the developer to add a variety of others modules like AngularJS built-in: • $rootScope - common scope between all application controllers / directives / services / factories (will be introduced further) • $http - core service enabling applications to communicate with remote servers using XHRs7. Higher level of abstraction is provided by $resource, which provides the way to communicate with REST-based applications/ services. $window, service referencing to the global JavaScript object window, with properties specific for currently user web browser. ...or even modules taken straight from the open-source community, like LocalStorageModule8, which comes up with a dependency injectable service localStorageService, respectively giving the controller’s access to the browsers HTML5-specific storage.

7 8

34

XHR - XMLHttpRequest Module available on public Github repository: https://github.com/grevory/angular-local- storage


Figure 4: Concept of one-way data binding in popular templating systems (source: J.Adamczyk based on [9]).

Figure 5: Concept of two-way data binding in AngularJS (source: J.Adamczyk based on [9]). 35


Directives HTML Syntax extensions (or DOM elements’ markers), recognized by Angular engine during compilation, which can occur in the application template in three forms: as a element name (tag), attribute name or a class name. Directives are considered as the elements able to be reused throughout the application. It consist of it’s own logic, template and scope, which can appear in the isolated or transcluded form. To create and start to use a simple directive we need to declare it as the application extension module [10]. 1. angular.module(’docsIsolateScopeDirective’, []) 2. .controller(’Controller’, [’$scope’, function($scope) { 3. $scope.naomi = { name: ’Naomi’, address: ’1600 Amphitheatre’ }; 4. $scope.igor = { name: ’Igor’, address: ’123 Somewhere’ }; 5. }]) 6. .directive(’myCustomer’, function() { 7. return { 8. restrict: ’E’, 9. scope: { 10. customerInfo: ’=info’ 11. }, 12. templateUrl: ’my-customer-iso.html’ 13. }; 14. }); Listing 5: Sample AngularJS Directive Declaration - script.js.

Directive is recognized by a DOM element (’E’, other possibilities are ’A’ - attribute and ’C’ - class), it has it’s own isolated scope, which copies the value from the outher scope’s value assigned to given attribute „info” inside the directive’s tag. 1. <div ng-controller=”Controller”> 2. <my-customer info=”naomi”></my-customer > 3. <hr> 4. <my-customer info=”igor”></my-customer > 5. </div> Listing 6: Sample AngularJS Directive Controller Template - controller-template.js

Each directive’s name, declared with camel case notation within JavaScript file (e.g. myNotation, masterThesisProject) can be later on recognized by controller only when instantiated with „dashes” notation in the template (Listing 4, line 2 and 4). In the above case, outer scope properties naomi and igor will be passed into the inner, isolated sco-

36


pe of the directive and respectively rendered in appropriate bindings within directive’s template (Listing 7, line 2 and 5). 1. <span class=”name”> 2. Name: {{customerInfo.name}} 3. </span> 4. <span class=”address”> 5. Address: {{customerInfo.address}} 6. </span> Listing 7: Sample AngularJS Directive Template - directive-template.js

2.5.2 Server-Side Cloud Computing Architecture - divides the application into two sections: the front-end and the back-end. They connect to each other through a network, usually the Internet. The front end is the side the computer user, or client, sees. The back end is the „cloud” section of the system. The front-end includes the client’s computer (or computer network) and the application required to access the cloud computing system. Not all cloud computing systems have the same user interface. Services like Web-based e-mail programs leverage existing Web browsers like Internet Explorer or Firefox. Other systems have unique applications that provide network access to clients. On the back-end of the system are the various computers, servers and data storage systems that create the „cloud” of computing services. In theory, a cloud computing system could include practically any computer program you can imagine, from data processing to video games. Usually, each application will have its own dedicated server. NODEJS Cross-platform environment for running server-side JavaScript code. Made by Ryan Dahl, with its first production version in 2009. The copyrights are in the hands of Joyent, company Dahl was working for that time. The core of the server is written in C++. Applications written for NodeJS should be designed in event-driven manner, using asynchronuous callback functions. NodeJS operates on a single thread, however its non-blocking IO nature and is considered as the great solution for high performance, scalable, real-time applications (e.g. chats, geolocation). Variety of built-in modules like http (HTTP Server), or socket (creating TCP Sockets, introduced in further subsections) exists, however developers are not limited by them and can design, export and share their own. 1. var http = require(’http’); 2. var server = http.createServer(function (req, res) { 3. res.writeHead(200, {’content-type’: ’text/plain’}); 4. res.end(’Hello World!’); 5. }).listen(9000); Listing 9: localhost HTTP Server listening on a port 9000 with only a few lines of code. 37


Among all the other web servers mentioned in the section „‚State-of-the-art’ technologies to choose between”, NodeJS has been chosen to perform server-side core operations due to the several reasons: Event-Driven Computing Unlike the other multi-threaded servers creating separate instances of program listening for the requests at given port, single-threaded NodeJS compensates all user requests within one running instance and serves their requests in asynchronuous manner [7]. Non-blocking Input/Output - a vast majority of the libraries/extensions/modules being used in NodeJS applications operates on the asynchronuous software programming pattern called callbacks: 1. var myCallback = function(data) { 2. console.log(’got data: ’+data); 3. }; 4. 5. var usingItNow = function(callback) { 6. // performing some work ... 7. callback(’get it?’); 8. }; 9. 10. //Finally use it with this line: 11. usingItNow(myCallback); 12. 13. furtherCodeOne(); 14. furtherCodeTwo(); 15. furtherCodeThree(); 16. 17. //Or define another callback on-the-fly: 18. usingItNow(function(data) { 19. doSomethingWith(data); 20. }); Listing 9: example of asynchronuous JavaScript callback.

In the beginning of the example above, function myCallback is being passed to the usingItNow function as an argument and after performing some actions (text after double backslash sign is being treated as a comment) callback is invoked within the function usingItNow. To make it more understandable - most often it takes some time to retrieve data from the server, pick up a specific record from the database collection/ table, etc. There is no need to block the whole resources of given server application thread, because the response time of data being (hopefully) sent back as the result is out of the application developer’s control. Therefore, application can send and forget the request and start doing the other tasks (in the example above furtherCodeOne, furtherCodeTwo, furtherCodeThree functions). At time response data will be back, application will invoke the callback function (myCallback) and pass the response data as 38


an argument, letting the callback function to deal with it. It is important to mention, that the actions resulting in receiving the response data may occur during or in between further executing code, so a special caution about work peformed at any common global data is highly needed and expected (which in case of JavaScript natural variable scoping philosophy does not have to be a serious threat). Google V8 Engine - written in C++, open-source lightweight javascript engine, which NodeJS implementation, as well as Google Chrome web browser is based on [12]. Node Package Manager - extremely useful tool, when dealing with installing a third-party NodeJS modules, as well as managing project dependencies. It decouples already implemented components from the working project, making it as portable as possible. All the dependencies, which working project or additional modules relies on, are stored in one integral file, usually named package.json, which also provides basic information about the application or a package (Listing 10). 1. { 2. "name”: "rdeskapp”, 3. "version”: "0.0.0”, 4. "dependencies”: { 5. "connect -mongo”: :~0.4.0”, 6. "ejs”: "~0.8.4”, 7. "enum”: "^0.2.6”, 8. "express”: "~3.4.3”, 9. "grunt -contrib -compass”: "^0.9.0”, 10. "handlebars”: "^2.0.0-alpha.4”, 11. "lodash”: "2.4.1”, 12. "mongoose”: "~3.8.8”, 13. "node-phantom”: "^0.2.5”, 14. "passport”: "~0.2.0”, 15. "passport -local”: "~0.1.6”, 16. "phantom”: "~0.6.4” 17. "phantomjs”: "~1.9.7-12”, 18. "socket.io”: "~1.0.6” 19. }, 20. "devDependencies”: { 21. "connect -livereload”: "~0.3.0”, 22. "grunt”: "~0.4.1”, 23. "grunt-autoprefixer”: "~0.4.0”, 24. "grunt -bower -install”: "~0.7.0”, 25. "grunt-concurrent”: "~0.4.1”, 26. "grunt -contrib -clean”: "~0.5.0”, 27. } 28. } Listing 10: package.json - file example.

39


EXPRESSJS A web development framework for NodeJS applications, minimal and flexible due to it’s common with Node platform, modular approach. Express applications are also characterized with the direct access to core NodeJS API9. Express can be installed through npm, by running a simple command in terminal: $ sudo npm install express -g where -g flag stands for installing it globally in the system. Creating the application with the help of Express framework is fairly easy. Following the modular nature of Node, we define the necessity of using Express (which is also o Node module), by including this lines in our module: kh

1. var express = require(’express’); 2. var app = new express(); 3. var http = require(‘http’); Listing 11: Express application.

Whenever a client’s HTTP request „reaches” the Express app it is being intercepted by the app instance. Developer can prescribe the routes for the application to react differentely to each of them, enabling to detect the state of the application (i.e. set of this kind of routes with distinction to HTTP methods is a first step to create REST API interface, which is going to be introduced later on), which primarily uses the stateless HTTP protocol:

kh

1. app.get(’/’, function(req, res) { 2. res.send(’Welcome!’); 3. }); 4. app.get(’/hello.text’, function(req, res) { 5. res.send(’Hola!’); 6. }); 7. app.get(’/contact’, function(req, res) { 8. res.render(’contact’); 9. }); 10. http.createServer(app).listen(3000, function(){ 11. console.log(’Express server listening on port ’ + 3000); 12. }); Listing 12: Express routes.

For the particular route one can set a request handler app.get(), which takes then relative URL as the first argument, and a callback as the second. There are 2 arguments passed in to the callback: req - a HTTP request object, and res - a HTTP response returned to the client after performing an application-specific logic. In the above example, application is sensitive for three cases, where HTTP request URL reaches:

9

40

API - Application Programming Interface


• application server root path (e.g. localhost/, myDomain.com/) and sends back the text in the HTTP response payload „Welcome!” • resource (most likely a file) named hello.text), and sends back the text „Hola!” • relative path /contact (e.g localhost/contant, myDomain.com/contact) and renders a contact view The code introduced in Listing 11 by default was able to process incoming HTTP requests at port 80 (which is default port for HTTP Web Servers [13]). When one needs to listen for request at different port, Express API enables that (e.g. at the port 3000, Listing 12, line 10).

41


42


3. Us ed S tand ards

43



Set of tools, which have been chosen to be used during the project’s implementation use a variety of standards described by IEEE, IETF, etc. They need to be shortly introduced before further reading.

3.1 Bluetooth Low Energy Bluetooth LE (Low Energy), with the 4.0 number specified by Bluetooth SIG [14] differs drastically from the Classic Bluetooth 2.1, which customers’ world got used to. Both of these standards work on 2.4Ghz ISM (Industrial, Scientific and Medical) band. Classic Bluetooth make use of 79 channels, each 1Mhz width, however Bluetooth LE works with only 40 channels, 2Mhz spaced. The Classic version, with pseudo-random frequency hopping sequence, each Master device can establish up to 7 Slave connections. On the other hand, Bluetooth LE comes with totally new protocal stack and profiles. LE radio system employs a shaped, binary frequency modulation in order to lower complexity of transceiver and 1Ms/s symbol rate, alongside with 1Mb/s bit rate [15]. There are two ways to achieve multiple access in Bluetooth LE radio system: • FDMA - Frequency division multiple access - 3 advertising and 37 data channels, 2 Mhz band spaced (Figure 6), • TDMA - Time division multiple access - one device sends the packet and the other receives it, at the specific for each device time interval Furthermore, another division of Bluetooth LE devices appears. Physical channels of LE TDMA devices use time units called events (Advertising, Connection), thanks to which we can distinguish devices referred as: • advertisers - transmit advertising packets • scanners - receive advertising packets without being obliged to connect to given advertiser Advertising events can cover all the process of communication if point-to-point or point-to-many (broadcast) unidirectional, as well as bidirectional transfer is eventually needed. During the second option, two-way communication is achieved by using data channels. The whole process of connection starts with listening to connectable advertising packets by initiators. The willingness of forming a connection occurs on the same advertising PHY channel which it was advertised on and immediately ends the advertising 45


process on this channel. From that moment, after establishing the connection, initiator is called a master and advertiser a slave, respectively. We take benefit of connection events now. They are responsible for carrying data packets between master and the slave, alongside performing a channel hopping during every connection event’s start (Figure 7). 802.15 IEEE standard gives the opportunity to the master device to initiate and end the connection events anytime.

Figure 6: Bluetooth LE FDMA - advertising and data channels (source: J.Adamczyk based on [18]).

Figure 7: Bluetooth LE FDMA - advertising and connecting events (source: J.Adamczyk based on [14]). 46


Figure 6 shows how Bluetooth LE protocol stack looks like. It distinguishes following layers (starting with the lowest): • Controller - responsible for running RF front-end and catching, queueing physical incoming packets, as well as outgoing. Used also as the first firewall for filtering packets sent by specific devices. • L2CAP - Logical Link Control and Adaptation Layer - ensures protocolchannel multiplexing, segmentation, flow control and retransmission of data in two directions with upper layers. The L2CAP layer comes up with logical channels idea, named L2CAP channels, which are multiplexed over one or more logical links. Units transferred by L2CAP channels are called L2CAP Service Data Units (SDUs) with the size up to 64 kilobytes. • GAP - Generic Access Profile - treated as the interface for upper layer to implement Bluetooth modes - master, slave, advertising, scanning • SM - Security Manager - responsible for pairing, authentication, encryption, key distribution. Security procedure are initiated by Master device with a 128-bit AES key, however Slave device may send a request to begin the security initiation, e.g during reconnection, when it provides keys to the Master in order to perform a reconnection [15]. • ATT - Attribute Protocol - key-value structures designed to optimize process of sending small packets. • GATT - Generic Attribute Profile - specific for Bluetooth 4.0, responsible for specifying application profiles, which stand for application-specific data formats, interpreted in the upper layer. This results in increased power efficiency, because only upfront-known, easy to adopt data is being exchanged. For the purpose of this paper, we will also introduce three fields, which are usually described by GATT attributes in modern Bluetooth LE devices: 1. UUID - Universally Unique Identifier - „guaranteed” to be unique across every device around the world, due to the 128-bit space (as we could already observe in case of IPv4 32-bit address space, which was designed in the same manner, it does not have to be truly future-proof). In order to omit the case of storing all known UUID, some of them has been preallocated for the sake of often-used, registered purposes. Futhermore, 16 and 32-bit aliases have been also introduced (we can refer them to the IPv4 address classes) [16]. 2. Major - 2 bytes identification number. Usual use cases fill this number with the number superior to the minor number, as some way of ordering the devices within given building, company, etc. 3. Minor - 2 bytes identification number. Usual use cases fill this number with the number subsidiary to the major number, as some way of ordering the devices within given limited area, floor, room, etc. 47


Figure 8: Bluetooth LE Protocol Stack (source: J.Adamczyk based on [15]).

Above fields were introduced as the core part of the concept of iBeacons, trademarked by Apple Inc.. This name describes a Bluetooth LE devices able to indicate their presence and approximate distance to the receiver, which is usually a smartphone with appropriate application able to process data sent by iBeacon with the specific proximityUUID [16]. During the time this paper was being prepared, there is a huge market demand on this kind of devices [17], like Estimote, Kontakt.io, Roximity, etc. 48


3.2 HTTP Protocol HTTP stands for Hypertext Transfer Protocol and is described as application-layer, reliable, connection-oriented protocol (both in OSI as well as in TCP/IP model [18]). First version of the protocol, delivered in 1990, used to transfer only raw data. HTTP operates in request/response manner. A client send a request to the exposed endpoint. Data sent distinguishes the header and the payload. In the header there are several fields needed to be filled out in order to be understand and processed by a server. Server then responds with HTTP response, structured similar to the request, also with some additional, required fields, like three-digit status code, which indicates, if request has been succesfully processed, if any internal server error occured, etc. Before request will reach their destinations, data sent by User Agents, which are responsible for forming datagrams, is encapsulated all the way down through the OSI/ TCP-IP model and after reaching destination devices, decapsulated in the opposite way up 7. During the source-destination route, packets travel through hops (nodes), which can be any networking device. After entering a particular hop, datagram is either partially or even fully rewritten in order to reach another node described by routing table, of a particular, current device (Figure 9).

Figure 9: OSI Model (source: J.Adamczyk based on [18]). 49


However, there are also a few intermediary devices, which can play a specific role during the client-server transaction. Each of these devices can occur in a totally virtualized form: • Proxy - acts like destination server, if the content appropriate to the request is cached in proxy server. Otherwise, if request cannot be processed locally, proxy server forwards this request to the origin sever able to fulfill request. • Gateway - an intermediary for the server able to serve to request • Tunnel - relay between two connections, only routes the message with no regards to eventually exisiting intermediaries (firewalls) HTTP message header can consists of up to three parts, each with some specific property-value pairs, dependent whether the specific HTTP message is a request or response, with some common parts between them. Some of mentioned fields will be grouped and presented here: 1. GENERAL - common headers to both HTTP request and response, do not apply to entity data provided in payload of the message • Cache-Control : caching mode directive10 • Connection : possibility of making HTTP connection persistent • Transfer encoding : how HTTP message is encoded (chunked, gzip, etc.) • Via : each intermediary between ultimate receiver of the message (IP address of receiver set during creation of HTTP message at origin source) adds the value to this field 2. ENTITY - fields which characterize payload (body) of the HTTP message • Content-Encoding : mechanism of entity’s compression (e.g tar, zip) • Content-Type : describes the format and charset of the message (e.g. application/json; charset=utf-8) • Expires : provides a date denoted for cache, in order to decide whether the entity should be considered stale or not. Date format is explicitly specified by RFC 1123 document (e.g. Thu, 01 Dec 1994 16:00:00 GMT ) • Last-modified : in the same date format as Expires, shows the information about when the entity has been changed last time 3. REQUEST - header fields specific for request message in HTTP transaction • Accept : Accepted media-types as a message response to the request (e.g plain/text, application/xml) • Accept-Encoding : Accepted message enconding (see. Content-Encoding in Entity-specific headers) 10 Most of the meanings of specific header fields’ properties have been intentionally omitted, because they are out of the scope of this paper.

50


• Authorization : set if resources needs and authentication or server has respondend with 401 status • Host : required field with the address of desired service/endpoint/port the request is addessed to • User-Agent : informations about the web browser responsible for creating the structure of request 4. RESPONSE-constructed by device addressed in a request (or by intermediary nodes), most of the time by web servers • Age : filled out by cache server with approximate age of entity • ETag : Validating fingerprint (usually consists of Content-MD5 value) • Location : when server has served the PUT or POST request, it may create the new resource and provide the URI of it in this field. When server needs more time to process the request this field describes the location of future-created resource) • Server : Informations about responding server Besides a vast of HTTP header fields (obligatory or optional), which messages and packet datagrams of this application-layer protocol can consists of, there are custom headers which can be assigned to the message. This properties, not stated in HTTP Standard, are usually prefixed with „X-” in current web applications (e.g . X-Powered-By: ASP.NET [19]). However, IETF RFC 6648 document deprecates this notation, proposing custom HTTP headers to be not inifluenced by any prefix, but rather create a non-ambiguous namespace, like vendor/company/domain specific (e.g „VND.ExampleInc.foo” or „com.example.foo”) [19]. One of the key aspect of HTTP request and it’s obligatory property to define is the method, describing how server should react to given request. We can distinguish 8 HTTP request methods: 1. CONNECT - used when requests is part of SSL proxy transaction 2. DELETE - a willing of deleting an entity. Server may reply with acknowledgment status and willing of discarding given resource on the server (which does not have to happen - none HTTP status is able to confirm such operation) 3. GET - retrieve an entity based on provided URI11 - none of GET requests should invoke a business logic (i.e creating or modifying business informations - see POST request) 4. HEAD - only HTTP header part is sent to the server - no payload 5. OPTIONS - modifies interaction properties of a server/service

11

URI - Unique Resource Identifier

51


6. POST - invokes code on a server side, creates new entity. Such HTTP requests usually consists of user-provided data (e.g. form data from a given website) 7. PUT - modifies particular entity (fully or partially) on a server or creates a new one if mentioned doesn’t exist 8. TRACE - request to track intermediary hops (through Via header field) on the way to ultimate recipient For each properly processed HTTP request, server or service responds with the HTTP response and a three-digit status code defined [13]. There are five groups of these codes, describing how server managed to process the request. Main groups with a few examples will be described. • 1xx - informational, whether the request was at least received by server and is being passed further in order to continue processing (e.g. 100 - Continue, 101 - Switching Protocols) • 2xx - success, request was succesfully understood and accepted (e.g. 200 - OK, 201 - Created - the usual response for POST requests) • 3xx - redirection, further processing of a request is necessary in order to fulfill requirements (e.g. 301 - Moved Permanently, 304 - Not Modified, 305 - Use Proxy) • 4xx - client-side error, request not understandable by server due to the bad syntax or not fulfilled authorization/authentication (e.g. 400 - Bad Request, 401 - Not Authorized, 404 - Not Found) • 5xx - server-side error, valid request could not be finished (e.g. 500 - Internal Server Error, 502 - Bad Gateway, 503 - Service Unavailable) Introducing the whole spectrum of not mentioned status codes is out of the scope of this paper.

3.3 JSON - JavaScript Object Notation Not a standard itself, but derived from a ECMA-262 standard [21], described in RFC 4627 [22], language-independent text format of structured data serialization. It can consist of four primitive types: 52


• strings - chain consisting of zero or more Unicode characters (limited only to the size of HTTP request) • numbers - represented in a form known from the most of programming languages. Ability to provide the number in fraction, integer, engineer, expnential mode, either positive or negative. Non-evaluable number is cosidered as a NaN (Not-A-Number) object. • booleans - Boolean logic values true or false • null - variable value not set and two structured, taken straight from JavaScript standard: • objects - closed in curly-brackets set of one or more name-value pairs, sepa- rated by comas. Name is a string and a value is represented by one member from (string, number, boolean, null, object, array) set. It means that every value in object can stand for another object instance (nesting). JSON document is a representative of the object type itself. • arrays - closed in square brackets structure of one or more values (usually, but not always, of the same type JSON Document Format is widely known in the area of modern web and mobile applications due to its native JavaScript support (out-of-the-box methods available to be invoked on a particular type instance), which is not always the case, because almost every programming language nowadays enables the applications to easily parse it. It’s easy to read and adapt structure makes it easy learn and implement in minutes and became widely recognized in the Web Developers community (e.g. main data structure used in NodeJS environment. A sample example of JSON document is presented below: 1. { 2. "id”: 1, 3. "name”: "A green door”, 4. "price”: 12.50, 5. "tags”: ["home”, "green”], 6. "article”: { 7. "title”: "Green doors will make you happy”, 8. "content”: "Lorem Ipsum Dolor Sit Amet...” 9. } 10. } Listing 13: Sample JSON Document

53


3.4 REST - Representational State Transfer Altough REST is not a standard itself, it relies very strongly on HTTP (REST author was the co-author of this protocol standard). Hence, it’s description has been located in this section of this paper. REST - REpresentational State Transfer is the architectural style of Web, introduced in years 1994/1995 [23] by Roy Fielding, is aiming into improvement of following web metrics: • speed - resource is explicitly described by an URI - therefore is able to be cached • scalability - caching enables storing data across clustered servers „closer” to the end user, e.g. with the help of CDN12 networks • simplicity - based only on CRUD operations - Create, Read, Update, Delete • data independence - none format of the resource is dictated up-front. Client can specify the required format in the header field (e.g. Accept or Accept- Encoding HTTP request header field - content negotiation) The word Representational, stands for a negotiable, often different format of messages during client-server transactions. State Transfer - means that the state of interaction is explicitly defined within interaction parameters, there is no necessity of looking into the message payload. What has to be pointed out, is that REST is not a technology, but it’s an architectural style deriving from web technologies. It’s key characteristics are: Stateless interactions - neither current nor former messages contain any information dependent on recipient’s state Uniform interface - REST interface is based on a limited set of HTTP Protocol’s actions. Programming interfaces of the applications, which implement REST paradigm are called RESTful. An example of such interface design is presented below: 1. GET /profiles HTTP/1.1 2. GET /profiles/12345 HTTP/1.1 3. POST /profiles/ HTTP/1.1 4. PUT /profiles/12345 HTTP/1.1 5. DELETE /profiles/12345 HTTP/1.1 12

54

CDN - Content Delivery Network


Sample HTTP requests performed against such API fulfill the requirement of using only four - GET, POST, PUT, DELETE - methods, which correspond to create, read, update, delete actions respectively. Their meaning can be as follows: 1. Retrieve all profiles available 2. Retrieve profile with an id: 12345 3. Create new profile entity with data included in POST request’s payload 4. Update (fully or partially) data of the profile with an id: 12345 5. Delete the profile with an id: 12345 Note, that this is only one of possible behaviors of such RESTful interface. Everything depends on the server logic, which is going to be performed on incoming requests. However, this approach is nowadays followed by a vast of web applications.

55



4. Imp lemen tation



CAVEAT A project implemented with the mentioned set of technologies does not explicitly rely on them and could be implemented with another widely-known tools/frameworks. Author has not performed any project-specific measurements which could indicate, that the choice of collecting this set was the one and only legitimate. This part of this paper is denoted for a technical description about what has been done, which tools have been used, which patterns and best practices have been followed in order to implement the concept of modern registration desk named rDESK .

4.1 Project Structure Source code of the project has been divided into two git public repositories, hosted on BitBucket13. First repository named rdesk-app consists of server logic imlplementation and client-side, web-based application. The second one called rdesk-mobile is the repository of the native Google Android client application. The whole project takes benefits from only free, open-source solutions.

4.2 Using the repository Using GIT repositories needs the short manual about how to fetch, install and perform the changes on such a repository. However, this is not a git software versioning system tutorial, because introducing the wide spectrum of knowledge about this topic is out of the scope of this paper.

CAVEAT All the examples this paper consists of were performed on Ubuntu 14.04 Trusty Tahr Operating System. Firstly, one has to install GIT packages within our OS. We can add it easily by executing: $ apt-get install libcurl4-gnutls-dev libexpat1-dev gettext \ libz-dev libssl-dev 13

BitBucket - hosting service for Git / Mercurial projects - http://bitbucket.org/

59


Then, a repository located on Bitbucket (or any other hosting service, e.g. GitHub) has to be cloned to our machine. We can do this two ways, either downloading the zipped package straight from Bitbucket or again, using the terminal: $ git clone https://yourlogin@bitbucket.org//your-repository.git After the package has been downloaded to our machine, one needs to install both: npm and bower dependencies by simply executing within the project directory: /your-repository$ npm install ...npm work... /your-repository$ bower install ...bower work... Then, application server has to be invoked, preceded by a variety of prepare tasks, by using Grunt JavaScript task manager. $ grunt serve Grunt looks for the module file named generically Gruntfile.js in the root project directory, and then for the task called serve: 1. grunt.registerTask(’serve’, function (target) { 2. if (target === ’dist’) { 3. return grunt.task.run([’build’, ’express:prod’, ...........’open’, ’express-keepalive’]); 4. } 5. 6. if (target === ’debug’) { 7. console.log(’DEBUG!’); 8. return grunt.task.run([ 9. ’clean:server’, 10. ’bower-install’, 11. ’concurrent:server’, 12. ’autoprefixer’, 13. ’concurrent:debug’ 14. ]); 15. } 16. 17. grunt.task.run([ 18. ’clean:server’, 19. ’bower-install’, 20. ’concurrent:server’, 21. ’autoprefixer’, 22. ’express:dev’, 23. ’open’, 24. ’watch’ 25. ]); 26. }); Listing 14: Gruntfile.js - task configuration file for Grunt. 60


At Listing 14 - line 17, there is a set of task always perfromed within the task serve, like: cleaning temporary files, setting parallel task to watch for changes alongside with refreshing the web browser, etc. One can specify also the target of the task (here: an environment Grunt should invoke the application in - e.g. grunt serve:dist). It is clearly seen, that one can even chain the declared tasks into any necessary order. The actual status of each task being performed can be followed in the terminal: Running „serve” task Running „clean:server” (clean) task Cleaning .tmp...OK Running „bower-install:app” (bower-install) task Running „concurrent:server” (concurrent) task Running „compass:server” (compass) task ... Done, without errors. Execution Time (2014-09-15 18:53:32 UTC) Total 3.1s Running „autoprefixer:dist” (autoprefixer) task ... Running „express:dev” (express) task Starting background Express server debugger listening on port 5858 Express server listening on port 9000 in development mode Running „open:server” (open) task db connection open Running „watch” task Waiting... GET / 200 63ms - 5.29kb ...

From that moment, application server listens on the port 9000 for incoming HTTP requests (Note: one GET requests was already served with the status 200 ). Any changes performed on any *.js file will be intercepted and investigated by a tool named JsHint14, which checks the syntax of the code.

14

JsHint - http://jshint.com/

61


4.3 rDesk - app repository structure With the rapid rise of web applications, constantly developed, deployed and published worldwide on a daily- or even hourly-basis, web developers community faced the problem of a variety of repetetive tasks they were needed to perform, sometimes in an infinite, iterative manner: • creating the application from the scratch, • refreshing the web browser in order to see te changes, • resolving problem with third-party dependencies, • minimizing source files, • creating CSS sprites from a wide spectrum of icon graphics, • many, many more... Fortunately, this problem is yet overcomed and all of above problems are now only the matter of being familiar with system terminal in order to deal with them. A triplet of the following tools: 1. Yeoman1215 - full-stack bootstrapping/scaffolding tool for web-application projects (Figure 10) 2. Grunt16 - JavaScript Task Runner (Figure 10) 3. Bower17 - package manager for client-side applications (Figure 10) has been used in order to kickstart the project. A backbone of the application was scaffolded within one of the several generators available within Yeoman tool called generator-angular-fullstack18. Usage of such generator is really simple and contracts only to running a following commands: $ npm install -g generator-angular-fullstack $ yo angular-fullstack rdesk First line is responsible for installing mentioned generator within our global system environment. Second one denotes an actual application bootstrap process (within the folder terminal points at given moment) and the name of the application assigned for the project (here: rdesk). Generated file structure of the project looks the following way:

15 Yeoman project official website - http://yeoman.io/ 16 Grunt project official website - http://gruntjs.com/ 17 Bower project official website - http://bower.io/ 18 available as the open-source module on Github - https://github.com/DaftMonk/generatorangular-fullstack

62


rdesk-app | +-- app | +-- bower_components | +-- angular +-- jquery +-- socket.io-client . . . +-- images +-- scripts | +-- controllers +-- directives +-- services app.js +-- styles +-- views | +-- partials 404.html index.html +-- lib | +-- config +-- controllers +-- models routes.js +-- node_modules +-- test Gruntfile.js README.md bower.json package.json server.js The source of code of browser-based application is located within the app directory, however all server logic is located inside the lib directory. Web browser client is the AngularJS (Figure 10) based application and it consists of following elements: • bower_components - a directory for all the Bower dependencies. One can find Angular compiled library here, jQuery - a library for DOM manipulations19, Twitter Bootstrap CSS Framework20, etc. All the client-side dependencies are stored in the file bower.json in the application root directory. • images - for any graphics needed to be used in the project (e.g. a favicon - address bar icon in web browser) • scripts - any JavaScript file, which is the part of Angular project. We divide them into controllers, directives, services. There is also one main entry file called app.js, with the logic dependent of running the web-browser-based application itself. 19 20

jQuery - official project website: http://jquery.com/ Twitter Bootstrap - official project website: http://getbootstrap.com/

63


Server-side application runs the NodeJS application server with the Express MVC framework on the top (Fig. 8) and has the following folder structure: • config - configuration files for NodeJS, Express, Passport authentication library, specific for every environment set by developer (e.g. testing, development, production) • controllers - actual business logic, database operations, divided into the files indicating the resource type the operations are being performed on) • models - data models consisting of the mongoDB (Fig. 8) database schemas, alongside with the schema-level validation functions) • routes.js - NodeJS module responsible for intercepting HTTP requests directed to the specific routes and redirecting the requests to be handled by specific controllers from controllers directory A folder named node_modules in the project root directory consists of all dependencies fetched by Node Package Manager, which are specified in the file package.json, within the same directory. README.md is the file, where developer can provide any written information likely to be needed in order to specify basic information about the project, installation manual, etc. This description will be shown at the main repository website (e.g. https://bitbucket.org/your-login/your-repository). Last but not least, main application entry file - server.js: 1. ’use strict’; 2. var express = require(’express’), 3. path = require(’path’), 4. fs = require(’fs’), 5. mongoose = require(’mongoose’); 6. 7. /** 8. * Main application file 9. */ 10. 11. // Set default node environment to development 12. process.env.NODE_ENV = process.env.NODE_ENV || ’development’; 13. 14. // Application Config 15. var config = require(’./lib/config/config’); 16. 17. {...} 18. 19. // Passport Configuration 20. var passport = require(’./lib/config/passport’); 21. // Connect to database 64


22. var db = mongoose.connect(config.mongo.uri, config.mongo. options, function(err) { 23. if(err) throw err; 24. 25. var app = express(); 26. var server = require(’http’).Server(app); 27. var io = require(’socket.io’)(server); 28. 29. // Express settings 30. require(’./lib/config/express’)(app); 31. 32. // Socket controller 33. require(’./lib/controllers/socket’).socketListener(io); 34. 35. // Routing 36. require(’./lib/routes’)(app); 37. 38. // Start server 39. server.listen(config.port, function () { 40. console.log(’Express server listening on port %d in %s mode’, config.port, app.get(’env’)); 41. 42. // Expose app 43. exports = module.exports = app; 44. }); 45. }); Listing 15: Server-side application main entry file - server.js.

As source code provided in Listing 15 is the main entry point for any other explanation at server-side application, author will provide a deeper explanation about what has been achieved at given code lines: • 1 - ’use strict’, changes the way JavaScript is usually interpreted in web browsers - it converts mistakes into thrown errors, simplifies variable uses, performs „secure-syntax” checks and more [24]. • 2-5 - creating the instances of required modules. ’fs’ is the File System module - lets the NodeJS to manipulate on files, ’mongoose’ - module taking the benefits of Mongoose21 driver - Object Data Manager working at the top of MongoDB - noSQL database used in the project • 12 - setting the default environment, which application is going to run in, according to specified on the system NODE_ENV variable or either setting ’development’ environment manually.

21

Mongoose - official project website: http://mongoosejs.com/

65


• 15 - retrieving the config files for required modules and assigning configura- tion variables to the config object • 22 - performing an asynchronuous connection to the mongoDB database server by providing an URI (connection string) and the connection options (here: safe: true, key-value pair, in order to ensure confirmations of database operations) • 25, 26, 27 - instantiating Express application object, HTTP server and SocketIO module. This code is executed within database connection callback, because of runtime inconsistencies, when the database connection occurs. More straightforward, there is no point of creating those objects (compiling the application), when the connection with database fails. • 36 - setting up the routes predefined in ’./lib/routes.js’ module and passing an app reference there. • 40 - starting point of listening to incoming requests at given, specified in first argument, port. • 43 - at most important line. App object is being exposed to other modules. After requiring server.js file in other modules one can access the exposed app object

Figure 10: Spectrum of the tools used in the project (source: J.Adamczyk). 66


4.4 Server-Side Application Models A system, which will be dealing with patients registration, needs to have database models specified in order to increase the abstract level of data, it’s portability and understanding. Author has distinguished 7 relevant models, which the database is going to work with: 1. Patient 1. /** 2. * Patient Schema 3. */ 4. var PatientSchema = new Schema({ 5. _createdBy: { type: Schema.Types.ObjectId , ref: ’userSchema’ }, 6. name: { 7. first: String , 8. second: {type: String , default: null}, 9. last: String 10. }, 11. birthdate: Date, 12. pesel: {type: Number , required: true}, 13. address: [addressSchema], 14. email: {type: String , default: null}, 15. company: { type: Schema.Types.ObjectId , ref: ’ companySchema’ }, 16. job: String , 17. visits: [visitSchema] 18. }); 19. 20. /** 21. * Virtuals 22. */ 23. 24. PatientSchema 25. .virtual(’name.full’) 26. .get(function () { 27. return this.name.first + ’ ’ + this.name.second + ’ ’ + this.name.last; 67


28. }) 29. .set(function (setFullNameTo) { 30. var split = setFullNameTo.split(’ ’), 31. firstName = split[0], 32. lastName = split[split.length]; 33. 34. this.set(’name.first’, firstName); 35. this.set(’name.last’, lastName); 36. 37. if (split.length === 3) this.set(’name.second’) 38. }); 39. 40. /** 41. * Pre Hooks 42. */ 43. 44. PatientSchema.pre(’save’, function (next) { 45. if (!this.birthdate) { 46. var peselString = this.pesel.toString(); 47. this.birthdate = new Date( 48. peselString.substring(0, 2), 49. peselString.substring(2, 4), 50. peselString.substring(4, 6) 51. ); 52. } 53. next(); 54. }); 55. 56. /** 57. * Validations 58. */ 59. // validate empty first and last names (second name can be empty) 60. PatientSchema.path(’name.first’).validate(function (first ){ 61. return first && first.length > 0; 62. }, ’First name cannot be empty.’); 63. 64. PatientSchema.path(’name.last’).validate(function (last) { 65. return last && last.length > 0; 66. }, ’Last name cannot be empty.’); 67. 68. // validate PESEL length different than 11 69. PatientSchema.path(’pesel’).validate(function (num) { 68


70. return num && num.toString().length === 11; 71. }, ’PESEL number has to be defined and be 11 digits long. ’); 72. 73. // validate empty address 74. PatientSchema.path(’address’).validate(function (addr) { 75. return addr.length > 0; 76. }, ’Address cannot be empty.’); 77. 78. // validate empty createdBy Field 79. PatientSchema.path(’_createdBy’).validate(function ( _ createdById) { 80. return _createdById && _createdById.length > 0; 81. }, ’createdBy cannot be empty.’); 82. 83. mongoose.model(’Patient’, PatientSchema); Listing 16: Patient database model - /models/patient.js.

Listing 16 shows some interesting features of modelling the data with Mongoose ODM22 at the lines: • 4-18 - Schema of a model is defined here. Within company property only ObjectId, a globally unique identifier for objects, is needed. At any time one can perform a population operation, which will extend given entity by combining Company model within Patient model • 24-38 - defining virtual attribute within property name called full, which is a combination of three patient’s names provided. What is charateristic about the virtual attribute is that it’s not stored persistently but returning to the user in as-needed basis. • 44-54 - before storing model entity with user-provided values, pre hooked function converts the string which stands for the birthdate to the JavaScript Date object • 60-81 - validation functions against values provided by user. E.g field pesel, which is the place to provide the PESEL number - 11-digit national identification number, is being validated against it’s length before entity will be stored in database • 83 - exposing the Model to the ODM 2. Visit - rDesk project operates on this Model most often. In the real world, that is what current registration desks are dealing with daily and one can treat this model as the mainly used data unit. Visit Model entites can be either created by Administrator or Doctor, not by Patient user role (Figure 11). 22

ODM - Object Data Manager

69


1. /** 2. * Visit Schema 3. */ 4. var VisitSchema = new Schema({ 5. _createdBy: {type: Schema.Types.ObjectId , ref: ’user’,default: null}, 6. date: { type: Date, default: Date.now }, 7. price: { type: Number, default: null }, 8. status: { type: String, enum: [’done’, ’waiting-for-examination -results’ ,’abandoned’] }, // visit entity can be created straight by a user 9. prescribedExaminations: [{ 10. type: Schema.Types.ObjectId, ref: ’examination’ 11. }] 12. }); Listing 17: Visit database model - /models/visit.js.

3. Examination - inseperable part of the Visit model. At every visit doctor can prescribe several examination in order to make the visit complete. Hence, the potential set (an array in the model) of examinations’ ObjectIDs is defined in the Visit model.

Figure 11: System database roles (source: J.Adamczyk). 70


1. /** 2. * Examination Schema 3. */ 4. var ExaminationSchema = new Schema({ 5. _createdBy: {type: Schema.Types.ObjectId , ref: ’user’}, 6. datePrescribed: { type: Date, default: Date.now }, 7. dateDone: { type: Date, default: null }, 8. details: {type: Schema.Types.ObjectId , ref: ’examinationDetails’}, 9. name: String , 10. label: String , 11. price: Number 12. }); Listing 18: Examination database model - /models/examination.js.

4. Details - details of given examination. It contists of date given examination was prescribed, it’s potential date of finish, details, etc. 1. /** 2. * Examination Details Schema 3. */ 4. var ExaminationDetailsSchema = new Schema({ 5. _createdBy: {type: Schema.Types.ObjectId , ref: ’user’}, 6. datePrescribed: { type: Date, default: Date.now }, 7. dateDone: { type: Date, default: null }, 8. name: String , 9. label: String , 10. price: Number , 11. details: [{ 12. question: String , 13. result: String , 14. remarks: String 15. }] 16. }); Listing 19: Examination details database model - /models/details.js.

5. StatusVisit - created explicitly by Patients when interacting with the system through the website form or through the mobile application. Patients wanted to be registered are obliged to provide a limited amount of information (e.g. optional address) in order to speed up the process of registration anyhow ((the doctor himself/herself does not need to collect all the patient’s data he or she can provide at his/her own, alongside shortening the time spent in the clinic). Afterwards, data collected within StatusVisit model entity is going to 71


be used in proper, the most valuable from the system perspective Visit entity. Therefore we can treat StatusVisit model as sort of intermediary in the system interaction sequence flow. 1. /** 2. * Status Visit Schema 3. */ 4. var statusVisitSchema = new Schema({ 5. address: { type: Schema.Types.ObjectId , ref: ’addressSchema ’, default: null }, 6. date: { type: Date, default: Date.now }, 7. name: { 8. first: {type: String , required: true}, 9. last: {type: String , required: true} 10. }, 11. type: { type: String, default: ’unknown’ }, 12. pesel: {type: Number , required: true}, 13. denotedFor: { type: Schema.Types.ObjectId , ref: ’userSchema’, required: true }, 14. status: { type: String, enum: statusTypes } // visit entity can be created straight by a user 15. }); Listing 20: StatusVisit database model - /models/statusvisit.js.

6. Address - address of the patient / company 1. /** 2. * Address Schema 3. */ 4. var AddressSchema = new Schema({ 5. street: String , 6. house: Number , 7. flat: {type: Number , default: null}, 8. zipcode: Number , 9. city: String 10. }); Listing 21: Address database model - /models/address.js.

7. Company - vast majority of the patients are employed and therefore needed to be examined 1. /** 2. * Company Schema 3. */ 4. var CompanySchema = new Schema({ 72


5.

_createdBy: { type: Schema.Types.ObjectId , ref: ’userSchema’ }, 6. name: String , 7. address: [addressSchema], 8. nip: Number 9. }); Listing 22: Company database model - /models/company.js.

RESTful API - routes.js One of the several goal of this project was to introduce a clean, well-designed REST interface (see: 3.4). In order to achieve that, following server routes have been defined in routes.js file:

1. ’use strict’; 2. 3. var index = require(’./controllers’), 4. users = require(’./controllers/users’), 5. session = require(’./controllers/session’), 6. patients = require(’./controllers/patients’), 7. visits = require(’./controllers/visits’), 8. stats = require(’./controllers/stats’), 9. companies = require(’./controllers/companies’); 10. 11. var middleware = require(’./middleware’); 12. 13. /** 14. * Application routes 15. */ 16. module.exports = function(app) { 17. 18. // Server API Routes 19. 20. // users 21. app.post(’/api/users’, users.create); 22. app.put(’/api/users’, users.changePassword); 23. app.get(’/api/users/me’, users.me); 24. app.get(’/api/users/:id’, users.show); 25. 26. // patients 27. app.post(’/api/patients’, patients.create); 28. app.put(’/api/patients/:id’, patients.edit); 29. app.get(’/api/patients’, patients.showAll); 30. app.get(’/api/patients/:id’, patients.showById); 73


31. app.get(’/api/patients/:id/reports/:repId’, patients. getReport); 32. app.get(’/api/patients?c’, patients.showByCompany); 33. 34. //companies 35. app.get(’/api/companies’, middleware.auth, companies. showAll); 36. 37. // Visits 38. 39. // user side 40. app.post(’/api/visits’, visits.create); 41. app.get(’/api/visits/:date’, visits.showVisitsByDate); 42. 43. // patient side 44. app.post(’/api/visits/:status/:date’, visits.createStatusVisit); 45. app.get(’/api/visits/:status/:date’, visits. showStatusVisitsByDate); 46. 47. // Beacons - separate routes for mobile base url 48. app.get(’/api/beacons/:beaconDataString’, users. showByBeaconData ); 49. 50. // sessions 51. app.post(’/api/session’, session.login); 52. app.del(’/api/session’, session.logout); 53. 54. // Stats 55. app.get(’/api/stats/:date’, stats.fetch); 56. 57. // All undefined api routes should return a 404 58. app.get(’/api/*’, function(req, res) { 59. res.send(404); 60. }); 61. // All other routes to use Angular routing in app/ scripts/app.js 62. 63. app.get(’/partials/*’, index.partials); 64. app.get(’/*’, middleware.setUserCookie , index.index); 65. };

Listing 23: HTTP Server Routes - /routes.js. 74


Listing 23 shows some important approach: within possibly the same URL, differentiated only by HTTP methods, we can distinguish in what state our application currently is and appropriately react to that state. We specify this behavior explicitly in lines: • 4-10 - requiring controller modules and assigning them to given variables as objects • 28-34 - operations involving Patient model resources - each route is being served with another method from patients controller object (e.g. create(req, res) method at line 28). There is also Express-specific feature about enabling route URL to have parameters and queries: – a string occuring after colon in route URL is accessible later on in handling method through req.params object, at property defined after colon in routes definition, for example: HTTP GET /api/patients/12345 will be intercepted by method showById in patients controller and req.params.id will be then equal to 12345. – a string occuring after question mark in route URL is accessible later on in handling method through req.query object, at property defined after question mark in routes definition, for example: HTTP GET /api/patients?acme will be intercepted by method showByCompany in patients controller and req.query.c will be then equal to acme. • 60 - if incoming request is addressed with the URL, which does not fit to any specified route, HTTP 404 status (Not Found) is returned. What is important to point out, each of the handling methods takes three parameters: req, res, next. The first two were already introduced (System Architecture, Client-Side, Par. 2.5.2) however the third, next is responsible for redirecting given HTTP request to the next route, which fulfills the requirements. Controllers Controllers are the modules with exposed functions of application business logic. The spectrum they cover is wide enough to create a separate paper, therefore only the part of available controllers is going to be comprehensively described: • visits.js - performs operation on resources connected semantically and log- ically with StatusVisit model: 1. /** 2. * Create visit with specific status 3. */ 4. exports.createStatusVisit = function (req, res, next) { 5. StatusVisit.findOne({ 75


6. "pesel" : req.body.pesel 7. }, function (err, _existingstatusvisit) { 8. if(err) return err; 9. if(_existingstatusvisit) { 10. return res.json(202, 'Status Visit with such pesel already exists.') 11. } 12. else { 13. User.find({ 14. "denotedFor": req.body.denotedFor 15. }, function (err, _denotedUser) { 16. if(err) return err; 17. if(!_denotedUser) { 18. return res.json(202, 'Denoted user does not exists.') 19. } 20. else { 21. var status = req.params.status; 22. if(['waiting', 'registered'].indexOf(status) !== -1) { 23. req.body.status = status; 24. if(status !== 'waiting') { 25. req.body.date = prepareRequestDate(req.params.date); 26. } 27. var statusVisit = new StatusVisit(req.body); 28. 29. statusVisit.save(function (err, _ statusvisit) { 30. if(err) { 31. return res.json(400, err); 32. } 33. 34. if(status === 'waiting') { 35. var toSend = { 36. _id: _statusvisit._id, 37. name: _statusvisit.name, 38. date: _statusvisit.date 39. }; 40. SocketCtrl.sendMessageToUser( _statusvisit.denotedFor , 'waiting:new', toSend); 41. } 42. return res.json(200, 'Visit has been saved with status: ' + status + '.' ); 76


43. }); 44. } 45. else { 46. return res.json(400, 'Visit has invalid status type.'); 47. } 48. } 49. }); 50. } 51. }); 52. }; Listing 24: Visit controller - /controllers/visits.js.

In order to understand the work of this controller, a short explanation will be provided, according to given lines: 5-11- Mongoose ODM can perform a query within the database straight from the given model. Here model queries the database by invoking: StatusVisit.findOne() and expects just one result back in the callback. The point os to check whether a StatusVisit with the PESEL number provided in the request already exists in the database. 13-19 - performing a query on User model. Now controller is looking for the id of the doctor which this StatusVisit is directed to.

Figure 12: Entities stored within statusvisits collection. Robomongo - GUI MongoDB Management Tool (source: J.Adamczyk). 77


27-32 - Mongoose ODM provides also other actions, like saving, updating, deleting, populating the records, and many, many more23. Here, it creates new instance of StatusVisit model and invokes the save() function, which equals to storing the entity to statusvisits collection (each Model will save it’s entities under callection: „name of the model in lowercase” + ’s’ at the end) (Figure 12). 40-44 - every connection to the application establish a WebSocket connection, thanks to the Socket.io24 library. Each connection then joins the room with the name of currently logged in user (applicable only to web application so far), which prevents server of receiving a vast of non-identified connections. Afterwards, StatusVisit controller at given lines creates the message which is going to be sent only to the user (doctor) with an id specified within just saved StatusVisit entity propagated in the callback (Listing 24, line 29) in _statusvisit object. • users.js - responsible for mantaining user data in the system. One interesting feature of this controller has to be introduced: 1. {...} 2. /** 3. * Get profile of specified user with Beacon Data 4. */ 5. exports.showByBeaconData = function (req, res, next) { 6. var queryArray = req.params.beaconDataString. split('+'); 7. var queryObj = { 8. uuid: queryArray[0], 9. major: parseInt(queryArray[1]), 10. minor: parseInt(queryArray[2]), 11. }; 12. 13. User.findOne({ beaconData: queryObj }, function (err, user) { 14. if (err) return next(err); 15. if (!user) return res.send(404); 16. 17. return res.send({ 18. _id: user._id, 19. name: user.name, 20. email: user.email 21. });

23 24

78

Mongoose API - http://mongoosejs.com/docs/api.html Socket.io - official project website - http://socket.io/


22. }); 23. }; 24. {...} Listing 25: User controller - /controllers/users.js.

Each User model entity can have the beaconData attribute described. Bluetooth Low Energy devices provide three public descriptors of given device: UUID, major number, minor number, which explicitly characterize the device globally and within given building/facility. This data is extremely useful in the rDesk reception desk concept, because every patient using rDesk mobile application provides the information after successful connection with such BLE device. Therefore, this device data is then resolved by server to the specific User (doctor, clinic) account. Listing 23 shows, how the BLE description points to the specific User account.

4.5 Client-Side Application - Webbrowser-based The structure and details of front-end AngularJS application will be introduced in this subsection. As it is impossible to cover all the logic performed by this part of the system, author’s point was to bring the idea of variety of techniques used during development of modern web application and connect them semantically in understandable manner. index.html & app.js index.html - located within /app/views directory, is rendered after entering the main URL of the application and stands for the entry point of the client-side application: 1. {...} 2. <html class=”no-js”> <!--<![endif]--> 3. <head> 4. <title>rDesk - modern hospital reception desk</title> 5. {...} 6. <link rel=”stylesheet” href=”styles/main.css”> 7. <link rel=”stylesheet” href=”bower_components/flat-ui-official/css/flat-ui.css”> 79


8.

<link rel=”stylesheet” href=”bower_components/angular-snap/angular-snap.css”> 9. </head> 10. {...} 11. <body ng-app=”rdeskApp”> 12. 13. <snap-drawer class=”sidebar” ng-include=”’partials/sidebar’”> 14. </snap-drawer> 15. <snap-content class=”main-container”> 16. <div ng-include=”’partials/navbar.html’”></div> 17. <div ng-view></div> 18. </snap-content> 19. {...} 20. <script src=”bower_components/jquery/dist/jquery. js”></script> 21. <script src=”bower_components/angular/angular.js”></ script> 22. 23. <!-- build:js({.tmp,app}) scripts/scripts.js --> 24. <script src=”scripts/app.js”></script> 25. <script src=”scripts/controllers/main.js”></ script> 26. <script src=”scripts/controllers/navbar.js”></ script> 27. <script src=”scripts/controllers/login.js”></ script> 28. <script src=”scripts/controllers/sidebar.js”></ script> 29. <script src=”scripts/controllers/signup.js”></ script> 30. <script src=”scripts/controllers/settings.js”></ script> 31. <script src=”scripts/controllers/visit.js”></ script> 32. <script src=”scripts/services/auth.js”></script> 33. {...} 34. </body> 35. </html> Listing 26: Root Angular template - /app/views/index.html.

This HTML document is mostly generated with Grunt tasks. Lines 6 - 8 load every necessary CSS stylesheet in order to create a comfortably looking environment for the user. All the client-side logic - controllers, directives and services, as well as third-party libraries from the bower_components are being loaded at lines 24 - 32, just before the 80


end of <body> tag (in order to make the static resources of the template independent from any potential error occured in those libraries). At most important thing happens at the line 11, where the Angular-specific attribute is specified: <body ng-app=”rdeskApp”> AngularJS library travers the DOM in order to find this specific attribute, which is in fact an Angular-specific directive creating the application scope within the HTML element (tag) and renders the appropriate HTML template inside, where this directive is instatiated (body element). App.js is the main entry of client-side logic: 1. 'use strict’; 2. 3. angular.module('rdeskApp’, [ 4. 'ngCookies’, 5. 'ngResource’, 6. 'ngRoute’, 7. 'ui.bootstrap’, 8. 'snap’, 9. 'ngAnimate’, 10. 'timer’, 11. 'btford.socket-io’, 12. 'angularCharts’ 13. ]) 14. .config(function ($routeProvider, $locationProvider, $httpProvider, snapRemoteProvider) { 15. {...} 16. 17. $routeProvider 18. .when('/’, { 19. templateUrl: 'partials/main’, 20. controller: 'MainCtrl’, 21. authenticate: true 22. }) 23. .when('/login’, { 24. templateUrl: 'partials/login’, 25. controller: 'LoginCtrl’ 26. }) 27. .when('/signup’, { 28. templateUrl: 'partials/signup’, 29. controller: 'SignupCtrl’ 30. }) 31. .when('/settings’, { 81


32. templateUrl: 'partials/settings’, 33. controller: 'SettingsCtrl’, 34. authenticate: true 35. }) 36. .when('/visit/new’, { 37. templateUrl: 'partials/new-visit’, 38. controller: 'VisitCtrl’, 39. authenticate: true 40. }) 41. .otherwise({ 42. redirectTo: '/’ 43. }); 44. 45. $locationProvider.html5Mode(true); 46. 47. {...} 48. 49. }]); 50. }) 51. .run(function ($rootScope, $location, Auth, snapRemote) { 52. 53. // Redirect to login if route requires auth and you’re not logged in 54. $rootScope.$on('$routeChangeStart’, function (event, next) { 55. 56. if (next.authenticate && !Auth.isLoggedIn()) { 57. $location.path('/login’); 58. } 59. }); 60. }); 61. Listing 27: Entry script file - /app/scripts/app.js.

The following operations are performed within this file. Among the lines: • 3-13 - a dependency injection of the external, required in the project AngularJS modules • 17-40 - Route Provider specifies the application behavior as the reaction for given URL change by web browser. Each route denotes the HTML template for a particular route, a controller and optionally, a requirement for the user to be registered in order to get access to given part of the application 82


Figure 13: Controllers’ scopes distinction within a specific view (source: J.Adamczyk).

• 41-43 - default route for accessed and unspecified before URLs (here: a redirection to home website) • 45 - prevents the application to reload the page every time the URL changes, links are being rewritten and hashbang mode25 is omitted. • 51-59 - if at given route description, property authenticate is set to true and current user is not logged in, application will redirect him to the login page. Controllers Controllers take the responsibility of the front-end application logic within given scope. There can be several active scopes existing alongside each other at the given view (Fig. 10): 1. navbar.js - sets the dropdown menu contents and logic for opening/closing the sidebar menu by clicking the icon at the left border of a scope. It also invokes a service called Auth in case of user’s willing to logout from the application 1. angular.module('rdeskApp’) 2. .controller('NavbarCtrl’, function ($scope, $location, Auth, snapRemote) { 3. $scope.menu = [{ 4. 'title’: 'Home’, 5. 'link’: '/’ 6. }, { 7. 'title’: 'Settings’, 8. 'link’: '/settings’ 9. }]; 10. 11. $scope.logout = function() { 12. Auth.logout() 13. .then(function() { 25

hashbang mode - e.g., rewriting <a href=”/some?foo=bar”> to /index.html#!/some?foo=bar [25]

83


14. 15. 16. 17. 18.

$location.path('/login’); }); }; {...} }; Listing 28: Navbar Controller - /app/scripts/controllers/navbar.js.

2. sidebar.js

Figure 14: DatePicker and RadialStats directives combined (source: J.Adamczyk).

3. main.js - main application view controller - contains of the datePicker directive outer logic, as well as functions responsible for fetching visit data for dashboard statistics and preparing resources for dashboard chart: 1. angular.module('rdeskApp’) 2. .controller('MainCtrl’, function ($scope, $http, Stats, $filter, Visit, $location, $rootScope) { 3. $scope.dateChosenChanged = function (_date) { 4. $scope.fetchStats(_date, function (data) { 5. $scope.actualStats = data; 6. }); 7. }; 8. 9. $scope.newWaitingVisit = function() { 10. $scope.actualStats.waiting++; 11. if($scope.data.data) { 12. //update waiting chart 13. $scope.data.data[$scope.data.data.length 1].y[1]++; 14. } 15. }; 16. 17. $scope.fetchStats = function (date, cb) { 18. var dateString = $filter(‚date’)(date, ‚yyyyMMdd’); 19. Stats.get({ date: dateString }, cb); 84


20. 21. 22. };

}; {...} Listing 29: Main Controller - /app/scripts/controllers/main.js.

Directives & Services Already introduced before (see: System Architecure section), directives are the reusable HTML extensions, understood by AngularJS during DOM traversial and often consisting of their own isolated scope. rDesk has the set of it’s own directives and also takes benefits of a group of third-party extensions provided by Angular open-source community: • datePicker - whenever user switches the date (Figure 14), outer scope of the directive is notified and visit data from given day is fetched from the server in order to update radialStats directive • radialStats - three basic statistics providing daily information about how many users have registered through the website form, how many are waiting in the queue outside the room/queue and how many visits have been successfully accomplished. Whenever a new user joins the queue, these stats are being updated „on the fly”. User can easily switch the dates in order to check the statistics from previous days (Figure 14).

Figure 15: rSelect dropdown menu (source: J.Adamczyk).

• rSelect - customized dropdown menu (Figure 15), an Angular wrapper for dropdown menu provided by FlatUI GUI framework26 • rList - visit list with the distinction to waiting and registered visits (Figure 16). It takes the name of the list from the directive custom attribute and looks for the appropriate template. 1. angular.module(‚rdeskApp’) 2. .directive('rlist’, function (StatusVisits, Socket, Auth, Visit) { 26

Flat UI Bootstrap User Interface Kit - http://designmodo.github.io/Flat-UI/

85


Figure 17: FlatUI User Interface kit (source: www.designmodo.github.io/Flat-UI/) 86


3. return { 4. templateUrl: function (elem, attrs) { 5. return 'partials/rlist-’ + attrs.type; 6. }, 7. restrict: 'E’, 8. replace: true, 9. scope: { 10. updateStats: '&’, 11. rebuildScroll: '&’ 12. } 13. {...} 14. }; 15. }; Listing 30: rList directive script.

1. {...} 2. <rlist type=”waiting” class=”rlist” update-stats=”newWaitingVisit()”> 3. </rlist> 4. {...} Listing 31: Usage of rList directive.

Figure 16: rList for waiting visits (source: J.Adamczyk).

Returned properties of directive have the following meaning: – restrict: ’E’ - indicates, that directive can be recognized within HTML template only by DOM elements (HTML tags) with „dash” notation – replace: ’true’ - directive’s own template will replace the DOM element, which Angular has recognized as the entry point of directive – scope: {...} - isolated scope of this directive is created by establishing the binding between the values of the properties from the outer scope (here: functions), specified as the values of attributes within directive HTML syntax (Listing 31). 87


Views - „Mobile-First” Responsive Web Design From the server side, views are the last element of MVC framework and the first stage of system interaction with the users. Therefore, Graphical User Interface of such systems should be designed in a easy-to-adapt and consist way, with user-centered approach. In the era, when mobile internet users amount has overcome desktop users [26], each modern web application should be oriented exactly to the firstly mentioned group. Hence, a web development trens called „Mobile First” is gaining welldeserved publicity. The problem of loading massive, „heavy” websites designed for desktops seems resolved nowadays thanks to the approach called „Responsive Web Design”(RWD). A principle of such technique is to manipulate website templates (HTML syntax as well as CSS stylesheets) in a way that empowers websites to „automagically” fit into screen they are currently displaying on. rDesk project takes the advantage of both of these approaches. One of the most popular „responsive” frameworks called Twitter Bootstrap has been used here and is responsible for adapting the front-end of the service to every user’s screen. The small help of CSS mediaqueries has been also involved. It’s basic idea is to provide breakpoints to CSS stylesheet, which describe how CSS queries should behave according to actual width size of the browser: 1. @media screen and (max-width: 960px) { 2. #registered { 3. .scrollme { 4. height: auto; 5. } 6. } 7. } Listing 32: Media queries in CSS stylesheet.

To give the user the the experience of using modernly designed application, author has decided to use the GUI kit called FlatUI, which introduces a concept of minimalistically looking user interface, without any shadows or gradients, in order to enable loading of the application on mobile devices as fast a possible. This UI kit works at the top of Twitter Bootstrap CSS framework (Figure 17).

88


4.6 Client-Side - Native, mobile Google Android OS application The second way patients will be able to interact with the server is the mobile application developed for Google Android devices with the OS version number greater than 4.3 („Jelly Bean”).

4.6.1 Environment There are two popular development environments, which Android community respects the most for implementing applications: Android Development Tool, based on Eclipse, and Android Studio, based on Intellij Idea. For this project, the second IDE27 mentioned has been chosen.

Figure 18: Android Studio ID (source: author’s J.Adamczyk).

4.6.2 Project Structure Structure of the project made within Android Studio is following:

27

IDE - Integrated Development Environment

89


Figure 19: Lifecycle of application Activity (source: J.Adamczyk based on: http:developer. android.comreferenceandroid appActivity.html#ActivityLifecycle). 90


RDesk | +-- app | +-- build +-- libs | +-- estimote-sdk-preview.jar +-- src | +-- main | +-- java | +-- com.example.jac.rdesk | LeDeviceListAdapter.class MainActivity.class RdeskRestClient.class RegisterVisitActivity.class | +-- res | +-- anim +-- drawable +-- drawable-hdpi . . . +-- layout +-- values AndroidManifest.xml | .gitignore build.gradle As it can be clearly seen, main resources of an application is located within app directory. Inside it, build folder is denoted for the files generated during deployment process. Folder named libs contains the third-party libraries required in the project. This project uses the SDK library for handling Bluetooth Low Energy beacons, manufactured and provided by Estimote Inc.28 Inside the folder /app/src/main, there are two at most important folders for the project, with the majority of the source code specific for rDesk mobile application: • java/com.example.jac.rdesk - every Java class, Activity, Service, Adapter, etc. from the project is located in this package • res - folder consisting of all multimedia-like resources used in application: – anim - one can find XML files here with the description of animationtransitions used:

28

Estimote Inc. - http://estimote.com/

91


1. <?xml version=”1.0” encoding=”utf-8”?> 2. <set xmlns:android=”http://schemas.android.com/apk/res/ android” 3. android:fillAfter=”true” > 4. 5. <alpha 6. android:duration=”1000” 7. android:fromAlpha=”0.0” 8. android:interpolator=”@android:anim/accelerate_ decelerate_interpolator” 9. android:toAlpha=”1.0” /> 10. 11. </set> Listing 33: XML Animation - /res/anim/fade_in.xml.

– drawable, drawable-hdpi... - XML-based shapes or graphics distinguished to density of given device’s screen. – drawable, drawable-hdpi... - XML-based shapes or graphics distinguished to density of given device’s screen. – layout - XML-based layouts for a specific activities – layout - place where constant values are specified as XML files. For example: details of strings.xml look as follows: 1. <?xml version=”1.0” encoding=”utf-8”?> 2. <resources> 3. <string name=”app_name”>RDesk</string> 4. <string name=”hello_world”>Hello world!</string> 5. <string name=”action_settings”>Settings</string> 6. <string name=”title_activity_register_visit”>RegisterVisitActivity</string> 7. </resources> Listing 34: Constant string values used in application - /res/values/strings.xml.

4.6.3 Activities Activities are the main units of the Android application loosely bound with each other, which are the components providing a screen the user can interact with [17]. Activity itself has its own lifecycle, which is being gone through, during the application life: Each square in the lifecycle (Figure 19) stands for the callback invoked in the activity’s source code in order to handle the state change: 92


1. 2. 3. 4. 5.

@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } Listing 35: State change callback - onCreate().

Graphical User Interface of Activity can be either designed through the creator provided in Android Studio or described by XML file in /app/src/res/layout path: 1. <?xml version=”1.0” encoding=”utf-8”?> 2. <LinearLayout 3. android:orientation=”vertical” 4. android:layout_width=”fill_parent” 5. android:layout_height=”fill_parent” 6. android:background=”@color/brand_primary” 7. xmlns:android=”http://schemas.android.com/apk/res/android”> 8. 9. <LinearLayout xmlns:android=”http://schemas.android. com/apk/res/android” 10. android:orientation=”vertical” 11. android:layout_width=”match_parent” 12. android:layout_height=”match_parent”> 13. 14. <RelativeLayout 15. android:layout_width=”match_parent” 16. android:layout_height=”0dp” 17. android:orientation=”vertical” 18. android:layout_weight=”2”> 19. 20. {...} 21. 22. </RelativeLayout> 23. 24. {...} 25. 26. </LinearLayout> 27. 28. </LinearLayout> Listing 36: Sample Activity layout.

Due to the style of positioning elements in a layout, several layouts are distin- guished:

93


• RelativeLayout - elements are positioned relatively to each other or to the parent • LinearLayout - children of this layout are positioned within one column or one row • GridLayout - elements of this layout are placed in a rectangular grid • WebView - layout mode enabling developers to load websites to given container

4.6.4 AndroidManifest.xml Document with essential information about application, required prior to the initial launch of application: 1. <?xml version=”1.0” encoding=”utf-8”?> 2. <manifest xmlns:android=”http://schemas.android.com/apk/ res/android” 3. package=”com.example.jac.rdesk” > 4. 5. <uses-permission android:name=”android.permission. BLUETOOTH” /> 6. <uses-permission android:name=”android.permission. BLUETOOTH_ADMIN” /> 7. <uses-permission android:name=”android.permission. INTERNET” /> 8. 9. <application 10. android:allowBackup=”true” 11. android:icon=”@drawable/ic_launcher” 12. android:label=”@string/app_name” 13. android:theme=”@style/AppTheme” > 14. <activity 15. android:name=”.MainActivity” 16. android:label=”@string/app_name” 17. android:theme=”@android:style/Theme.NoTitleBar” > 18. <intent-filter> 19. <action android:name=”android.intent. action.MAIN” /> 20. 21. <category android:name=”android.intent. category.LAUNCHER” /> 22. </intent-filter> 23. </activity> 24. 94


25. <service 26. android:name=”com.estimote.sdk.service.BeaconService” 27. android:exported=”false” /> 28. 29. <activity 30. android:name=”.RegisterVisitActivity” 31. android:label=”@string/title_activity_register_visit” 32. android:parentActivityName=”.MainActivity” > 33. <meta-data 34. android:name=”android.support.PARENT_ACTIVITY” 35. android:value=”com.example.jac.rdesk. MainActivity” /> 36. </activity> 37. </application> 38. </manifest> Listing 37: AndroidManifest.xml.

Following actions are performed at lines: • 5-7 - access to the specific resources of the device are prescribed here. They are provided to user before installation, at modal window in Google Play29, which one can deny or accept. • 9-13 - basic information about application: icon, name, used system theme, etc. • 14-23 - list of activities in application. Starting activity is specified within <intent-filter> tag

4.6.5 Application deployment Deplyoment process is supported by Gradle - project automation tool responsible for dependencies management and targeting the application for specific version of the Google Android. Application dependencies and other requirements are spec- ified in build.gradle file, located in /app/src folder. After deployment, APK package (appname.apk), ready to be installed on targeted devices and ready for certification process at Google Play, is located in /bin/ folder in a root directory of the project.

29

Google Play - https://play.google.com/

95


4.7 Project state, Use Cases and Future Improvements

Figure 20: rDesk dashboard runs seamlessly on every device (source: J.Adamczyk). 96


4.7.1 Project State and Use Cases By the date this paper is finished, the state of this project is as follows: • Patients can interact with exposed rDesk API through the website forms and native mobile application installed on Google Android 4.3+ devices enabled to communicate with Bluetooth Low Energy Devices. They can express a willing for being examinated by registrating the visit with initial waiting or registered status. • Doctors/Clinic administration workers have the dashboard web-based application provided. It works seamlessly on desktop computers, tablets and other mobile devices. It enables the medical staff to create administrative accounts, register patient visits and manage the stored data and real queues, print out documents from stored templates. Every user profile data (e.g., visits specific for given doctor/clinic) is separated from the other profiles.

4.7.2 Future Improvements Possible list of features applicable in the future to the rDesk project are almost endless: extended visits and patients data management, notifying patients waiting in the queue about approximate time of service and about actual position in the queue, communication between medical staff/doctors and sharing common required data , creating the visit history of given patient and enabling him/her to view it online and many, many more. As the project is still in the development mode, one necessary improvement has to be introduced in the future - deploying the application to one of the fast, scalable and reliable Platform as a Service (PaaS) solutions available in the cloud (e.g., Amazon Web Services, Heroku, Open Stack, etc.) From the „real-world” point of view - rDesk concept is already really close to be implemented in reality. However, one main problem can be predicted - conflict between registered, waiting and regular patients and difficulties with managing the queue when all of the mentioned group of patients will „confront” each other in front of a medical reception desks: • Which patients should be serviced faster and which not? Why? • How to deal with extreme situations - when number of the patients is going to drastically exceed the average daily amount? • How to confirm both sides of the system users about the actual date of visit and make the conversion rate „registered-served” close to 100%? This and many more questions have to be answered, but their scope is far away from the scope of this paper.

97



5. Co nclu sion



5. Conclusion This paper tried to pointing out an urgent-to-solve problem still existing in the era of ubiquitous digital services, altogether with revealing the extremely wide spectrum of branches needed to be at least „touched”, in order to provide a comprehensive solution of such problem. Field of web and mobile applications evolves at extremely fast pace and it is not likely that it will slow down in the nearest future. Every single day developers are deploying vast of application „to the cloud” and reveal more and more aspects, where their work could become automated or at least speeded up. Hence, tools like Grunt, Gulp, Bower, NPM, Gradle will be area of interest of even bigger audiencies. Internet of Things is not a concept anymore, it is already a reality. The numbers of devices with IP address assigned is becoming out the human control. They are measuring, sensing, collaborating, just to make our lives better. Technology leaders, entrepreneurs, Research and Development secenter and developers need to be altogether aware of that fact and are in request of trying to „pull out” the maximum of the possibilities it gives to mankind, it’s quality of life and health. This paper alongside with the designed project tried to show one possible improvement in that area, connecting many available tools and ideas between themselves into one product. Worth to mention at the end - current recipient desks in polish hospitals are still obliged to mantain medical data in a paper form. Altough the national polish system named an Electronic Platform of Collecting, Analysing and Sharing Digital Medical Records P1 [28] is aiming to completely discard manually written documentations, in author’s opinion this process can be still long and painful. One can imagine, how the level of healthcare, in Poland and in majority of other countries, could increase if such complete platform existed.

101


References Books, white papers: [1] Stuart K. Williams, IrDA - Past, Present and Future, Network Technology Department HP Laboratories Bristol, 1999 [7] T. Hughes-Croucher, M. Wilson, Node: Up and Running, O’Reilly Media, 2012 [8] B. Green, S. Seshadri, AngularJS - Less Code, More Fun, and Enhanced Productivity with Structured Web Apps, O’Reilly Media, 2013 [13] Frank Leymann, HTTP - lecture handouts, University of Stuttgart, 2014 [14] Bluetooth SIG, Specification of the Bluetooth System, Bluetooth SIG, 2013 [15] Julio Villegas, Bluetooth Low Energy Version 4.0. Helping create the “internet of things”, 2013 [18] T. Parker, TCP/IP, Helion, 1997 [20] P. Saint-Andre, D. Crocker, M. Nottingham, Deprecating the „X-” Prefix and Similar Constructs in Application Protocols, Internet Engineering Task Force (IETF), June 2012 [21] ECMA International, ECMAScript Language Specification, ECMA International, June 2011 [22] D. Crockford, The application/json Media Type for JavaScript Object Notation (JSON), Network Working Group, July 2006 [23] R. T. Fielding, R. N. Taylor, Principled Design of the Modern Web Architecture, ACM Inc., 2002 [29] H. Yaapa, Express Web Application Development, Packt Publishing, 2013

Online materials: [2] Nanci Taplett, Bluetooth Smart Technology—From Trend to Standard, May 2014; www.blog.bluetooth.com/bluetooth-smart-technology-from-trend-to-standard/ [3] Fitbit Flex, www.fitbit.com/flex [4] Tile, www.thetileapp.com [5] Estimote Inc., www.estimote.com [6] ISBNews, Fortinet: jedynie 41 proc. szpitali deklaruje gotowość do I etapu informatyzacji, May 2014, www.pb.pl/3548117,97373,fortinet-jedynie-41-proc.-szpitali-deklaruje-gotowosc-do-i-etapu-informatyzacji [9] AngularJS Data Binding, www.docs.angularjs.org/guide/databinding [10] AngularJS Directives, www.docs.angularjs.org/guide/directive 102


[11] EmberJS Data - Github Page, www.github.com/emberjs/data [12] V8 JavaScript Engine, google.com/p/v8/ [16] Andy Cavallini, iBeacon Bible 2.0, www.meetingofideas.files.wordpress. com/2014/06/ibeacon-bible-2-0.pdf [17] How iBeacons could change the world forever, www.washingtonpost.com/blogs/ innovations/wp/2014/01/07/how-ibeacons-could-change-the-world-forever/ [19] HTTP Gallery - HTTP Headers, www.httpwatch.com/httpgallery/headers/ [24] Multiple authors, Mozilla Developer Network - Strict mode, www.developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode [25] Hashbang and HTML5 Modes, www.docs.angularjs.org/guide/$location [26] Kimberly A. Whitler, Is 2014 Finally The Year Of Mobile?, www.forbes.com/sites/ kimberlywhitler/2014/02/06/is-2014-finally-the-year-of-mobile/ [27] Activities, www.developer.android.com/guide/components/activities.html [28] Projekt P1 - Elektroniczna Platforma Gromadzenia, Analizy i Udostępniania zasobów cyfrowych o Zdarzeniach Medycznych, www.p1.csioz.gov.pl

103



Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.