• Non ci sono risultati.

Development of a Cross-Platform Mobile Application and an Image Cloud Storage for an IoT System

N/A
N/A
Protected

Academic year: 2023

Condividi "Development of a Cross-Platform Mobile Application and an Image Cloud Storage for an IoT System"

Copied!
89
0
0

Testo completo

(1)

I ng e g ne r i a I nf o r mat i c a ( Co mput e r Eng i ne e r i ng )

Te s i di Laur e a Magi s t r al e

De ve l o pme nt o f a Cr o s s - Pl a t f o r m Mo bi l e Appl i c a t i o n a nd a n I ma g e Cl o ud St o r a g e f o r a n

I o T Sys t e m

Advi s o r s

Pr o f . Da ni e l e Tr i nc he r o

I ng. Gi ovanni Paol o Col uc c i

Ana La ur a TULA

APRI L 2 0 1 8

(2)
(3)

The iXemWine platform, developed by the research group from the iXem Laboratory,useswirelesstechnology applied to precision agriculture in ruralareas thatallowswineproducerstomonitortheirvineyardsthrough aweb application.

Given the widespread use ofsmartphones,there wasa need to create a mobile application to help the visualization the data collected from differentsensorsin a meaningfulway.The two main mobile operating systems,Android and iOS,uses both distinctlanguagesto create native applicationswhich are fastand optimized, butthisleadsto a duplication ofthecodebase.Therearecross-platform solutions aim to simplify thisproblem by using a singleprogramming languagefordeveloping applicationsthataretargeted formultipleplatforms.

Themain goalofthisprojectisto develop a cross-platform mobileapplication with a focus on the Android operating system using ReactNative,a JavaScript framework forwritingnatively renderingmobileapplicationsforiOS and Android.

Thegoalofthesecond partoftheprojectisto investigatethedifferentoptions forcloud storageserviceand develop a possiblesolution to storethepicturestaken by thesensor’scameraand visualizethem in theapplication.

(4)

Iwould liketo thank my family,fortheirunconditionalsupport,forguiding me,for theirinfinitepatienceand forallowing meto find my path in life.Thisthesisisthe culmination ofa long journey thathascertainly notbeen easy one,and would not havebeen possiblewithoutthem.

To my mother,forbeing my role modeland pushing me to be betterand whata betterway tothank you thatwritingthisthesisin English.

To my father,who hasshaped theperson Iam today and who took meto my first computerlesson asakid withoutknowingIwould follow thatcourse.

Tomy siblings,forputtingup with meand alwayshavingmy back.

Tomy grandmother,minona,who isalwayswith me.

To my aunt,mitía Ester,Juana and milategrandmother,minona Clara,who were abigpartofmy lifegrowingup and alwaysshowed theirsupport.

To my lifelong friendswho,despitethetimeand distance,arealwayspresentand to thenew ones,my family during theseyears,with whom Ishared thisexperienceand haveunforgettablememories.

At last but not least,Iwould like to thank the whole iXem Laboratory team, specially my thesisAdvisors,Prof.Trinchero and Ing.GiovanniColucci,fortheir guidancethroughoutthedevelopmentofthethesis.

(5)

1Introduction...1

1.1Introduction...1

1.2 ThesisGoals...1

1.3Generaloverview oftheiXemWinePlatform...1

2Cross-platform vsNative...3

2.1Native...3

Benefits...3

Drawbacks...3

2.2Cross-platform...3

Drawbacks...4

Benefits...4

3Javascript...5

3.1ECMAScript...5

3.2Transpilers...5

3.3Polyfill...6

3.4Modules...6

3.5Bundling...7

3.6Minification...7

3.7JavaScriptenvironments...7

3.7.1 Node...8

3.8Metro...9

3.8.1 TheJourney toaBundle...9 4React...11 4.1TheDOM...11 4.2React...11 4.2.1 Component...12 4.2.2 ComponentLifecycle...13 Mount...14 Update...14 Unmount...14 4.2.3 Refs...14 CreatingRefs...15 Accessing Refs...15 4.2.4 Higher-OrderComponents...16 4.2.5 Reconciliation...16 5ReactNative...18 5.1Internals...18 5.1.1 ThreadingModel...18 5.1.2 Bridge...19 5.1.3 JavaScriptEnvironment...19 5.1.4 JavaScriptSyntax Transformersand Pollyfills...19 5.2Differenceswith ReactWeb...20

(6)

5.3.2 UserInterface...22 5.3.3 ListViews...22 5.3.3.1 FlatList...22 5.3.3.2 SectionList...23 5.3.4 iOS/Android specific...23 5.3.5 Others...24 5.3.5.1 Animated...24 Interpolation...25 Handlinggesturesand otherevents...25 5.3.6 Style...25 5.3.7 DirectManipulation...26 5.3.8 Installation...26 5.3.8.1 Dependencies...26 5.3.9 ReactNativeCLICommands...28 5.3.10 TheCLI...30 5.3.11 Debugging...30 5.3.12 Linkinglibraries...30 6DataVisualization...32 6.1ScalableVectorGraphics(SVG)...32 6.2D3.js...33 6.2.1 D3-scales...33 6.2.2 D3-shape...33 6.2.3 D3-array...33 7Implementation...34 7.1Actorsofthesystem...34 7.1.1 Community...35 7.2Functionality...35 7.2.1 Authenticate...36 7.2.2 VisualizethelistofVineyards...37 7.2.3 VisualizetheNodesand CamerasinsideaVineyard...38 7.2.4 VisualizetheSensorsdatain Charts...39 7.2.5 Visualizethepicturestaken by aCamera...42 7.2.6 Search forvineyardsin theCommunity...43 7.2.7 Editpreferencesansseetheprofile...44 8Application Navigation...46 8.1ReactNavigation...46 8.1.1 Navigator...46 8.1.2 Authentication flow...46 8.1.3 App containers...47 8.1.4 Navigation Prop...47 8.1.5 Passingparameterstoroutes...48 8.1.6 Handling state...48 8.1.7 Navigation lifecycle...48 8.1.8 Application navigation...49

(7)

9.2Redux...52 9.2.1 CombiningReducers...53 9.2.2 React-redux...54 9.2.3 AsyncRequests...54 9.2.4 Redux Thunk...54 9.2.5 PersistingState...55 9.2.6 Application State...55 10 Web Services...58 10.1.1 Promises:...58 10.1.2 Async/Await...58 10.1.3 JSON Web Token...59 10.1.4 Moment...60 10.1.5 DataTransformations...61 11 Deploy...62 11.1GeneratingSigned APK...62 11.2GeneratethereleaseAPK...62 12ImageCloud Storage...63 12.1Own cloud infrastructure(In-house-servers)...63 12.2Amazon cloud service...63 12.3Functionalitiestoprovide...64 12.3.1 Authentication...65 12.4Flask...66 Routing...66 HTTP methods...66 TheResponseobject...67 12.5SQLAlchemy...68 12.6Amazon SimpleStorageService...68 12.7AWS Command LineInterface...69 12.8Boto3...69 CreatingClients...69 12.8.1.1 Upload aFile...70 12.8.1.2 Generateapre-signed URL...70 12.9Proposed Solution...71 13 Conclusion...72 13.1Futurework...72 14 References...73

(8)

Illustration 1.3.1:Overview oftheApplication...2 Illustration 4.2.1:Lifecyclediagram...13 Illustration 4.2.2:Commonly used lifecyclemethods...13 Illustration 4.2.3:High OrderComponent...16 Illustration 5.1.1:TheThreadsand theBridge...18 Illustration 5.3.1:ScrollView parts...21 Illustration 5.3.2:Android platformsinstalled...27 Illustration 5.3.3:Projectstructure...28 Illustration 5.3.4:Optionsforcommandsavailablein thecurrentProject...30 Illustration 7.1.1:Representation ofauser’sdata...35 Illustration 7.2.1:UseCases...36 Illustration 7.2.2:LoginScreen:Authentication oftheuser...37 Illustration 7.2.3:Visualization ofthelistofvineyards...38 Illustration 7.2.4:Visualization ofsensorsand camerasin avineyard...39 Illustration 7.2.5:Visualization ofthetemperatureand thedew pointofa

Temperature-Humidity Sensor...41 Illustration 7.2.6:Visualization ofthehumidity ofaTemperature-Humidity Sensor ...41

Illustration 7.2.7:Visualization ofaTwoLayerLeafWetnessSensor...42 Illustration 7.2.8:Photogrid visualization ofthepicturestaken by acamera...43 Illustration 7.2.9:Search and visualization ofthevineyard'sposition...44 Illustration 7.2.10:User'sprofileand languagechangescreen...45 Illustration 8.1.1:Application Navigation...50 Illustration 9.1.1:Flux achitecture...52 Illustration 9.2.1:Redux flow...53 Illustration 9.2.2:Application State...56 Illustration 9.2.3:Actionsand Screens...57 Illustration 10.1:Token-based Authentication...60 Illustration 12.2.1:Camerabackend architecture...64 Illustration 12.5.1:DatabaseforCloud ImageSystem...68 Illustration 12.9.1:Proposed Solution forCloud ImageSystem...71

(9)

Table5.3.1:Main propertiesofFlex...26 Table12.3.1:Backend functionalities...65

(10)

Listing 5.3-1:ReactNativeCLIinstallation...28 Listing 5.3-2:Creation ofanew ReactNativeProject...28 Listing 5.3-3:Launch theapplication in an Android deviceoremulator...29 Listing 5.3-4:Launch theapplication in iOS deviceoremulator...29 Listing 5.3-5:Command toverify theconnected smartphones...29 Listing 5.3-6:Linkinganativelibrary...31 Listing 8.1-1:Navigatetoaanotherscreen and passparameters...48 Listing 8.1-2:Read aparameter...48 Listing 9.2-1:Function prototypeforamiddleware...54 Listing 10-1:Pseudocodeforcalculating thesignature...59 Listing 10-2:Gettingcurrentdateand time...60 Listing 10-3:Initialization with specificdate...60 Listing 11.2-1:CommandstogeneratetheAPK...62 Listing 12.4-1:MinimalFlask application...66 Listing 12.4-2:ExampleofGET and POST method...67 Listing 12.4-3:Exampleofquery string...67 Listing 12.4-4:make_responseexample...67 Listing 12.8-1:Createaclient...69 Listing 12.8-2:Upload afile...70 Listing 12.8-3:Generateapresigned URL toreturn totheclient...70

(11)
(12)

1 I nt r oduc t i o n

1. 1 I nt r o duc t i o n

TheInternetofThings(IoT)[1]providesefficientresourceutilization whilereducing the human intervention to increase the productivity.Within an IoT system a wirelesssensornetwork (WSN)[2]can beused.A WSN isa network ofdevicesthat can communicatetheinformation gathered from a monitored field through wireless links.Thedata isthen forwarded through multiplenodes,and with a gateway,the dataisatlastforwarded toa Server,which exposesa RESTfulAPIfortheclientsto use.

Theaim oftheiXemWine[3]platform iscollecting data from thecropsforprecision agriculture.Thisallowswineproducersto benefitfrom theadvantagesofIoT and to monitortheirvineyardsthrough a web application.

Given the widespread use ofsmartphones,there was a need to create a mobile application to help the visualization the data collected from differentsensorsin a meaningfulway.

1. 2 The s i s Go al s

Themain goalofthisprojectisto develop across-platform mobileapplication with a focus on the Android operating system using React Native[4], a JavaScript[5] framework for writing natively rendering mobile applications for iOS[6] and Android[7].

Thegoalofthesecond partoftheprojectisto investigatethedifferentoptionsfor cloud storageserviceand develop a possiblesolution to storethepicturestaken by thesensor’scameraand visualizethem in theapplication.

1. 3 Ge ne r al ove r vi e w of t he i Xe mWi ne Pl at f or m

Theplatform iXemWineisa Low-PowerWide-Area Network[8],with sensorsableto transmitinformation over long distances,even in non-line ofsight,by meansof unlicensed frequencies.

When data isreceived by Gateways,itissequentially forwarded to the Network Serverusingstandard TCP/IP[9]connections.

(13)

Theapplication Server,written in Python[10],receivesdata by theNetwork Server using theMQTT[11]protocol.The serveralso providesa RESTFul[12]API[13],as shown in Illustration 1.3.1,thatcan beused to retrievealltheinformation by means ofHTTP[14]requests.

TheREST APIreturnsdatain alanguage-independentformatthatclientscan easily consume,this allows the interaction with many interfaces and a consistent user experience.

Illustration 1.3.1:Overview ofthe

Application

(14)

2 Cr os s - pl at f or m vs Na t i ve

2. 1 Nat i ve

Nativeapplicationsaretheonesthataredeveloped exclusively fora specificplatform and itsOperating System in a languagecompatiblewith them,forexample,theiOS devicesuseObjective-C[15]orSwift[16]while theAndroid devicesusesJava[17]or Kotlin[18].

Be ne f i t s

• Developed forthespecificplatform,they arefastand responsive.

• Theplatform’ssoftwaredevelopmentkit(SDK)allowsaccessto allthedevice APIs.

• Platform comeswith familiarand originaluserinterface(UI)components.

• Allowsuseofdevice-specificfunctionalities.

• Android and iOS have large communitiesbehind them.Ifthere’sa frequent problem,itishighly likely to find a ready-made solution in the form ofa third-party library oran API.

Dr awba c ks

• Requiresseparatedevelopmentprocessesforevery platform,sincethecodefor oneplatform only worksforthatplatform.

• With differentcodebases,itisalwaysdifficultto releasesamefeatureson all platformsatthesametime.

• Thecostofdevelopmentand maintenanceofthemobileapplication ishigh.

2. 2 Cr os s - pl a t f or m

Cross-platform mobile applications are developed using an intermediate language thatisnotnativeto thedevice’soperating system.Thismeansthatsome,orall,of thecodecan beshared acrossplatforms– forinstance,acrossboth iOS and Android.

To build mobile applications,the cross-platform frameworksprovides a platform- independent API that uses a programming language, like JavaScript that the developersuse to build the mobile application,including the userinterface,data persistenceand businesslogic.

(15)

Thosesolutionscan besplitintotwocategories:

• HTML5 based (PhoneGap[19],Apache Cordova[20],Ionic[21]):Developers createmobileapplicationsusing web technology,they load a mobilebrowser in the application and perform alllogic operations within that browser, offeringalso added functionalitiesthattraditionalweb technology doesnot.

• Native Widget based (React Native): Developers can use JavaScript to constructtheirapplication from componentsthatare subsequently mapped into the platform specific widgets. In order to use native widgets, the JavaScriptpartofthe application hasto communicate with the native part through a“bridge”.

Dr awbac ks

• Not as many third-party components, also some of them might behave differently than expected.A lotofcomponentshavesmallcommunitiesbehind them,and thecreatorscan’talwaysupdatethem frequently.

• Notasefficientasanativeapplication.

• Limited deviceAPIaccess.

Be ne f i t s

• ReactNativeprovidesnearly identicalperformancetonative.

• ReactNative actually rendersusing itshostplatform’s standard rendering APIs,which enables itto stand outfrom mostexisting methodsofcross- platform application development.

• Currently popularamongmobileapplication developers.

• Itsecosystem isexpandingrapidly every day alongwith new features.

• Thedevelopmenteffortislowersincethereisa high percentageofthecode thatcan bereused.

Taken into accountallofthis,a decision wasreached to choose a cross-platform approach using the ReactNative framework forthe developmentoftheiXemWine mobileapplication.

(16)

3 Java s c r i pt

JavaScriptisa high-level,interpreted programming language thatconformsto the ECMAScriptspecification.Itischaracterized asdynamic,weakly typed,prototype- based and multi-paradigm.JavaScriptisprimarily aclient-sidelanguage.

The vastmajority ofwebsitesusesJavaScript,majorweb browsershave different dedicated JavaScriptenginesto interpretand executethecode(orusessomesortof lazy compilation),forexample:

• Chrome[22]and Node[23]:V8[24]

• Firefox[25]:SpiderMonkey[26]

• Safari[27]:JavaScriptCore[28]

• MicrosoftEdge[29]/IE[30]:Chakra[31]

They each implementthe ECMAScriptstandard,butmay differforanything not defined by it.

3. 1 ECMASc r i pt

ECMAScriptisthestandard upon which JavaScriptisbased.ECMAScript2015[32], also known asES6,isa fundamentalversion ofthe standard.Since a long time passed between thepreviousrelease,thisreleaseisfullofimportantnew featuresand majorchangesin suggested bestpracticesin developingJavaScriptprograms.

Thisupdateaddssignificantnew syntax forwriting complex applications,including classesand modules,which simplifiesthedefining ofcomplex objectswith theirown prototypes.Other new features include iterators and for/op loops,Python-style generators,arrow functions,binary data,typed arrays,collections(maps,setsand weak maps),promises,numberand math enhancements,reflection,proxies(meta- programmingforvirtualobjectsand wrappers)and templateliterals.

3. 2 Tr a ns pi l e r s

Transpilers,orsource-to-source compilers,aretoolsthatread sourcecodewritten in oneprogramminglanguage,and producetheequivalentcodein anotherlanguage. Asstated previously,every browserusesa differentJavaScriptengineand each one, has:

(17)

• differentperformancecharacteristics

• implementsadifferentsubsetofES2015features

• isapproachingfullcompliancewith thespecatdifferentrates.

Thatmeansthat,somefeaturesworksfineforthoseusersrunning themostrecent Chrome,Firefox,orSafari,butitwon'twork forusersrunning olderversions,orfor anyoneusingInternetExplorer.

Kangax[33] created an ES6 compatibility table where developers can track the supportofvariousES6 featureson variousJavaScriptengines,theES6 compatibility table[34]showsthattherewasa clearprogress,butitisnotquitetimeto writeES6 directly.Instead,developerswritesourcecodein ES6,and letatranspilertranslateit to plain ES5thatworksin every browser.

One ofthe most populartools is Babel[35],a tool-chain mainly used to convert ECMAScript 2015 code into a backwards compatible version ofJavaScript that worksboth in currentand olderbrowsersorenvironments.

Babel also has plugins available to provide specific conversions used in web development.For example,developers working with React[36],can use Babelto convert JSX[37] (JavaScript eXtension) markup into JavaScript using the Babel preset"react".

3. 3 Pol yf i l l

When Babelcompilesthecode,istaking thesyntax and running itthrough various syntax transformsin orderto getbrowsercompatible syntax.Butitisnotadding any new properties needed to the browser’s globalnamespace or any JavaScript primitive.Thiscan beachieved by usingapolyfill.

A polyfilliscodethatdefinesa new objectormethod in browsersthatdon’tsupport them natively.A polyfillcan be used to implementvariousbrowserfeaturesother than ECMAScript standards,for example SVG[38],Canvas,Web Storage (local storage/session storage)amongothers.

3. 4 Modul e s

Almostevery languagehasa conceptofmodules— a way to includefunctionality declared in one file within another.Typically,a developercreatesan encapsulated library ofcoderesponsibleforhandling related tasks.Thatlibrary can bereferenced by applicationsorothermodules.

(18)

Thebenefitsofusingmodules:

• codecan besplitintosmallerfilesofself-contained functionality.

• Thesamemodulescan beshared acrossany numberofapplications.

• Codereferencing a moduleunderstandsit’sa dependency.Ifthemodulefileis changed ormoved,theproblem isimmediately obvious.

• Modulecodehelpseradicatenamingconflicts.

ES6 introduced built-in modulesthatoffersup a variety ofalternativesforimporting and exportingmodules.

3. 5 Bundl i ng

Bundling isthe processoffollowing imported filesand merging them into a single file:a “bundle”.In web developmentthebundling,orthe“concatenation” ofallthe filesinto onebig file(ora couplefilesasthecasemay be)isin orderto reducethe numberofrequests.Thisisreferred asthe“build step”or“build process”.

3. 6 Mi ni f i c at i on

Minification isthe processofremoving allunnecessary charactersfrom the source codesofinterpreted programming languagesormarkup languageswithoutchanging their functionality. These unnecessary characters usually include white space characters,new linecharacters,comments,and sometimesblock delimiters,which are used to add readability to the code but are not required for it to execute. Minification reduces the size ofthe source code,making its transmission over a network moreefficient.

3. 7 JavaSc r i pt e nvi r onme nt s

Nowadays,therecan beconsidered mainly threetypesofJavaScriptenvironments: 1)Client-side browser JavaScript: Scripts written in JavaScript that are

embedded in a web page'sHTML and run client-sideby a JavaScriptengine in theuser'sweb browser.

2)Client-side native JavaScript:Mostdevicescan have a JavaScriptrun-time, therefore,developers can ship JavaScript files with Android/iOS/Desktop applications and then run them there.These engines also support adding

(19)

“hooks” from JavaScriptinto the native code,and that'show ReactNative provideitsAPI.

3)Server-side JavaScript:Server-side JavaScriptrefersto JavaScriptthatruns on server-side and is therefore not downloaded to the browser. Server generally hastwomeanings:

◦ A pieceofsoftwarethatlistensfornetwork requestsand then respondsto them.

◦ A computerrunningsuch apieceofsoftware.

Nodeisa toolthatcan beeitherofthose,and also allowsto useJavaScriptfornon- serverand non-web purposes.

3. 7. 1 Node

NodeisaJavaScriptrun-timeenvironmentbuilton Chrome’sV8Javascriptengine. Generally,the serveritselfisrun directly from Node(e.g.with theHTTP built-in module)ratherthan being embedded in anotherserverlike Apache[39](asismost common forPHP[40]).In thiscase,a browserdoesn'tneed to beinvolved atall.If oneis,then itwillprobably beoneacting asa clientand making a requestto the server.

A fourth casecan beadded tothepreviousenvironments: 4)Build-scriptsrunningon runtineslikeNode

Developerscan use JavaScriptto generate JavaScriptfiles,thatis,to build and combine severalJavaScriptfilesinto a single file,and transpile itifneeded.This processishow tobundlethefilesfor(1)and (2)and maybealso (3).

Metroisa server-sidebuild-script(which runson Node)thatisused by ReactNative to work asa:

• DevelopmentServer:Starta serverthatservesJavaScriptcodeasa web page would (1& 3).During thedevelopmentstageitallowsto iteratequickly on a deviceby connectingtothedevelopmentserverrunningon themachine.

• Bundler:BundlealltheJavaScriptcodein a nativeapplication thatlatercan beinstalled on a mobiledevice(2).

(20)

3. 8 Me t r o

Metro[41]isthedevelopmentplatform forReactNative,itdoesthatby exposing a HTTP server so clients, in this case, emulators or connected devices can communicate with it and it also exposes a Websocket[42] server so it can push updatesintothem.

In development,thebundlewillcomefrom thethedevelopmentserver.Thatway if the code is changed,the server willsend a request to the client,through the Websocket,to download thenew codeorupdatethecodeon thefly.So,thebundle isdynamically generated from thesourcecode.

In production,an offlinebundleisused sincethecodeisalready on thedeviceand doesnotneed tobedownloaded.

MetroisaJavaScriptbundler.Ittakesin options,an entry file,and theoutputisa JavaScriptfileincludingallJavaScriptfilesback.

Metrohasthreeseparatestagesin itsbundlingprocess:

• Resolution:Metro needsto build a graph ofallthemodulesthatarerequired from theentry point.To find which fileisrequired from anotherfile,Metro uses a resolver. In reality this stage happens in parallel with the transformation stage.

• Transformation:Allmodules go through a transformer.A transformer is responsible for converting (transpiling) a module to a format that is understandableby thetargetplatform (eg.ReactNative).Transformation of moduleshappensin parallelbased on theamountofcoresavailables.

• Serialization:Assoon asallthemoduleshavebeen transformed they willbe serialized.A serializer combines the modules to generate one or multiple bundles.A bundle isliterally a bundle ofmodules combined into a single JavaScriptfile.

3. 8. 1 The Jour ne y t o a Bundl e

Metro isitselfa package thatisrun on Node and thatisthe reason Node isa dependency ofReactNative.Themain task isto build JavaScrip code,and thatalso entails:

• Monitoring allthe filesin the project:Using the module jest-haste-map[43] from anotherprojectcalled Jest[44] givesthe ability ofmonitoring the file system and emittingchangesevery timeitdetectschanges.In ordertoachieve

(21)

this,it uses watchman[45] ifit is installed.Watchman is an open source projectfrom Facebook which monitorthefilesystem asa daemon processso it reduces the start-up time. However if not installed, it falls back to fs.watch[46],thishasa start-up overhead butafterthatisthesameasusing watchman.

• Transform thesourcecode:Metrodoeswhatany otherbundlerdo,which isto use Babel,the difference isthe way itisexecuted.Transpilation isa very expensive process, most bundlers have a main process and execute the transpilation processonefileaftertheother.Metro usesa differentapproach, the main process doesn't transform any file,but it spawns a set ofchild processesthatare called workers.Filesare sentin parallelto each ofthese workers,so thetranspilation happensatthesame time and then return the resultback.Usually itspawnsoneworkerpercore.

• Storecache artifacts:Metro shipswith an internalmulti-layercache located insidetheMain process.Ifthefilewasnevertranspiled,itwilltranspilethe fileand saveitin thecache.

• Build bundles:Metro producesbundlesthrough serializers,which receivethe graph and can manipulatethem in any way.

• Executecodeon devices.

(22)

4 Re a c t

4. 1 The DOM

BrowsersrenderHTML to a web page,beforethishappensthey createa Document ObjectModel[47] ofthe page.The DOM is an object-oriented tree-like structure representation oftheweb page,constructed in memory,which can bemodified with ascriptinglanguagesuch asJavaScript.

A HTML documentcan have encapsulated HTML contentinside ofotherHTML content.Thebrowserwhen loading theHTML documentinterruptsand parsesthis hierarchy to create a tree of node objects that simulates how the markup is encapsulated.

Theproblem with theDOM isthatitisnotoptimized fordynamicapplications.So, updating itslowstheapplication when therearea severalthingsto bechanged;as thebrowserhastoreapply allstylesand rendernew HTML elements.

4. 2 Re ac t

Reactisan open source JavaScriptlibrary created by Facebook forbuilding user interfaces[48]. It introduces a declarative approach for building UIs that allows developersto:

• writedeclarativeviewsthat“react”tochangesin data

• abstractcomplex problemsintosmallermodulescalled components

Reactisdeclarative,in thesensethatallowsdevelopersto declarewhatthey want and thelibrary willtakecareoftheDOM manipulation efficiently,withoutworking directly with thebrowserAPI.

To minimizethenumberofcostly DOM operationsrequired to updatetheUI,React buildsand maintainsan internalrepresentation oftherendered UI.Itincludesthe Reactelementsreturned from thecomponents.Thisrepresentation letsReactavoid creating DOM nodesand accessing existing onesbeyond necessity,asthatcan be slower than operations on JavaScript objects.Sometimes it is referred to as a

“virtualDOM”.

(23)

4. 2. 1 Compone nt

Components are JavaScript functions or classes that returns a node (something Reactcan render,e.g.a <div/>)and receivesan objectofthepropertiesthatare passed to theelement.

These object,called props,are passed to a componentand used to compute the returned node.Changesin thesepropswillcause a re-computation ofthereturned node,which meansare-render.Unlikein HTML,thesecan beany JavaScriptvalue. During thedevelopmentstage,Reactcan validatethetypesofcomponentpropsat runtime.This allows developers to ensure the correct passing ofprops and help documentthecomponent’sAPIs.

Therearetwo main typesofcomponentsin React:ClassComponentsand Stateless FunctionalComponents.Themostobviousreason isthatClasscomponentsareES6 classeswhileFunctionalComponentsarefunctions.Additionaldifferencesarelisted in thefollowingTable4.2.1:

StatelessFunctionalComponent (SFC)

ClassComponent (React.Component)

• Simplestcomponent:usewhen a stateisnotneeded.

• A function thattakespropsand returnsanode.

• Should be“pure”(itshould not haveany sideeffectslikesetting values,updatingarrays,etc.)

• Any changein propswillcausethe function tobere-invoked.

• An abstractclassthatcan be extended tobehavetheway developersneed.

• Haveadditionalfeaturesthat SFCsdonot:

◦ Haveinstances

◦ Maintain theirown state

◦ Havelifecyclemethods (similartohooksorevent handlers)thatare

automatically invoked

• Renderingbecomesafunction of propsand classproperties. Table4.2.1:TypesofReactComponents

(24)

ClassComponentscan havea statewhich addsan internally-managed storageto a component.Stateisa classproperty on thecomponentinstance,this.state,and can only beupdated by invoking this.setState()and passing itan objecttobemerged,or a function ofprevious state. The calls to setState() calls are batched and run asynchronously.

Components are units containing both the rendering logic and the UIlogic and instead ofseparating them,Rect puts markup in JavaScript.So,writing React meanswriting JSX,an XML-like syntax extension ofJavaScriptthattranspilesto JavaScript,wherelowercasetagsaretreated asHTML/SVG tagsand uppercaseare treated ascustom components.Using JSX allowsto writeconciseHTML/XML-like structures(e.g.,DOM liketreestructures)in thesamefilewhereistheJavaScript code,then Babelwilltransform theseexpressionsintoactualJavaScriptcode.

4. 2. 2 Compone nt Li f e c yc l e

The component lifecycle contains three major phases: mounting, updating and unmouting.

The Illustration 4.2.2 [49] shows the order in which the most common lifecycle methodsarecalled:

Illustration 4.2.1:Lifecyclediagram

Illustration 4.2.2:Commonly used lifecyclemethods

(25)

Mount

Since class-based components are classes, the first method that runs is the constructor method.Typically,isthe place to initialize the component’sstate,or otherclassproperties,bound methods,etc.

Therender()method isthemostused lifecyclemethod.Itisin allReactclasses,this isbecause render()isthe only required method within a classcomponent.Asthe name suggests it handles the rendering ofthe component to the UI.It happens duringthemountingand updatingofthecomponent.

Reactrequiresthattherender()ispure.Purefunctionsarethosethatdo nothave any side-effectsand willalwaysreturn the same outputwhen the same inputsare passed.ThismeansthatitisnotpossibletosetState()within arender().

Now thatthecomponenthasbeen mounted and isready,componentDidMount()is called.Thisisthe place to initiate APIcalls,ifdata needsto be loaded from a remoteendpoint.Unliketherender()method,componentDidMount()allowstheuse of setState(). Calling the setState() here will update state and cause another rendering butitwillhappen before the browserupdatesthe UI.Thisisto ensure thattheuserwillnotseeany UIupdateswith thedoublerendering.

Update

Thisphase is triggered every time the state orpropschanges,which cause a re render.Themethod componentDidUpdate()can doanythingthatisn’tneeded forUI (network requests,etc.).In thislifecycle,setState()can be used,butithasto be wrapped itin a condition to check forstate orprop changesfrom previousstate. IncorrectusageofsetState()can lead toan infiniteloop.

Unmount

The unmounting phase is the last stage ofthe component lifecycle,so when a component is removed from the DOM,React invokes componentWillUnmount() rightbeforeitgetsremoved.Thismethod isused to clean up any open connections such asWebSocketsorintervals,removeeventlisteners.Thiscomponentwillnever be re-rendered and because ofthatitdoesn’tmake sense to callsetState()during thislifecyclemethod.

4. 2. 3 Re f s

Refs[50]providea way to accessDOM nodesorReactelementscreated in therender method.In the typical React data flow, props are the only way that parent componentsinteractwith theirchildren.To modify a child,re-renderitwith new

(26)

props.However,there are a few caseswhen modify a child outside ofthe typical dataflow,forexamplemanagingfocusand textselection.

Creating Refs

Refsarecreated using React.createRef()and attached to Reactelementsvia theref attribute. As Listing 4.2-1 shows, Refs are commonly assigned to an instance property when a componentisconstructed so they can bereferenced throughoutthe component.

Accessing Refs

When a refis passed to an elementin render,a reference to the node becomes accessibleatthecurrentattributeoftheref:

Thevalueoftherefdiffersdependingon thetypeofthenode:

• When therefattribute isused on an HTML element,therefcreated in the constructorwith React.createRef()receivesthe underlying DOM elementas itscurrentproperty.

• When the refattribute isused on a custom classcomponent,the refobject receivesthemounted instanceofthecomponentasitscurrent.

Listing 4.2-1:Accessa Ref

const node = this.myRef.current;

Drawing 4.2.1:Createa Ref class MyComponent extends React.Component {

constructor(props) { super(props);

this.myRef = React.createRef();

}

render() {

return <div ref={this.myRef} />;

} }

(27)

• Function componentscan notuse the refattribute because they don’thave instances.

4. 2. 4 Hi ghe r - Or de r Compone nt s

A higher-ordercomponent[51](HOC)isan advanced techniquein Reactforreusing component logic. They are a pattern that emerges from React’s compositional nature.

Concretely,a higher-order component is a function that takes a component and returnsa new component.Sinceitreturnsa new component,itaddsan extra layer ofabstraction.In thislayercan beadded state,behavior,oreven style,asshown in theIllustration 4.2.3.

Whereas a component transforms props into UI, a higher-order component transformsa componentinto anothercomponent.HOCsarecommon in third-party Reactlibraries,such asRedux’sconnect().

4. 2. 5 Re c onc i l i at i on

Reconciliation[52] isthe processby which Reactsyncschangesin the application statetotheDOM,soit:

• ReconstructsthevirtualDOM

• DiffsthevirtualDOM againsttheDOM

• Only makesthechangesneeded

Illustration 4.2.3:High OrderComponent

(28)

When a component’spropsorstatechange,Reactdecideswhetheran actualDOM update isnecessary by comparing the newly returned elementwith the previously rendered one.When they arenotequal,ReactwillupdatetheDOM.

(29)

5 Re a c t Na t i ve

A framework that relies on React for writing real, natively rendering mobile applicationsforiOS and Android using JavaScript.Thefactthatitactually renders using itshostplatform’sstandard rendering APIenablesitto stand outfrom most existingmethodsofcross-platform application development.

There are separate threads for UI, layout and JavaScript that communicate asynchronously through a “bridge”.TheJavaScriptthread can requestUIelements to beshown and ifisblocked,theUIwillstillwork.

5. 1 I nt e r na l s

5. 1. 1 Thr e adi ng Mode l

Therearetwo importantthreadsrunning in each ReactNativeapplication.Oneof them isthe main thread,which also runsin each standard native application.It handlesdisplaying theelementsoftheuserinterfaceand processesusergestures.The otheroneisspecificto ReactNative,itstask isto executetheJavaScriptcodein a separate JavaScriptengine.The JavaScriptthread dealswith the businesslogic of the application.It also defines the structure and the functionalities ofthe user interface.Thesetwothreadsnevercommunicatedirectly and neverblock each other. Ifthe application accessesany native API,itisdone on a separate native module thread.Forexample-Animationsarehandled in ReactNativeby a separatenative thread tooffload thework from theJavaScriptthread.

Illustration 5.1.1:TheThreadsand the Bridge

(30)

5. 1. 2 Br i dge

Between thetwo threadsthereisthebridge,which isthecoreofReactNative.The bridgehasthreeimportantcharacteristics[53],itis:

• Asynchronous.Itenablesasynchronouscommunication between the threads. Thisensuresthatthey neverblock each other.

• Batched.Ittransfersmessagesfrom onethread to theotherin an optimized way.

• Serializable. The two threads never share or operate with the same data. Instead,they exchangeserialized messages.

5. 1. 3 JavaSc r i pt Envi r onme nt

When usingReactNative,JavaScriptcodewillrun in twoenvironments:

• In mostcases,ReactNative willuse JavaScriptCore,the JavaScriptengine thatpowersSafari.

• When using Chromedebugging,allJavaScriptcoderunswithin Chromeitself, communicating with native code via WebSockets.Chrome uses V8 as its JavaScriptengine.

While both environments are very similar, there may end up hitting some inconsistencies.

5. 1. 4 JavaSc r i pt Synt ax Tr ans f or me r s and Pol l yf i l l s

ReactNativeshipswith theBabelJavaScriptcompiler.A fulllistofReactNative's enabled transformations can be found in metro-react-native-babel-preset, for example.It provides ES5 and ES6 transformations like arrow functions,classes, spread operator, modules and async/await,template literals,etc. Also, specific transformationslikeJSX and Flow.

Many standardsfunctionsarealsoavailableon allthesupported JavaScriptruntimes by meansofpollyfills.

(31)

5. 2 Di f f e r e nc e s wi t h Re ac t We b

• Both usesJSX fordefining componentsbutReactNativehasaseparatesetof tags,somebasecomponentsfordefininguserinterfaceformobile.

• React-Nativeisnotmadefrom web elementsand can’tbestyled in thesame way.

• NobrowserAPIs:CSS animations,Canvas,SVG,etc.,butsomehavebeen polyfilled (fetch,timers,console,etc.)

• Navigation:In a web browser,linksto differentpagesarepossibleusing the anchor(<a>)tag.When a userclickson a link,theURL ispushed to the browserhistory stack.When the userpressesthe back button,the browser popstheitem from thetop ofthehistory stack,so theactivepageisnow the previously visited page.ReactNativedoesn'thavea built-in idea ofa global history stack likeaweb browserdoes.

• Eventhandling:Unlikeweb,notevery componenthasevery interaction,there are only a few “touchable” components,like Button and TouchableOpacity.

Web handlers willreceive the event as an argument,but React Native handlersoften receivedifferentarguments.

• ReactNative’scomponentsarenotglobally in scopelikeReactweb components.

◦ Importfrom 'react-native'

• Thediv tag in web correspondsto theView tag and thespan tag to Texttag in ReactNative.Alltextmustbewrapped by a<Text/> tag.

5. 3 Compo ne nt s a nd API s

ReactNativeprovidesa numberofbuilt-in components,thefollowing arethemost importantonesused in theapplication:

5. 3. 1 Ba s i c Compone nt s

• View:Themostfundamentalcomponentforbuilding a UI.Itisa container thatsupportslayoutwith flexbox,style,and touch handling,and accessibility controls.View isdesigned to benested insideotherviewsand can have0 to many children ofany type.

(32)

• Text:A componentfordisplayingtext.

• Image:A componentfordisplaying images.There aretwo waysto load the blob data,the first approach loads the image data from the network by passing an objectwith auriproperty to source.Theotherway isusing a local imagefile,by callingrequire()and passingtheresulttosource.

• TextInput:A componentforinputtingtextvia akeyboard.

• ScrollView:Providesa scrolling containerthatcan hostmultiplecomponents and views. Is a specialkind of View that has two parts, as shown in Illustration 5.3.1:

◦ Container(the grey box),it'sthe outside View,itsheightcan'texceed 100% ofthewindow height

◦ Content(marked in blue)is the innerpart,itcan be higher than the window height,it'swhat'smoving insidethecontainer.

ScrollView’sstyle definestheoutercontaineroftheScrollView,e.g itsheight and relations to siblings elements while contentContainerStyle defines the styleoftheinnercontainerofit,e.gitemsalignments,padding,etc.

By default,ScrollView islaid outvertically.In orderto scrollthe content horizontally,theprop horizontalmustsettotrue.

Illustration 5.3.1:

ScrollView parts

(33)

5. 3. 2 Us e r I nt e r f ac e

• Button:A basicbutton componentforhandling touchesthatrender accordingly on any platform.Thereareothercomponentsthatallow a developerto customize“touchable”components.

5. 3. 3 Li s t Vi e ws

ReactNativeprovidescomponentsforpresenting listsofdata,themostimportantis FlatListsinceitisused to show theuser’svineyardsand thegrid ofpicturestaken by a camera.There isalso SectionList,a componentwith additionalsupportfor sections,itisused to display theNodesand Camerasfrom a vineyard.Both ofthese componentsareperformant.In detail:

5.3.3.1FlatList

The Flatlist[54] component displays a scrolling list of changing, but similarly structured,data.Itworkswellforlong listsofdata,where the numberofitems mightchangeovertime.UnliketheScrollView,theitonly renderselementsthatare currently showing on the screen,not allthe elements at once.The component requirestwoprops:

• data:sourceofinformation forthelist.Array ofdata used to createthelist, typically an array ofobjects.

• renderItem: takes one item from the source and returns a formatted componentto render.function thatwilltakean individualelementofthedata array and renderacomponentforit.

Each item ofthelistmusthavea uniquekey,thatallowstheVirtualizedList(which iswhatFlatListisbuilton)to track itemsand aidsin theefficiency ofthelist.The prop keyExtractorcan beuseto specify which pieceofdata should beused asthe key.

Isfully cross-platform and provides:

• Optionalhorizontalmode.

• Configurableview-ability callbacks.

• Headersupport.

• Footersupport.

(34)

• Separatorsupport.

• PulltoRefresh.

• Scrollloading.

• ScrollToIndex support.

5.3.3.2SectionList

SectionList[55]islikeFlatListbutwith additionalsupportforsections.Itrequiresa renderSectionHeaderfunction prop forsection headersand instead ofthedata prop, itdefinesectionswhereeach section:

• hasitsown dataarray

• can overridetherenderItem function with theirown custom renderer

5. 3. 4 i OS/Andr oi d s pe c i f i c

DatePickerAndroid:Opensthestandard Android datepickerdialog. Theavailablekeysfortheoptionsobjectare:

• date(Dateobjectortimestamp in milliseconds):datetoshow by default

• minDate (Date or timestamp in milliseconds):minimum date that can be selected

• maxDate(Dateobjectortimestamp in milliseconds):maximum datethatcan beselected

• mode (enum('calendar','spinner','default')):to setthe date-pickermode to calendar/spinner/default

◦ 'calendar':Show adatepickerin calendarmode.

◦ 'spinner':Show adatepickerin spinnermode.

◦ 'default':Show a default native date picker(spinner/calendar) based on android versions.

Itprovidesthe open()method,thatreturnsa Promise which willbe invoked an objectcontaining action,year,month (0-11),day iftheuserpicked adate.

(35)

Thiscomponentisused to givetheusertheoption to display thedata ofthesensor on thatselected date.

5. 3. 5 Ot he r s

5.3.5.1Animated

Animation can be defined asmanipulating imagesorobjectsto appearasmoving. ReactNative providesthe Animated library forcreating animations,itallowsto declarea computation in JavaScriptand computeiton thenativethread and noton theJavaScriptthread,so iftheJavaScriptthread isblocked,theanimation willstill run.

Thestepsareusually asfollows:

1)Create a new Animated instance and define the starting value orthe starting location oftheanimation in referenceto theexactX,Y coordinateson thescreen.

TheX,Y coordinatesalwaysstartatthetop-leftcornerofthescreen.

2)Definetheend valueorending location oftheanimation.Animated hasbuilt-in typesto use to getfrom the starting location orvalue to ourending location or value.Each animation typeprovidesa particularanimation curvethatcontrolshow thevaluesanimate:

• Decay:startswith an initialvelocity and gradually slowstoastop.

• Spring:providesasimplespringphysicsmodel.

• Timing:animatesavalueovertimeusing easingfunctions.

3)Definewhich elementto animate.ReactNativeprovidesfourcomponents.These componentsdo thebinding oftheanimated valuesto theproperties,and do targeted native updatesto avoid the costofthe reactrenderand reconciliation processon every frame.

• Animated.Image

• Animated.ScrollView

• Animated.Text

• Animated.View

(36)

Interpolation

Interpolate()isa method thatisavailable to be called on any animated value,it interpolatesthevaluebeforeupdatingtheproperty,e.g.mapping0–1to0–10.Allows inputrangesto map to differentoutputranges.

Handling gesturesand otherevents

Gestures,like panning orscrolling,and othereventscan map directly to animated valuesusing Animated.event().Theanimated eventshelp to extractthevaluesfrom complex eventobjects.

5. 3. 6 St yl e

ReactNativeusesJavaScriptobjectsforstyling,whereobjectkeysarebased on CSS properties.Every componentacceptsa “style” prop where these are defined.The styleprop can takean array ofstyles.

Additionally,ReactNativeprovidestheStyleSheetfunctionally,which isthesameas creating the objectsforstyle,buthave an additionaloptimization:only sendsIDs overthebridge.

A componentcan specify the layoutofitschildren using the Flexbox algorithm.

Flexbox isdesigned toprovideaconsistentlayouton differentscreen sizes.

Flexbox worksthesameway in ReactNativeasitdoesin CSS on theweb,with a few exceptions.The defaultsare different,with flexDirection defaulting to column instead ofrow,and theflex parameteronly supportingasingleunit-lessnumber. Toachievethedesired layout,Flexbox offersthreemain properties:

(37)

Property Values Description

flexDirection 'column','row' Used tospecify ifelementswillbe aligned vertically orhorizontally.

justifyContent'center','flex-start','flex-end','space- around','space-between'

Used todeterminehow should elementsbedistributed insidethe container.

alignItems 'center','flex-start','flex-end', 'stretched'

Used todeterminehow should elementsbedistributed insidethe containeralongthesecondary axis (oppositeofflexDirection).

Table5.3.1:Main propertiesofFlex

5. 3. 7 Di r e c t Mani pul at i on

Itissometimesnecessary to make changesdirectly to a componentwithoutusing stateorpropsto triggera re-render.setNativePropsistheReactNativeequivalent to settingpropertiesdirectly on aDOM node.

5. 3. 8 I ns t al l at i on

5.3.8.1Dependencies

Depending on the developmentOS and the targetOS,the dependenciesvary.For example,a Maccomputerisrequired to build projectswith nativecodeforiOS.In thisprojectthetargetOS isAndroid,sotherequirementsare:

• Node(8.3ornewer)

• Watchman (optional)

• TheReactNativeCommand LineInterface(ReactNativeCLI)

• A JDK (JDK 8)

• Android Studio(orjusttheCommand LineTools)

(38)

Nodecomeswith NodePackagerManager[56](npm)which willbeused toinstallnot only ReactNative,butallofthe application’sdependencies.Instead ofnpm,yarn can also beused.

Thefirstrequirementwhen developing Android applicationsisan up-to-dateversion ofJDK (JavaSE DevelopmentKit),atthemomentJDK 8.

Android Studio installsthelatestAndroid SDK by default.Building a ReactNative application with native code,however,requires a specific Android SDK,at the beginning ofthe project it was Android SDK Platform for API Level23 (6.0 Marshmallow). Additional Android SDKs can be installed through the SDK Manager.

Additionally,thedevelopermustinstall:

• GoogleAPIs

• Intelx86 Atom_64System Image

Itis importantto setup the Android and Java environmentvariables.Forthis project,theversionsofthedependenciesinstalled are:

• DevelopmentOS:Linux Mint19Tara

• npm:6.5.0

• Node:v8.11.3

• Yarn:1.12.3

• Watchman:4.9.0

Illustration 5.3.2:Android platformsinstalled

(39)

5. 3. 9 Re ac t Na t i ve CLI Commands

ToinstalltheReactNativeCLI:

Thiswillcreate a new folderin the currentdirectory and create a ReactNative projectinsideofit.

AstheIllustration 5.3.3 shows,theAndroid and iOS folderscontain Objective-C and Java codeforiOS and Android nativeparts.Thenode_modulesdirectory containsall installed npm packages.In the rootfolderthere are variousconfiguration filesfor Babel,Flow[57],Git[58],Watchman and Yarn[59].Thereisalso an index JavaScript file,called index.js,thatservesasan entry pointoftheapplication.

Listing 5.3-2:Creation ofa new React NativeProject

react-nativeinit<projectname>

Listing 5.3-1:ReactNativeCLI installation

npm install-g react-native-cli

Illustration 5.3.3:

Projectstructure

(40)

Torun and build theapplication,in thecaseofAndroid/iOS case:

Theinstructionsbuild thenative .app or.apk using theiOS orAndroid toolchains, startstheMetro Bundler,which minifiesand servestheJSX and otherassetssuch as imagesoverto thedevice.On Android,itstartstheadb serverto push the.apk with allthenativelibrariesincluded ontothedevice(with USB debuggingenabled). The react-native CLIwillrun the packager,which is in charge ofbundling the JavaScriptfilesand launch theemulatoron thephysicaldevice.

Thepackagerneed to berunning atalltimeswhiledeveloping,thecodechangeswill bereflected in theapplication by enablinghotreloading.

Metro serverisconfigured to starton port8081 by default.Oncetheapplication is launched in thesimulator/device,a requestissentto theserverforthebundle.The serverthen downloadsallthe required dependencies,bundlesthe JavaScriptcode and sendsitback totheapplication.Afterthisstep,theapplication startworking. Thedevelopmentwasdoneusing a physicalAndroid smartphone,running Android 8.0.0.To verify ifthedeviceisconnected thecommandin Listing 5.3-5 can beused in thecommand line:

Listing 5.3-4:Launch theapplication in iOS deviceoremulator

react-nativerun-ios

Listing 5.3-3:Launch theapplication in an Android deviceoremulator

react-nativerun-android

Listing 5.3-5:Command to verify the connected smartphones

adb devices

(41)

To run theapplication in a device,thedevelopermustauthorizethemobiledevice and enableUSB debugging thefollowing mustbeactionsmustbefollowed:“Settings

> DeveloperOptions> USB debugging”.

5. 3. 10The CLI

Thereact-native-cli,installed by meansofnpm asa separatemodule,isa shellfor accessing theCLIembedded in theReactNativeofeach project.Thecommandsand their effects are dependent on the version ofthe module ofreact-native in the contextoftheproject.

Running react-native -help from inside a ReactNative projectwilllistallofthe currentcommands,asshown in Illustration 5.3.4:

5. 3. 11De bug gi ng

From the device’sdevelopermenu,itispossible to tap on “Debug JS Remotely.” Thiswilllaunch Google Chrome and run the JavaScriptin the browserinstead of running iton thedevice.ReactNativewillsetup a Websocketconnection between the device and the browserthatallowsthe developerto use Chrome’sdeveloper console.

5. 3. 12Li nki ng l i br ar i e s

SomeReactNativemodulesincludenativecodeforAndroid and/oriOS in addition to JavaScript.Therearesomeextra stepsto connectitwith thenativepartsofthe application.

Illustration 5.3.4:Optionsforcommandsavailablein thecurrentProject

(42)

In thecaseofAndroid,ifthereistheneed to usenativecode,therearetwo waysto useJavawith theAndroid SDK in aReactNativeproject:

• putthe Java code directly into the existing app by adding Java classesto android/app/src/main/* folder and use them from MainActivity/MainApplication.

• createan Android Library,which istheway any npm react-nativepackages (thatgobeyond JavaScript)work.Thebenefitisthatitisreusable.

So,tolink alibrary firstinstallthecomponent,usingnpm likeanormalmodule,and then link itwith thecommand listed in Listing5.3-6:

Itisan automatic way forinstalling native dependenciesand to avoid manually linking allthe dependencies in the project.It works for both Android and iOS.

However,thelinking processofthelibrariescan vary,so itisimportantto check the installation stepsforeach ofthem.

Listing 5.3-6:Linking a nativelibrary react-nativelink <dependency-name>

(43)

6 Da t a Vi s ua l i z a t i o n

6. 1 Sc al abl e Ve c t or Gr aphi c s ( SVG)

SVG[60]isa languagefordescribing 2D-graphicsand graphicalapplicationsin XML which isthen rendered using theSVG viewer.Mostmodern browserssupportSVG and can display them asan imagesjustlikearegularJPG.

SVG drawings are created using a wide array ofelements.For this project the followingelementsareused:

• <svg>:isa containerthatdefinesa new coordinatesystem and theviewing area wheretheSVG willbevisible.Itisused astheoutermostelementofany SVG documentbutitcan also beused to embed a SVG fragmentinsideany SVG orHTML document.

• <g>:is a container used to group other SVG elements.Transformations applied to the <g> elementare performed on allofitschild elements,and any ofitsattributesareinherited by itschild elements.

• <line>:basicshapeused tocreatealineconnectingtwopoints.

• <text>:definesa graphicselementconsisting oftext.It'spossibleto apply a gradient,pattern,clipping path,mask,orfilterto <text>,justlikeany other SVG graphicselement.

• <path>:generic element to define a shape.Allthe basic shapes can be created with apath element.

SVG supportin ReactNativeisvia react-native-svg[61].It providesSVG supportto React Native on iOS and Android,and a compatibility layer for the web.This library contain nativecodeand mustbelinked asexplained in Linking librariesand readingtheinstruction provided in thelibrary’sinstructions.

The library svg-path-properties[62]isa pure Javascriptlibrary used to obtain the functionsgetPointAtLength(t)and getTotalLength()needed to do somecalculations forplottingthechart.

(44)

6. 2 D3. j s

D3.js[63]isa JavaScriptlibrary thatexploitsallthebenefitsprovided by theDOM to visualizedata using HTML,CSS and SVG.D3 managesthecomplexitiesofweb standardsand providescapabilitiesto browsersby combining powerfulvisualization componentsalong with a data-driven approach.Thelibrary consistsofmany useful featuresincludingscaling,transformations,axescreation and many others.

D3,in its4th version,ispresented asa collection ofmodules developerscan use independently,with minimaldependency between them,allneatly isolated in their own repository.Thefollowingmodulesareused in thisproject.

6. 2. 1 D3 - s c al e s

D3-scales[64]providestheencodingsthatmap abstractdata to visualrepresentation.

Every dataset has values within a domain and though the domains can vary drastically,onething remainsconstant;thenumberofpixelsavailableon thescreen.

Thesedifferentdomainsneedsto bemapped onto thisoutputrange.Thisishandled by D3-Scalesproperty thatmapsthe inputdomain to the outputrange.Once D3 scale function isdefined by providing itwith inputdomain and outputrange of pixels,thescalefunction can becalled by passing theinputvalueand itreturnsa scaled outputvalue.D3 providesdifferenttypesofscalessuch aslinear,ordinal, logarithmic,squareroot.In theproject,only thelinearscaleisused.

6. 2. 2 D3 - s hape

D3-shape[65]providesgraphicalprimitivesforvisualization,such aslinesand areas. Thismodulesupply a variety ofshapegenerators.Aswith otheraspectsofD3,these shapesaredriven by data:each shapegeneratorexposesaccessorsthatcontrolhow theinputdataaremapped toavisualrepresentation.

6. 2. 3 D3 - ar r ay

D3-array[66]providesarray manipulation,ordering,searching,summarizing,among otherthings.Data in JavaScriptis often represented by an iterable (such as an array,set or generator),and so iterable manipulation is a common task when analyzingorvisualizingdata.

(45)

7 I mpl e me nt a t i o n

The development of the application was using an incremental approach, each functionality wasimplemented and tested incrementally untiltheapplication covered themostimportantusecases.

Two importantmattersare the Application Stateand the Application Navigation, thosetopicsaredescribed in thefollowingchapters.

Anothertopicistheinteraction oftheapplication with theserverthrough itsAPI, covered in Web Services.

7. 1 Ac t or s of t he s ys t e m

The iXemWine is a community formed by the a network ofpublic sensors in vineyardslocated in municipalitiesorfarmsdistributed throughoutItaly.Anyone can registerand haveaccesstoit.

A userrepresentssomeonewho can log into theiXemWineapplication.In addition to thebasicinformation,hascredentialsthatenablesthem to log in to thesystem.

Each userhasroles,assigned to them,thatdefinespermissionsto perform a group of tasks.

An useradministratorcan perform additionalactions,likeadding a camera sensorto avineyard.

A vineyard isrepresented asan objectwith a uniqueidentification and a name.It hasinformation associated with it,liketheitscreation dateand thecity itislocated in,in addition tothelatitudeand longitude.

A vineyard can have nodesand camerasassociated with it.A node hassensors,a type,a alias,creation dateand otherconfiguration parameters.Each node’ssensor hasachannelin which ithandlestheactualmonitoringdata.

A usercan own one,severalorany vineyards,asshown in Illustration 7.2.1.In addition,a vineyard can be shared with otherusers.Both the shared and owned vineyardsmustbedisplayed in theapplication.In thecaseofa vineyard thatisnot owned and norshared with the user,then only a limited view ofthatvineyard is shown.

(46)

7. 2 Func t i onal i t y

Themain functionalitiesoftheapplication aredescribed in theIllustration 7.2.2 and then described in detailin thefollowing sections.

7. 2. 1 Aut he nt i c at e

Thefirstscreen oftheapplication iswheretheuserentersitscredentialsto login to the application.Once the user press the login button,it sends a HTTP POST

Illustration 7.2.1:Representation ofa user’sdata

Illustration 7.2.2:UseCases

(47)

requestto theiXemWinebackend Authentication Serverwith thecredentialsand as a response itsendsthe token thatwillbe used by the useron allthe subsequent requests.

Thereonly complication when developing thisscreen wasthatwhen theuserpressed to type the username and password,the virtualkeyboard showed up and covered textinputsfields.

For this reason, React Native provides the built-in KeyboardAvoidingView componentbutthe documentation isvague,e.g.,“Android and iOS both interact with thisprop differently.Android may behavebetterwhen given no behaviorprop atall,whereasiOS istheopposite” .[67]

To avoid theuseofa third-party librariesand also to havea cross-platform solution, an alternativesolution wasreached using:

• theKeyboard moduleto controlkeyboard events[68].Keyboard isa built-in ReactNative componentthatprovide a couple ofmethodsto listen forthe virtualkeyboard showing and hiding.

• animations,specifically transform/translateY to move the elements ofthe view vertically when thevirtualkeyboard shows/hide.

• theDimensions[69]built-in APItoobtain thewidth and heightofthescreen

• thecurrently focused field (and thusitsposition on thescreen)in orderto calculatethevaluetotranslatevertically theelements.

Theresultisthelogin screen,shown in Illustration 7.2.3:

(48)

7. 2. 2 Vi s ual i z e t he l i s t of Vi ne yar ds

To visualizethelistofvineyardsa userownsorhasbeen shared with,a component named Listwascreated,itisbased on the FlatList,built-in componentpreviously discussed.

TheListcomponentdisplaysaRow componentforeach item.A Row componenthas a title,detailsand the function callback when an item isselected.When the user presseson oneoftheitems,itnavigatesto anotherscreen thatshowsthedetailof thatvineyard.

Thelistofvineyardsauserownsand theonesshared with him areobtained oncethe usersuccessfully login to theapplication and redirected to thefirstscreen,which is thehome.

In the Illustration 7.2.4 the Home screen isshown,itdisplaysa Panelcomponent thatshowsthenumberofvineyard owned,theshared onesand thetotalnumberof nodesoftheuser.

Illustration 7.2.3:

LoginScreen:

Authentication ofthe user

(49)

The other place where the List component is shown is in the tab Shared (“Condivisi”)but,in thiscaseitonly displaystheListcomponent.

7. 2. 3 Vi s ual i z e t he Node s and Came r a s i ns i de a Vi ne yar d

Asstated previously,a vineyard can havenodesand camerasand to show them,the built-in SectionListcomponentisused.Thedifferenceto FlatLististhatitallowsto separate the data in sections.Each section hasitsdata source,itsrenderfunction and atitle.

In thiscase,theCamera and Nodesaretwo sections,asshown in Illustration 7.2.5 and the headerofthe screen isthevineyard’sname.When the userselectsone of them itnavigatestothespecificnodeorcamera.

Illustration 7.2.4:

Visualization ofthelist ofvineyards

(50)

7. 2. 4 Vi s ual i z e t he Se ns or s dat a i n Char t s

Sensors data are visualized by means ofa line charts.The chart configuration dependson thesensor’stype,becausein mostofthecasesthechartcan havemore than one data set to allow the user to contrast two physical quantities, like temperatureand thedew point[70],acrosstime.

Thereweren’tmany alternatives,itwashard to find a suitablelibrary thatmetthe functional and design needs at the same time. Only one library met the requirements, victory-native[71] but unfortunately it had known performance issue[72].So,for this functionality there was a time overhead oflearning and implementingthechartfrom scratch.

To build thechart,D3 wasused.Thefirstthing to do with thedata setisto scale (using d3-scales)thex and y domain to thewidth and heightofthechart,and then used the curve function,from the d3-shape library,to have a linearcurve forthe points.

Thescreen ofthesmartphonesare small,so theproposed solution wasto plotthe chartwithoutusing the“traditional”scrolling,instead,a ScrollView componentwas

Illustration 7.2.5:

Visualization ofsensors and camerasin a vineyard

(51)

used on top ofthechartso theusercan slidea cursoroverthelineand to show a slidinglabelthatactsasax-axis.

To getthelength oftheline,thefunction getTotalLength ofthesvg-path-properties library wasused.

Theticksofthey-axiscan befixed and bepassed asa prop orthey can bevariable and changeaccordingtothedataset.

Thelinesareplotted by meansoftheSVG path element,while they-axisusethe textelementforshowing thetick valueand thelineelementforplotting thedashed lines.

To be able to slide throughoutthe chartline,the only consideration isthatthe ScrollView’swidth attributeneedsto begreaterthan thewidth ofthescreen and at leastthesizeofthelinelength,sincethe“scrolling” iswhatenablesto movefrom oneend ofthelinetotheother.

Anotherthing islistening to the onScrolleventto getthe scrolling value atany point,and with thatvaluegetthe x and y coordinates(using svg-path-properties’s getPointAtLength function), and move the cursor along the graph using setNativePropsin ordertodoitwithouttriggeringanew rendering.

To allow the sliding movementofthe labelthatshowsthe valuesatthatspecific point,an interpolation isperformed wheretheinputrangeistheselected linelength and outputrangeisthewidth ofthescreen (minusthelabelwidth).A TextInput component is used to be able to update the label value using again the setNativeProps method.To display theproperlabelvalueata particularpointthe function scale.invert,from D3-scales,isused to revertfrom they and x coordinates valuestotheoriginalvalues.

To be able to plotthe two data setsin the same chart,in the chartcomponent’s stateisstored aselectedLine,which isthelineselected ataparticularmoment. The chartcomponentreceivesthe mandatory datasetand the socondary one,the selection to whereto placethecursorbetween them isperformed by a boolean called selectedMandatory.When thatboolean prop istrue,the mandatory lineLength is selected otherwisethesecondary is.Ifthereisno secondary provided,therecan not beany toggling.

The chartcomponentisencapsulated within a componentcalled ChartWithLabels thatadd theLabelfunctionality,showing a labelforeach data set,and thetoggling between them represented asswitchingaradiobutton.

(52)

Onemorelevelofabstraction iscreated foreach typeofnode,sinceeach Nodetype hasdifferenticons,colorsand constants.

The figure Illustration 7.2.6 and Illustration 7.2.7 shows an example of this functionality where the node type isa Temperature-Humidity sensor,so there are two charts,oneforthetemperatureversusthedew pointand theotherwith justthe humidity:

AnothertypeofsensoristheTwo LayerLeafWetnesssensor,thatshowsa top and a bottom humidity,butin thiscase to visualize thedata only one chartisneeded sincethetwodatasetrefertothesamescale,astheIllustration 7.2.8 below shows:

Illustration 7.2.6:

Visualization ofthe temperatureand the dew pointofa

Temperature-Humidity Sensor

Illustration 7.2.7:

Visualization ofthe humidity ofa

Temperature-Humidity Sensor

(53)

In addition to thechart,atthe top ofthescreen,thereisa Panelthatshowsthe latestcorrespondingsensor’svalueacquired.

7. 2. 5 Vi s ual i z e t he pi c t ur e s t ake n by a Came r a

The picturestaken by the camera are shown in a grid,Illustration 7.2.9,sortof Gallery usingaFlatListcomponentthatissettorenderthepicturesin columns. Thebackend returnsan array ofobjectsthatcontain theURL ofthepicturestaken by theparticularcamera on the date selected.The picturesshown atthestartby defaultaretheonestaken thatparticularday.

The user can see the details ofa picture by selecting it,which navigates to a differentscreen where the usercan zoom-in and zoom-outthe picture to see itin detail.

Illustration 7.2.8:

Visualization ofa Two LayerLeafWetness Sensor

(54)

7. 2. 6 Se ar c h f or vi ne yar ds i n t he Communi t y

Thesearch forvineyardsisby meansofa map,asshown in Illustration 7.2.10,the positionsofthevineyardsaredisplayed asmarkers.

The only reliable way to use mapsin ReactNative applicationsisto installthe third-party react-native-maps[73]package.

TheMapView componentfrom thatpackage isthe main toolused and providesa declarative approach to controlfeatures on the map where they are specified as children ofaMapView.

Each vineyard isrepresented by meansofa Markerthatisrendered on top ofthe map.A calloutisdisplayed with the vineyard’sbasic information when the user presseson themarker.Then,iftheuserpresson thecallout,theuserisredirected to ascreen,which showsinformation oftheselected vineyard.

To add the functionality ofmaps clustering the library react-native-maps-super- cluster[74] is used.It provides a ClusteredMapView component that receives the samechildren asaMapView butadd theextrafunctionality forclusterrendering.

Illustration 7.2.9:

Photo grid

visualization ofthe picturestaken by a camera

(55)

7. 2. 7 Edi t pr e f e r e nc e s ans s e e t he pr of i l e

Theusercan visualizeitsprofileand changesomepreferencesoftheapplication.In thiscase,thelanguage.Theavailablelanguagesareenglish and italian.Thelibrary i18n-js[75]isused,aplain popularJavaScriptlibrary which supportsfeaturessuch as date/timelocalization,numberlocalization,localefallback,etc.

Internationalization (i18n forshort)istheprocessofadapting an application to work with differentlanguages.Theinternationalization isdoneby having two files,en.json and it.json,containingstringsin a flatJSON format.Both languagefileswillcontain key-valuepairswith thesamekeysatany pointin timecontaining thetranslations ofthe headers,textsmessages,errors,etc.The differentscreenswillimportthose stringsfrom oneofthesefilesdependingon thecurrentlanguageselected.

In orderto configure some parameters,like the defaultlanguage,thefile i18n.jsis created.Besidesconfiguring i18n,italso exportsa translatefunction and someother utility functions,forexampletogetorsetthelanguage.

To changetheapplication’slanguagethereisa button in theUserscreen thatshows thecurrentlanguageand when pressed ittogglesthelanguages.

Illustration 7.2.10:

Search and

visualization ofthe vineyard'sposition

(56)

Thelanguage,stored in theRedux store,isalwaysin syncwith thelanguagein the i18n.jsfile,and when the userchangesthelanguagean action isdispatched which changesthelanguagein both i18n moduleand Redux store.

The navigator’s header text and bottom tab labels have to be re-rendered on languagechange.Thenavigation library allowsto passpropsto thenavigators,this propswillbe passed to each navigatorinstance and perform the re renderwhen a languagechangeoccurssinceitisconnected totheRedux store.

The Illustration 7.2.11 showstheuser’sprofileinformation and thefunctionality to changethelanguage.

MoreofRedux and navigation willbeaddressed on thefollowingchapters. Illustration 7.2.11:

User'sprofileand languagechangescreen

(57)

8 Appl i c at i o n Na vi ga t i o n

8. 1 Re ac t Navi ga t i o n

ReactNavigation[76]isused to movebetween screensin theapplication.Itprovides different types ofnavigation patterns,like a “stack ofscreens” or “tabs”.It’s a solution backed by the React Native community[77] that works with the native navigation componentsofboth Android and iOS.

8. 1. 1 Navi g at or

A navigatorisa componentthatimplementsa navigation pattern.Each navigator must have one or more routes. Each route must have a name and a screen component.Thescreen componentisa Reactcomponentthatisrendered when the routeisactive.

A screen can also beanothernavigator,sincethey arecomponents,so they can be nested. The result is that the application is a combination of these different navigators.

Therearethreetypesofbuilt-in navigatorsused in theprojectare:

• SwitchNavigator:Only show one screen ata time.When navigate,itreset screen immediately withoutanimation.

• StackNavigator:Containsscreensasastack.Each ofthescreensgetsmounted only when navigating to that particular screen and gets un-mounted only when goingback ormanually resetthenavigation state.

• TabNavigator:Containstabsthatthe usercan swipe.The tab screensget mounted allatonce.

8. 1. 2 Aut he nt i c at i on f l ow

Mostapplicationsrequire thata userauthenticatesin some way to have accessto data associated with thatuserorotherprivatecontent.Typically theflow lookslike this:

• Theuseropenstheapplication.

Riferimenti

Documenti correlati

Society’s relations work horizontally and connectedly, regarding interactions and organizations so the emergence of concepts of citizenship that derive from such interactions

estrogenic activity of extracts containing endogenous estrogens and breast cancer

Compared with sham mice, cardiac biopsies obtained from CKD mice showed increases in the phosphorylation of IkBa, nuclear translocation of the NF-kB subunit p65, increased

To download and install an application using the designed system, the final users can access the public Download Page, already described in section 4.1.5, opening a link generated

In this project we tried to combine the need to govern a specific business process, in this case the access control to equipment, cabinets or sensitive business areas, with

In the sound localisation task, source activity slightly moved from primary auditory cortex (HG) to secondary cortex, as a function of time after auditory stimulation.. Plot (a)

1) Heterogeneity: This feature allows integration of different types of IoT (including constrained) devices with heterogeneous processing components.. and various

Per far fronte a questo si è deciso in futuro di introdurre una classe adibita alla simulazione di interfacce bidimensionali attraverso l'uso di elementi a tre dimensioni, ciò che