42
Bachelor’s thesis Degree Programme in Information Technology Internet Technology 2017 Tam Nguyen Truong Thanh MONITORING ENVIRONMENTAL VARIABLES USING SENSORTAG

MONITORING ENVIRONMENTAL VARIABLES USING SENSORTAG · Picture 1. Concept of a monitoring system. 6 Picture 2. SensorTag CC2650. 8 Picture 3. The implementation structure. 12 Picture

  • Upload
    others

  • View
    2

  • Download
    0

Embed Size (px)

Citation preview

Page 1: MONITORING ENVIRONMENTAL VARIABLES USING SENSORTAG · Picture 1. Concept of a monitoring system. 6 Picture 2. SensorTag CC2650. 8 Picture 3. The implementation structure. 12 Picture

Bachelor’s thesis

Degree Programme in Information Technology

Internet Technology

2017

Tam Nguyen Truong Thanh

MONITORING ENVIRONMENTAL VARIABLES USING SENSORTAG

Page 2: MONITORING ENVIRONMENTAL VARIABLES USING SENSORTAG · Picture 1. Concept of a monitoring system. 6 Picture 2. SensorTag CC2650. 8 Picture 3. The implementation structure. 12 Picture

BACHELOR’S THESIS | ABSTRACT

TURKU UNIVERSITY OF APPLIED SCIENCES

Information Technology

2017 | 42

Tero Virtanen

Tam Nguyen Truong Thanh

MONITORING ENVIRONMENTAL VARIABLES USING SENSORTAG Thepurposeofthisthesiswastocreateasystemconsistingofamulti-functionalsensorandaweb-basedapplicationinordertomonitorenvironmentalvariables,suchastemperature,humidity,light,densityandsoon.Withanintentionofusingthesensortotrackobjectmovements,agyroscopesensorwasadditionallycreated.Theapplication,calledsensorApp,canbeseenasafull-stackwebdevelopingexamplewhichtakesadvantageofsuchtechnologiesasNodeJS,MongoDB,jQueryandSocket.io.

Theback-endpartofthisprojectisaNodeJSwebservercommunicatingwiththesensordeviceinordertoretrieveinformationthenforwardtotoaMongoDBdatabaseserverforstoring.Ontheotherhand,forthefront-endpart,thedatareceivedfromthesensorisalsotransferredtoaweb-interfacetopresentandmonitorinreal-timewiththehelpofWebSocket’slibrarynamedSocket.io.Inaddition,theHighChartslibraryisusedtocreategraphstovisualizeallthedatafromthesensororfromthedatabaseserver.

Theresultofthethesiswasthe”sensorApp”app.Theappiscapableofpresentingdatafromthesensorsand,especially,ispackedwithdatabaseextractionfeaturewhichisnotsupportedbyotherservices.Therewerefewobstaclesinthisproject,suchashardwarefaulty,overloadeddatatransmissionandsecuritymethods.Inaddition,limitationsintechnologywerealsoaddressed,forinstancepowerconsumptionandgyroscopeaccuracy.

KEYWORDS:

Node.js,MongoDB,JavaScript,jQuery,Sensor,Web,Server.

Page 3: MONITORING ENVIRONMENTAL VARIABLES USING SENSORTAG · Picture 1. Concept of a monitoring system. 6 Picture 2. SensorTag CC2650. 8 Picture 3. The implementation structure. 12 Picture

CONTENTS

LIST OF ABBREVIATIONS (OR) SYMBOLS 6

1 INTRODUCTION 6

2 TECHNOLOGIES 82.1 SensorTag 8

2.2 Bluetooth Low Energy 8

2.3 NodeJS 92.4 NodeJS Modules 9

3 PROCESS 12

4 IMPLEMENTATION 144.1 NodeJS and modules 144.2 JavaScript Libraries 154.3 Wire up 16

4.4 Setting up connection 174.5 Data Flow 204.6 User interface 234.7 Database 25

5 PERFORMANCE 27

6 ASSESSMENT 296.1 Obstacles 29

6.2 Potential Future Improvement 29

6.3 Limitations 30

7 CONCLUSION 34

REFERENCES 35

APPENDICES

Appendix 1. Application Tree Appendix 2. Sensortag module code

Page 4: MONITORING ENVIRONMENTAL VARIABLES USING SENSORTAG · Picture 1. Concept of a monitoring system. 6 Picture 2. SensorTag CC2650. 8 Picture 3. The implementation structure. 12 Picture

EQUATIONS

Equation 1. Differences when sensor changing position. 32

FIGURES

Figure 1. Data transfer from UI to server via “custom” socket. 21Figure 2. Socket “valuesOut” structure. 21Figure 3. Socket “signal”. 22Figure 4. Records are sent to database. 22

PICTURES

Picture 1. Concept of a monitoring system. 6Picture 2. SensorTag CC2650. 8Picture 3. The implementation structure. 12Picture 4. Discovery mode. 17Picture 5. Broadcasting connectivity signal. 18Picture 6. Sensor information recognized by node server. 18Picture 7. Sensor panel in dashboard. 19Picture 8. Responses from server when connected to SensorTag. 20Picture 9. Dashboard interface. 23Picture 10. Show records panel. 24Picture 11. Visualized graph of data. 24Picture 12. Exporting feature of HighCharts. 25Picture 13. Structure of a key in MongoDB database. 26Picture 14. A point transferred from server to graphs. 27Picture 15. How data is handled upon requests. 28Picture 16. Light density presentation. 30Picture 17. Gyroscope presentation. 32

TABLES

Table 1. JSON format. 11Table 2. NPM installing syntax. 14Table 3. Create project with Express Generator. 14Table 4. Sensortag module install command. 15Table 5. Link to “socket.io” library in HTML. 15Table 6. Get “socket.io” functions in JavaScript. 15Table 7. Link to your mLab database. 16Table 8. Link to HighCharts Library in HTML. 16Table 9. Start NodeJS server command. 17Table 10. Power consumption. 31

Page 5: MONITORING ENVIRONMENTAL VARIABLES USING SENSORTAG · Picture 1. Concept of a monitoring system. 6 Picture 2. SensorTag CC2650. 8 Picture 3. The implementation structure. 12 Picture

Table 11. Sensor states decided by Delta. 33

Page 6: MONITORING ENVIRONMENTAL VARIABLES USING SENSORTAG · Picture 1. Concept of a monitoring system. 6 Picture 2. SensorTag CC2650. 8 Picture 3. The implementation structure. 12 Picture

LISTOFABBREVIATIONS(OR)SYMBOLS

API Application Program Interface

BLE Bluetooth Low Energy

DOM Document Object Model

HTML Hyper Text Markup Language

IoT Internet of Things

JSON JavaScript Object Notation

MVC Model View Controller

RDBMS Relational Database Management System

UI User Interface

XML Extensible Markup Language

Page 7: MONITORING ENVIRONMENTAL VARIABLES USING SENSORTAG · Picture 1. Concept of a monitoring system. 6 Picture 2. SensorTag CC2650. 8 Picture 3. The implementation structure. 12 Picture

6

TURKUUNIVERSITYOFAPPLIEDSCIENCESTHESIS|TamNguyenTruongThanh

1 INTRODUCTION

Monitoringaserverplaysanessentialroleinanadministrator’sroutine.Asthenetworkgrows,keepingtrackofalltheactivitiesisbecomingmoreandmorecomplicated.Moreover,theperformanceofserversdoesnotonlydependonthehardwareorsoftwarealonebutalsoonotherfactorssuchastemperatureorhumidityofsurroundingenvironment.Especially,overheatingisoneofthemainreasonstocauseincreasinglatencyinnetworks.Therefore,theneedofasurroundingmonitorsystemwhichcanbesupervisedremotelyseemstobenecessary.

Picture1.Conceptofamonitoringsystem.

AspresentedinPicture1above,thecentralizedsystemisinchargeofretrievingdatafromanysensorbuilt-indevices.Sensordataconsistsoftemperature,humidity,lightdensity,magneticlevel,etc.Therawdataistransferredtothesystemwhereitwillbeconvertedintohumanreadablevalues.Whilebeingprocessed,thedataisalsocapturedbythedatabaseserverthensavedinformofrecords.Theadvantageofthedatabaseserverhereistokeeptrackofallmeasurementsduringthewholeoperation.Thedatabaserecordsarealsousedasafuturereferenceortoanalyzetrendingofsensorvalues.Therearemanyformsofpresentingdataforadministrator.Sincetherequirementistomonitorremotelywithanydevicesavailable,awebsiteisconsideredasthebestchoice.

Page 8: MONITORING ENVIRONMENTAL VARIABLES USING SENSORTAG · Picture 1. Concept of a monitoring system. 6 Picture 2. SensorTag CC2650. 8 Picture 3. The implementation structure. 12 Picture

7

TURKUUNIVERSITYOFAPPLIEDSCIENCESTHESIS|TamNguyenTruongThanh

Thisthesisdemonstratestheprocessofestablishingthemonitoringsystem.Withtheweb-basedapplicationbeingacoreofthesystem,theapplicationdoesnotprovideonlyagraphicalinterfacethatsuitseverydevicefromcomputertomobilephonebutalsoareal-timereportingfunctionality.Thethesisstartswithintroducingallthetechnologiesusedintheproject.ChapterProcessexplainswhytheselectedtechnologiesaresuitablefortheproject.ChapterImplementationdescribeshowtheprojectwasimplemented.ChapterPerformancereportsonhowtheperformancewasvalidated.Thefinalchapterdiscussesobstaclesandlimitationsinthisproject.

Page 9: MONITORING ENVIRONMENTAL VARIABLES USING SENSORTAG · Picture 1. Concept of a monitoring system. 6 Picture 2. SensorTag CC2650. 8 Picture 3. The implementation structure. 12 Picture

8

TURKUUNIVERSITYOFAPPLIEDSCIENCESTHESIS|TamNguyenTruongThanh

2 TECHNOLOGIES

2.1 SensorTag

SimpleLink™BluetoothSmart®/Multi-StandardSensorTagfromTexasInstrumentisanexpandablesensor-basedBluetoothdevice.TherearemanyversionsbuttheoneweuseinthisprojectparticularlyisCC2650SensorTag.Basically,thisversionhas10sensorsbuilt-insuchassupportforlight,digitalmicrophone,magneticsensor,humidity,pressure,accelerometer,gyroscope,magnetometer,objecttemperature,andambienttemperature[1]onthesamecircuitandoperatesatalowenergylevel.Intermsofexpandability,moresensorscouldbeaddedwithDevPackinordertofiteveryneed.Regardingpowerconsumption,accordingtoTexasInstrument,withanintervalof1second,itcanrunsforatleast1yearstraight.Moreover,italsoprovidesanoptiontotransfermeasurementstotheCloudviaanappforbothiOSandAndroidplatforms.Inaddition,iBeacon,ZigBee®/6LoWPANtechnologyarealsosupportedbythesensor.

Picture2.SensorTagCC2650.

Developmentkit(DevPack)[2]isanoptionalcircuitwhichprovidesUSBinterfaceforSensorTagtoenablethephysicalconnectiontocomputer.Updatingfirmwareandmakingmodificationtothesensorarethemainrolesofthekit.Ontheotherhand,italsohelpsthesensortouseexternalpowersupplywhenrunningoutofbattery.

2.2 BluetoothLowEnergy

BluetoothLowEnergy(BLE)orBluetoothSmartisalatestversionofBluetoothTechnology[3].InordertoaccommodateInternetofThings(IoT)trend,BLEnowconsumeslesspowerthanpreviousversionssoitcankeepoperatingforlongtimewithonlyacoin-cellbattery.Regardingsecurity,BLEcanenhancesecurityabilitysuchasfullycompatiblewith128-bitAESencryption.Moreover,withawideavailabilityalongwithmentionedfeaturesabove,BLEisgraduallymakingitswaytomoreandmoreIoTprojects.

Page 10: MONITORING ENVIRONMENTAL VARIABLES USING SENSORTAG · Picture 1. Concept of a monitoring system. 6 Picture 2. SensorTag CC2650. 8 Picture 3. The implementation structure. 12 Picture

9

TURKUUNIVERSITYOFAPPLIEDSCIENCESTHESIS|TamNguyenTruongThanh

2.3 NodeJS

Toaccomplishahugestreamofdataconstantlytransferringtotheserver,oneofthebestimplementationinthemarketatthemomentisNodeJSserver. Node.js/NodeJSisanevent-drivenenvironment.ItisalibrarywasinventedbyRyanDahlin2009.After45-minutetalkatJSConf,RyanintroducedNodeJSwhichchangedJavaScriptforever[4].WithanintentionofexpandingJavaScriptbeyondjustawebbrowserlanguage,NodeJSnowbecomesoneofthemostpowerfulserversinthemarket.ANodeJSserveriscapableofhandlingavastamountofconnectionsatonce.Despitethefactthatitisasingle-threadserver,itprovidesadecentperformanceasopposedtoothermulti-threadservers.ConcurrentoperationsissmoothlyexecutedwiththehelpofV8enginewhichisanenginefromGooglebuilttoimprovetheperformanceofJavaScript.ThereareaexcessivenumberofAPIsandmodulesavailableforNodeJSoutofthebox.ThousandsandthousandsofmodulesaredevelopedandcontributedbycommunityuptonowmakesNodeJSadaptitselftomanyprojectsoriswidelyusedbylargecompanies.

2.4 NodeJSModules

NodeJShasamodular-orientedstructure.Modulesareblocksofcodeincertainlanguagewhicharebuilttoaccomplishcertaintasks.Theirfunctionalitiescouldbestandaloneorcombinedwitheachotherinordertoachievemuchsophisticatedoperations.

Sensortag

SensortagmoduleforNodeJSwascreatedbySandeepMistryin2013[5].ItisanAPImadespecificallyforTexasInstrumentsSensorTags,namelyTICC26xxseries.Thismoduleisoneofthemostimportantpiecesofthisapp.Itprovidesfunctionstoestablishaconnectionbetweenthesensorandtheserveraswellasallowsdevelopersdisplayextracteddetailinformationofthedeviceforexampleserialnumbers,type,nameorevenfirmwarerevisions.Apartfromconnectivity,theAPIalsoenablesustotakecontroloverbuilt-insensorsinjustafewlinesofcode.Inotherwords,fromenablingacustomizedsensortoexportingdatainordertoprocessinfurtherstages,allofthosetaskscanbedoneeasilywithoutanyknowledgeoflowlevelprograminglanguage.Thecomprehensivelistofprovidedcategorizedfunctionsasfollows:

Page 11: MONITORING ENVIRONMENTAL VARIABLES USING SENSORTAG · Picture 1. Concept of a monitoring system. 6 Picture 2. SensorTag CC2650. 8 Picture 3. The implementation structure. 12 Picture

10

TURKUUNIVERSITYOFAPPLIEDSCIENCESTHESIS|TamNguyenTruongThanh

• Discovery• Connect/Disconnectdevice• DeviceInformation• Sensors

o Accelerometero IRTemperatureo Humidityo Magnetometero BarometricPressureo Gyroscopeo Luxometer(CC2650only)o IO

• SimpleKey

Socket.io

Sincewebapplicationisessentiallymainstream,datawhichtraversesacrossnetworksdemandsahighresponserateinordertomaintainuserexperience.Inmodernwebapplications,userinputsarefrequentlyprocessedinreal-time,thenexchangedbackandforthbetweenback-endandfront-endsections.ThatiswhenadefinitionofWebSocketcomesalong.Basically,WebSocket[6]isintentionallyaprotocolwhichenablesustosetupacommunicationchannelformessageexchangingfromaservertoclientsorviceversa.Regardingcompatibilityissuesbetweenmodernbrowsersandolderones,socket.iowasinventedtomaintainaconsistencyforusingWebSocketonanybrowserswithoutadjustments.Asamatteroffact,socket.iogrowsincrediblyfastandisimplementedinthemajorityofwebapplicationsalongsidewithNodeJS.

jQuery

jQuerywascreatedasaJavaScriptlibrary.Technically,everythingcanbedonewithJavaScript,whichnowisevenfasterandsimplerwithjQuery.Moreover,userinteractionisnowhandledinamorestraight-forwardway.Therearevarioustypesofactivityhappeningon-site,forexample,DOMmanipulation,eventschedulewhichnowcanaccomplishevenmorerapidlywithjQuery[7].Inaddition,pre-createdsnippetsforanimationsareavailablerightoutoftheboxfordevelopersaswell.Allinall,jQueryiswidelyusedinvastnumbersofprojectsinanyscaleandbecomeoneofthemostpopularJavaScriptlibrarieswithoutadoubt.

Page 12: MONITORING ENVIRONMENTAL VARIABLES USING SENSORTAG · Picture 1. Concept of a monitoring system. 6 Picture 2. SensorTag CC2650. 8 Picture 3. The implementation structure. 12 Picture

11

TURKUUNIVERSITYOFAPPLIEDSCIENCESTHESIS|TamNguyenTruongThanh

MongoDB

Adatabaseessentiallyisamust-haveinawebapplication.Sincethebeginning,RDMShastakenaleadinthewebdevelopmentindustry.Asaresultofthedominanceoflarge-scalewebapplications,theNoSQLdatabasehasbecomingstrong.Becauseofitnumerousfeaturessuchasscalable,adaptivetochanges,supportingJSON-likeformat,NoSQLhasreceivedsignificantattentionfromstart-upstolargescaleenterprises.OneofthemostpopulardatabasesinthiscategoryisMongoDB[8].Apartfromcharacteristicinheritanceofnon-relationaldatabases,MongoDB’smosthighlightingfeatureisaJSON-likedatabase.JSONformathasbeenwidelyusedtotransferdatabetweenclientsandservers.Table1.JSONformat.

{ 'key':value, 'Name':"John", 'ID':1}TheexampleaboveisasimpledeclarationofaJSON-formatvariable.Aspresentedinapairofkeyandvalue,JSONhasamoreflexiblestructurethanitsformer,XML.Inaddition,avaluecanbestoredinformofaJSONaswell.WiththeuseofJSONscheme,datafromservernowcanbedirectlystoredinMongoDBwithoutmakinganyconversions.Inaddition,complicatedtableconstraintsoftraditionaldatabasearecompletelyeliminated.Intermsofapplicationscaling,itisextremelyunsophisticatedtoappendmorerecordsorattributesastheappgrows.ThementionedfactorsmakeMongoDBsuitableforanycriteriaofthisprojectespeciallyinmobilegenerationwhereJSONcanbeseenasanewstandardfordatatype.

Page 13: MONITORING ENVIRONMENTAL VARIABLES USING SENSORTAG · Picture 1. Concept of a monitoring system. 6 Picture 2. SensorTag CC2650. 8 Picture 3. The implementation structure. 12 Picture

12

TURKUUNIVERSITYOFAPPLIEDSCIENCESTHESIS|TamNguyenTruongThanh

3 PROCESS

Aftercarryingoutsomeresearchtodecidewhichtechnologyissuitableforthisproject,alistofrecentoneswereselectedasfollows:NodeJS,MongoDB,jQuery,HighCharts,Socket.io.ThemainreasonforchoosingNodeJSinthefirstplaceisitshighperformancewhichisidealforreal-timewebapplications.Apartfromthat,thousandsofpluginsaredevelopedandavailabletoaccommodateanyrequirements.Especially,sensortagistheonelibrarythatcanenabledeveloperstoopenupthepotentialofTexasInstrumentsensors.Withthatfoundation,thesystemalreadyhasawebserverwithbuilt-infunctionalitytoconnectandcommunicatewiththesensordevice.Intermsofdatabases,MongoDBwaschosensinceitiseasytocorporatewithNodeJSandrecommendedthemostinwebdevelopmentcommunity.MeasurementsfromthesensorarestoredinMongoDBwhiletheyarepresentedonthewebsitesimultaneously.Thedatabasecomesinhandywhenitcomestoreviewthetrendinganalysisofvaluesfromthesensorinthefuture.Moreover,theabilitytointeractwithJSONformatalsoistakenintoaccount.

Picture3.Theimplementationstructure.

WiththeconvenienceofJSONstructure,HighCharts[9],ajQuerylibrarycanprocessdatafromdatabasetransparentlythendisplayitinanappealingway.TheadvantageofHighChartsliesinbuildingchartsorgraphswithsimplisticvisualregardlessofdeviceresolutionaswellasinprovidingafallbackcompatibilityforallcurrentweb-browsers.

Page 14: MONITORING ENVIRONMENTAL VARIABLES USING SENSORTAG · Picture 1. Concept of a monitoring system. 6 Picture 2. SensorTag CC2650. 8 Picture 3. The implementation structure. 12 Picture

13

TURKUUNIVERSITYOFAPPLIEDSCIENCESTHESIS|TamNguyenTruongThanh

Lastbutnotleast,socket.io,ontheotherhandisanupgradedversionofWebSocketwhichprovidescompatibilityacrossdevices.Withhighperformanceandstability,itisobviouslyaflawlesschoiceforreal-timewebapplication.Otherthanthat,socket.iowasalsobuiltonJavaScriptfoundationwhichmakesaseamlesscombinationwiththeothertechnologiesusedforthisconcept.

Page 15: MONITORING ENVIRONMENTAL VARIABLES USING SENSORTAG · Picture 1. Concept of a monitoring system. 6 Picture 2. SensorTag CC2650. 8 Picture 3. The implementation structure. 12 Picture

6

TURKUUNIVERSITYOFAPPLIEDSCIENCESTHESIS|TamNguyenTruongThanh

4 IMPLEMENTATION

Inordertogetthesystemoperated,allthepuzzlepieceshavetobeputtogetherinalogicalway,startingwithinstallationsoftheinfrastructurecore.Thefollowingsectionwillcovertheinitialstepstosetupabasicskeletonfortheapp.

4.1 NodeJSandmodules

NodeJSisavailabletoalmosteveryplatformavailableincludingWindows,MacOS,Linux.Thewalk-throughinstructionisclearlyavailableonNodeJS.org.However,fordemonstrationpurposes,allthestepsbelowthispointwillbetakenpartonMacOS.Thevisualinstructionfromthe‘.pkg’filedownloadedtoinstallNodeJSframeworkandNodepackagemanager(NPM)altogether.NPMisanessentialpartyetpowerfulofNodeJSenvironment.Itallowsustocustomizetheservertosuiteveryneedsfromprojecttoproject.ThemainfunctionofnpmistoaddorremovepackageswhichareexclusivelydevelopedforNodeJS.Table2.NPMinstallingsyntax.$ npm install <PACKAGE_NAME>

Express.jsframework

Express.js,whichintroducedafterRubyprojectSinatra,isanessentialframeworkforeveryonetobecomefamiliarwithNodeJS.AccordingtoJimR.Wilson,Expressprovidesmosttheplumbingcodethatcoderswillotherwiseendupwritingthemselves[10].Withonlyfewlinesofcode,afullyfunctionalbackbonewassetupandreadytogo.TheconceptbehindExpressisthatitispredefinedfollowingMVC(ModelViewController)architecturewiththesupporttemplateengines.ExpressGeneratorwascreatedforbeginnerstojumpintothedevelopingphasewithoutgoingthroughdeeplyconfigurationstepswithExpressbydefault.Abasicwebserverwillbedeployedrightoutoftheboxafterwithjustonelineofcode.Table3.CreateprojectwithExpressGenerator.

$ express sensorApp WejustcreatedasensorAppinthecurrentdirectorywithasimplewebserverwithanindexpage.

Sensortagmodule

SensortagmoduleisprovidedthroughNPMandisinstalledbythecommandbelow:

Page 16: MONITORING ENVIRONMENTAL VARIABLES USING SENSORTAG · Picture 1. Concept of a monitoring system. 6 Picture 2. SensorTag CC2650. 8 Picture 3. The implementation structure. 12 Picture

15

TURKUUNIVERSITYOFAPPLIEDSCIENCESTHESIS|TamNguyenTruongThanh

Table4.Sensortagmoduleinstallcommand.

$ npm install sensortag Anexamplecodecomesinthepackageenabletheserverreceivestemperatureandhumidityfromthesensorrightoutofthebox.Bymakingmodificationsinordertoadapttothisproject,specificfunctionsregardinglightsensorandgyroscopearealsoadded.Therearenotonlyvaluereceivingfunctionsareimplementedbutanumberofcalculationsarealsoplacedinthecodetocalculatetheoutputontheflybeforeitleavesforpresenting.

Socket.io

Themechanismofsocket.ioconsistsoftwoparts:theserverandclientside.TheserversideisdistributedfromNPM.Ontheotherside,theclientoneisslightlydifferent.First,thelibraryhastobeembeddedintothewebpage.Table5.Linkto“socket.io”libraryinHTML.

<script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>ThenfunctionalitiesareimplementedwithintheJavaScriptsection.Table6.Get“socket.io”functionsinJavaScript.

var socket= io.connect('http://yourdomain.address');

Additionalmodules

Inadditiontothementionedpackagesabove,therearesomeotherdependenciesneededtohelptheapplicationoperatingsuchas:serve-icon,morgan,body-parser,cookies-MongoDB,assert.

4.2 JavaScriptLibraries

mLab

mLabwasrenamedfromMongoLabinFebruary2016[11].mLabisanonlinedatabaseserviceusingMongoDB.ItprovidesanconvenientwaytointeractwithMongoDBwhichisalsocompatiblewithmanyexistingtechnologies.EasytosetupandreliableareadvantageswhenusingmLab.AregisteredaccountisneededtostartusingmLab.

Page 17: MONITORING ENVIRONMENTAL VARIABLES USING SENSORTAG · Picture 1. Concept of a monitoring system. 6 Picture 2. SensorTag CC2650. 8 Picture 3. The implementation structure. 12 Picture

16

TURKUUNIVERSITYOFAPPLIEDSCIENCESTHESIS|TamNguyenTruongThanh

Cloud-baseddatabasesareverypopularrightnowduetotheirportabilityandconvenience.mLabisagreatexample.Foreducationortestingpurposes,settingastandalonedatabase-servercouldbetime-consuming.mLabisconsideredasabetterchoicebecauseofitssimplicityininstallationandreliability.Tosetup,mLabcreatedanURLtoallowdeveloperstoaccessthedatabaseremotely.MongoclientisanobjectprovidingconnectingfunctionstoMongoDBdatabase.Byusingit,manipulatingthedatabasescanbedonewithonlyfewsteps.Table7.LinktoyourmLabdatabase.

url = ”MongoDB://<adminuser>:<password>@<link to your database:<port>/<database name>”; var MongoClient = require('mongodb').MongoClient; MongoClient.connect(url,function(err,database) {...};

HighCharts/HighStocks

ThereareplentyofJavaScriptlibrariesfordesigningchartsfromourdatabase.HighChartsisoneamongthebestsofarwhenitcomestoreliabilityandcompatibility.Table8.LinktoHighChartsLibraryinHTML.

<script src="https://code.highcharts.com"></script>

4.3 Wireup

WithafoundationoftheExpresspredefinedserver,thenextstageisconnectingallthecomponentstogether.Bydefault,Expresshasitsstartingpointsetto‘www’file.Anyactivityfollowedbywillderivefromthere.‘www’file’sjobistoconfigureaportfortheserverandhandlerelatederrorsorexception.App.jswillactasastationwheredataflowwillbeprocessedandtransferredtoeverypartofthesystem.Thepurposeofapp.jsisto:

• Createandconfigurewebserver.• Importlibraries/plugins.• Handleviews.• Connectwithdatabase.• Processandmanipulatedata.

Page 18: MONITORING ENVIRONMENTAL VARIABLES USING SENSORTAG · Picture 1. Concept of a monitoring system. 6 Picture 2. SensorTag CC2650. 8 Picture 3. The implementation structure. 12 Picture

17

TURKUUNIVERSITYOFAPPLIEDSCIENCESTHESIS|TamNguyenTruongThanh

4.4 Settingupconnection

Inordertostarttheapp,weissuethiscommandintheappdirectory:Table9.StartNodeJSservercommand.

$ node app.jsSincethebeginning,whenevertheappisopened,asocketissetuptoreceivesignalsfromthesensoreverysecondwhichiscalleddiscoverymode.Fromthedashboard,thesensorstatusispresentedas‘Discovering..’whichmeanstheconnectionbetweenthesensorandserverisnotestablishedyet.

Picture4.Discoverymode.

Thesensorwillbeturnedonbypressingpowerbutton3forseconds.Ablinkingledlightonthesensorindicatesthatitisindiscoverymode.Whileindiscoverymode,itstartsbroadcastingitsaddress(UUID)tonearbydevices.

Page 19: MONITORING ENVIRONMENTAL VARIABLES USING SENSORTAG · Picture 1. Concept of a monitoring system. 6 Picture 2. SensorTag CC2650. 8 Picture 3. The implementation structure. 12 Picture

18

TURKUUNIVERSITYOFAPPLIEDSCIENCESTHESIS|TamNguyenTruongThanh

Picture5.Broadcastingconnectivitysignal.

Withthehelpofsensortaglibrary,thesensorwasdetectedwiththediscoveryfunction.Fromtheconsolewindow,thesensor’stypeanddevice’sIDwereprintedouttoindicatethattheyfoundeachother.

Picture6.Sensorinformationrecognizedbynodeserver.

Inaddition,anotherstepwasaddedtoverifywhetherornotwearechoosingtherightsensortoconnectto.Aftergettingdiscovered,everytimewepressanybuttononthesensor,theserverwillshowitsrecognition.Therearetwomethodstobecomeestablishedwiththeserver.Wecantakeaphysicalactiondirectlyonsensorbyholdingbothbuttonsatthesametimeor,ontheotherhand,byclickingonconnectbuttonfromthedashboard.Theindicationwillbereflectedontheserverconsole.Theuserinterface(UI)offersoptionstoenablefromonlyonetoallthebuilt-insensorsinordertoadapteveryneed.

Page 20: MONITORING ENVIRONMENTAL VARIABLES USING SENSORTAG · Picture 1. Concept of a monitoring system. 6 Picture 2. SensorTag CC2650. 8 Picture 3. The implementation structure. 12 Picture

19

TURKUUNIVERSITYOFAPPLIEDSCIENCESTHESIS|TamNguyenTruongThanh

Picture7.Sensorpanelindashboard.

Oncetheconnectionisup,temperature,humidityandlightdensitysensorsareactivatedaccordingly.Measurementsstarttofloodintonode-serverwithanintervalof1second.Atthesametime,MongoDBisalsoreceivingthosevaluesthenstoringthemwithinthecollectionnamedafterthecurrentdate.

Page 21: MONITORING ENVIRONMENTAL VARIABLES USING SENSORTAG · Picture 1. Concept of a monitoring system. 6 Picture 2. SensorTag CC2650. 8 Picture 3. The implementation structure. 12 Picture

20

TURKUUNIVERSITYOFAPPLIEDSCIENCESTHESIS|TamNguyenTruongThanh

Picture8.ResponsesfromserverwhenconnectedtoSensorTag.

Allofthoseflowsofdataarehandledbysocket.io.Bysettingupthebridgesbetweenthenodeserver,thesensortagmoduleandtheUI,thenumbersweretransferredbackandforthseamlesslybetweenthoseendswhichcreatesadataflowthroughouttheentireapp.

4.5 DataFlow

BetweenUIandserver

Afterusershavemadetheirchoicesofwhichtypeofdatatheywanttoretrievefromthesensor,asocketnamed“custom”wascreatedinordertosendthatcommandstraighttosensortagmodule.Themodulethenenablesthefollowingsensorscorrespondingly.

Page 22: MONITORING ENVIRONMENTAL VARIABLES USING SENSORTAG · Picture 1. Concept of a monitoring system. 6 Picture 2. SensorTag CC2650. 8 Picture 3. The implementation structure. 12 Picture

21

TURKUUNIVERSITYOFAPPLIEDSCIENCESTHESIS|TamNguyenTruongThanh

Figure1.DatatransferfromUItoservervia“custom”socket.

Inaddition,anothersocketwasinitializedbythenameof“valuesOut”.ThissocketisinchargeofforwardingvalueswhicharereceivedfromsensortagmoduletotheUIforpresentation.Thevaluesarepresentedingauges(meters)andingraphs.

Figure2.Socket“valuesOut”structure.

Lastly,inordertokeeptrackofhowmanysensorsareoperating,the“signal”socketiscreated.Theroleofthissocketistosynchronizeallthestatesofsensortoalltheconnectedclients.

Page 23: MONITORING ENVIRONMENTAL VARIABLES USING SENSORTAG · Picture 1. Concept of a monitoring system. 6 Picture 2. SensorTag CC2650. 8 Picture 3. The implementation structure. 12 Picture

22

TURKUUNIVERSITYOFAPPLIEDSCIENCESTHESIS|TamNguyenTruongThanh

Figure3.Socket“signal”.

Betweendatabaseserverandnodeserver

MongoDB,ontheotherhand,capturesvaluesrightaftertheyhavearrivedatthenode-server.Alongwiththetimestamp,eachentrywasinputtothedatabaseservereverysecondinadesignatedstructurewhichisexplainedinlatersection.

Figure4.Recordsaresenttodatabase.

Page 24: MONITORING ENVIRONMENTAL VARIABLES USING SENSORTAG · Picture 1. Concept of a monitoring system. 6 Picture 2. SensorTag CC2650. 8 Picture 3. The implementation structure. 12 Picture

23

TURKUUNIVERSITYOFAPPLIEDSCIENCESTHESIS|TamNguyenTruongThanh

4.6 Userinterface

Dashboard

Intermsofvisualizationofthecurrentstatus,fromthedashboard,allthevaluesareupdatedeverysecondinreal-time.Thechartinthesectionbelowisplottedinordertovisualizeeverychangesincethesensorisconnected.

Picture9.Dashboardinterface.

Report

Thispagewasintendedtopresentthedatawhichisstoredinthedatabaseserverduringthetimebeing.Wewillhavetwofieldstoselect:dateandtypeofdata.Sincethestructureofdatabaseinthisprojectwascategorizedbydate,userscanchoosewhichtypeofdatatheywanttoqueryonthatspecificdayfromtheformabovethegraph.

Page 25: MONITORING ENVIRONMENTAL VARIABLES USING SENSORTAG · Picture 1. Concept of a monitoring system. 6 Picture 2. SensorTag CC2650. 8 Picture 3. The implementation structure. 12 Picture

24

TURKUUNIVERSITYOFAPPLIEDSCIENCESTHESIS|TamNguyenTruongThanh

Picture10.Showrecordspanel.

Afterthe”SHOW”buttonwaspressed,requestsarethenforwardedtotheMongoDBcontainingthetypeofdataalongwiththedatebyuser’schoicetoextracttherecords.Afterthat,allthedatawillbeconvertedintograph-friendlydataformatthenisvisualizedbyagraphasbelow.

Picture11.Visualizedgraphofdata.

Page 26: MONITORING ENVIRONMENTAL VARIABLES USING SENSORTAG · Picture 1. Concept of a monitoring system. 6 Picture 2. SensorTag CC2650. 8 Picture 3. The implementation structure. 12 Picture

25

TURKUUNIVERSITYOFAPPLIEDSCIENCESTHESIS|TamNguyenTruongThanh

OnemoreintegratedfeatureofHighChartslibraryisthatwecanexportanygraphtovarietyofimageformatssuchasPNG,JPEGandPDF.Theseexportedimagescanbeusedforstoringorsendingbyemail.

Picture12.ExportingfeatureofHighCharts.

4.7 Database

Whenitcomestotheapplication,thedatabaseplaysanessentialrole.Forthisparticularproject,thedatabaseserverisnotonlyinchargeofstoringmeasurementsfromthesensorbutalsohandlingrequestsfromuser.Comparedwiththerelationaldatabase,MongoDBhasadifferentapproachtobuilditsownstructure.Asmentionedearlier,insteadoftables,collectionsareusedtostoreentrieswhicharecalledkeys.EachkeyconsistsofanobjectID,time,measurementsandeachcollectioncontainsrecordsforoneday.DatabaseName:sensorAppCollectionnames:namebydateKeys:

● Hour-Integer● Minute-Integer● Second-Integer● Temp-String

Page 27: MONITORING ENVIRONMENTAL VARIABLES USING SENSORTAG · Picture 1. Concept of a monitoring system. 6 Picture 2. SensorTag CC2650. 8 Picture 3. The implementation structure. 12 Picture

26

TURKUUNIVERSITYOFAPPLIEDSCIENCESTHESIS|TamNguyenTruongThanh

● Humi-String● Lux-String● Gyros-String

AnexampleofarecordindatabaseisdemonstratedinPicture13below.

Picture13.StructureofakeyinMongoDBdatabase.

Page 28: MONITORING ENVIRONMENTAL VARIABLES USING SENSORTAG · Picture 1. Concept of a monitoring system. 6 Picture 2. SensorTag CC2650. 8 Picture 3. The implementation structure. 12 Picture

27

TURKUUNIVERSITYOFAPPLIEDSCIENCESTHESIS|TamNguyenTruongThanh

5 PERFORMANCE

PerformanceplaysanimportantroleinwebapplicationsandsensorAppisnotanexception.Acharacteristicofthissystemisconstantlyretrievingvaluesfromthesensorwithatinyintervalsoaburdensomeloadofdatawillbecarriedbythedatabase.Becauseofthat,transferringsuchahugeamountofdatatoplotonthegraphbecomeschallengingforboththeserverandclient-side.Sinceeverytimeusersrequestarecordforalongperiodoftime,thedatabaseserverhastomakeaquerywitharesultcanbeuptothousandsofentriesorevenmore.Regardingthemechanismbehindit,thedatabaseserverprocessestherequestbyusersfromthedashboard,thenreturnswithanarrayofobjectsaccordingly.Beforethearrayissentbacktotheclient-side,NodeJSconvertsthevaluestochart-compatibletypesothatthechartcanpresentthoselateron.Apointinthegraphwastechnicallyrepresentedbyatimeandarequestedvaluewhichiseithertemperature,humidityorlightdensity(lux).Aspresentedinanexamplebelow,xisthetimestamp(milliseconds)andyisthetemperature(°C).

Picture14.Apointtransferredfromservertographs.

Duringtheexportingdatastagefromdatabasetoclient,anobstacle,whichisamethodoftravelingvaluesacrossthesystem,hasbeenaddressed.Sincetheamountofdataisenormous,theprocessingspeedwilldependonmanyaspectsnamelyquerying,traversing,convertingandplottingtime.Aftertryingdifferentapproaches,thefinalsolutionhasperformedwell..

Page 29: MONITORING ENVIRONMENTAL VARIABLES USING SENSORTAG · Picture 1. Concept of a monitoring system. 6 Picture 2. SensorTag CC2650. 8 Picture 3. The implementation structure. 12 Picture

28

TURKUUNIVERSITYOFAPPLIEDSCIENCESTHESIS|TamNguyenTruongThanh

Picture15.Howdataishandleduponrequests.

Theideaisthatallthecalculationaswellasconvertingjobswillbegiventotheserverwhichthentransferstheresulttothegraphwithoutanyadditionaladjustment.Aftermanyattemptsandmodifications,themostefficientwaytotransferdatafromtheservertotheUIisbyusingAjax.Ajaxcallallowsdatatraversefromoneendtoanotherwithoutrefreshingthewebpage.Therefore,userexperiencewasimproveddramatically.Ontheotherhand,queryingandinsertingentriesarehandledsimultaneouslyonthedatabaseserver.

Page 30: MONITORING ENVIRONMENTAL VARIABLES USING SENSORTAG · Picture 1. Concept of a monitoring system. 6 Picture 2. SensorTag CC2650. 8 Picture 3. The implementation structure. 12 Picture

TURKUUNIVERSITYOFAPPLIEDSCIENCESTHESIS|TamNguyenTruongThanh

P

6 ASSESSMENT

Theprojectcoversmanyaspectsofhowtoimplementareal-timewebapplicationfromscratch.Withacombinationofmanyrecenttechnologiesonthemarket,allthecomponentscooperatesmoothly.Moreover,withasimpleyetpracticaluserinterface,themonitoringtasknowhasbecomemoretransparent.Infact,therequirementsenabletheauthortolearnmoreandhaveachancetoapplyprogramingskillsaswellasachieveasignificantamountofknowledgethroughoutthemaking.Moreover,troubleshootingorproblemsolvingskillwasgainedgraduallywhilefacingobstaclesontheway.Twomonthsincludingresearchingtimeisthetotalamounttimetobuildeverythingfromanideatothefullyworkingapp.Ittook1weekatleastduringthetimelinetotestoutallthecomponentsaswellascombinethemtogether.Thefinaltestingandtuningupphasestookanotherweekinordertoensuretheoutcomemettheexpectations.

6.1 Obstacles

Althoughtheapphasbeenfunctional,therearestillproblemsthatneedtobeaddressed.Firstofall,themeasurementcompletelydependsonthesensor.Duringthedebuggingstage,theprovidedsensorhasdisplayedastrangebehavior.Forexample,thehumiditysensorrandomlysendsitspeakvalueswhichare-40degreeCelsiusand100%humiditytobeprecisetotheserverinsteadofitscurrentvalues.Despitethenewestfirmwareinstalledorfreshbatteryinstallation,noimprovementhasbeenseen.Overall,itmostlikelycouldbeahardwarefault.Secondly,theperformanceofdatabasehasitsowndownside.Theproblemcouldbeavoidedbyahighspeedconnectionbetweentheclientandtheserverwhilequeryinghistoryrecordsfromdatabase.Becauseofahugeamountofentriesfloodingintothesamesocket,itcancauselatencyinresponse.Lastly,sincetheserverdoesnothaveanyencryptionmethodtobondwith,securitymattersshouldbetakenintoaccount.Nocredentialisrequiredtoaccessthedashboardremotelysoitistotallypossibleifoutsiderswanttointerferewiththeoperationofthesystem.

6.2 PotentialFutureImprovement

Everythinghasitspositiveandnegativesideand,ofcourse,thisappisnotanexception.Aconsiderednumberoftaskshavebeenaccomplished

Page 31: MONITORING ENVIRONMENTAL VARIABLES USING SENSORTAG · Picture 1. Concept of a monitoring system. 6 Picture 2. SensorTag CC2650. 8 Picture 3. The implementation structure. 12 Picture

TURKUUNIVERSITYOFAPPLIEDSCIENCESTHESIS|TamNguyenTruongThanh

30

flawlessly.However,thereweresomeimprovementsthatcouldhavebeenmadetotakeittoanotherlevel.Firstly,technically,anaccuracyoflightdetectionneedstobeincreased.Atthemoment,theconceptoftrackingopening/closingdoormovementsintuitivelydependsonthefluctuationsofthelinechart.Theoretically,thelightingleveliscompletelydifferentatanyrandompointinthemedium.Becauseofthat,everytimethedoorwasopened/closed,thechangeswerereflectedbytheupwardordownwardtrendonthegraph.

Picture16.Lightdensitypresentation.

Secondly,anadministratormayneedananalyticalreportforalongerperiodnotjustaday.Becauseofthatdemand,theexportingrecordsfeatureshouldbeupgradedtoalargerscalewhichallowstheadministratortoreviewastatisticforaweek,amonthorevenayear.Implementationdoesnotseemtobesophisticatedafterall.However,thetransmittingspeedofrecordsacrossthenetworkshouldbetakenintoaccount.Forafullday,wehave86400recordswith1sintervaltobeexact.Ontheotherhand,roughly,2.592e+6recordsareregisteredinamonthorevenaexcessivenumbersofrecordsinayear.Inaddition,thestruggleisnotonlywiththebandwidthofnetworkbutthenumbersofconnectionsaccessingtheappinordertoexportatthesametimeisalsoachallenginngproblem.Theperformancecouldbeimprovedbyusingefficienttweakingmethods.

6.3 Limitations

Powerconsumption

Thesensorisrequiredtofunctionconstantlytokeeptrackofeveryeventinrealtime.Asmentioned,thelimitinbatterycapacityisaseriousconcern.Throughoutthetestingphrase,with1sintervalfortransmission

Page 32: MONITORING ENVIRONMENTAL VARIABLES USING SENSORTAG · Picture 1. Concept of a monitoring system. 6 Picture 2. SensorTag CC2650. 8 Picture 3. The implementation structure. 12 Picture

TURKUUNIVERSITYOFAPPLIEDSCIENCESTHESIS|TamNguyenTruongThanh

31

andtheuseofonecoin-sizebattery,thesensorlastsonlyafewdaysbeforethebatteryrunsout.Thatresultwasconductedwhenallthesensorswereenabled,namelytemperature,humidity,luxometerandgyroscope.Themoresensorsareenabled,themorepowertheappconsumes.AccordingtoMishaandheranalysis[12],thepowerconsumptionofthesensorthroughoutoperationstageswasreflectedbythetablebelow.Table10.Powerconsumption.

Currentinmilliamp(mA)

Poweringon 12

Standby 0.24

TemperaturesensorON 0.84

Temperature+HumiditysensorsON 0.92

Lightsensor(Luxometer) 0.56

Motionsensor 4.16

Barometricsensor 0.5

Allsensorson(100mssamplerate) ~5.5

Followingtheanalysis,the240mAhbatterycanonlypowerthesensorforlessthan48hourswithmaximumtransferrateorroughly240hourswithjustonlytemperatureandhumiditysensorson.ThisresultisfarfromwhatTexasInstrumentspromotesontheirwebsitewhichitcanlastforayear.Therefore,inordertoaccomplishthatrateofmaintenance,wecanuseanexternalpowersupply.Becauseoflackofphysicalinterface,thesensorneedssupportfromthedevelopmentkittoconnecttoexternalbattery(powerbank)viaUSBport.

Page 33: MONITORING ENVIRONMENTAL VARIABLES USING SENSORTAG · Picture 1. Concept of a monitoring system. 6 Picture 2. SensorTag CC2650. 8 Picture 3. The implementation structure. 12 Picture

TURKUUNIVERSITYOFAPPLIEDSCIENCESTHESIS|TamNguyenTruongThanh

32

Gyroscopeaccuracy

Becauseofthesensitivityoflightsensor(luxometer),everyminormovementofthedoorwillberegistered.Therefore,dependingonlightdensityvaluealonetodeterminedoormovementisnotpracticalinareallifescenario.However,combiningthatdatawithvaluesfromgyroscopemakesthedeterminationmuchmoreaccurate.Forexample,whenthedoorstartstomove,thegyroscopereflects3valuesfrom3-axisand,simultaneously,luxometerprovidesfluctuationsfromlightdensity.SensorTagcomeswithdifferentsensorsdedicatedtomotiondetectionsuchasaccelerometerandgyroscope.Inordertotracktheobject'smovements,inthiscaseisthedoor,thegyroscopesensorwasenabled.Thissensorhas3axisvariablessimilartoaccelerometerwhicharex,yandz.DependingonthepositiontheSensorTagwasplacedontothedoor,oneofthe3variableswouldchangeaccordinglytothedoormovements.Bycalculatingthedifferencebetween2valueswhenthedoorat2positions,wecandeterminewhetherornotthedoorisbeingopened.

Picture17.Gyroscopepresentation.

Regardingthecalculationmethod,thevaluesof3axis(X0,Y0,Z0)whenthedooratrestwereinitiallymeasuredthensubtractedwithvalues(X,Y,Z)whenthedoorstartedtomove.Thedifferencesbetweentheinitialvaluesandcurrentvaluesof3axisarecalledDelta1,Delta2,Delta3.

Delta1=|X0-X|Delta2=|Y0-Y|Delta3=|Z0-Z|

Equation1.Differenceswhensensorchangingposition.

Sincethesensorisextremelysensitive,evenasmallmovementcanmakeadifference.Therefore,aso-calledOffsetConstant(C)isalsocreatedtoexcludethosetinychancesfromalgorithm.Inthiscase0.8istheoffsetconstant.Withthat,wecandecidewhetherthedoorisopenedorclosedbycomparingDeltastoOffsetConstant(C).

Page 34: MONITORING ENVIRONMENTAL VARIABLES USING SENSORTAG · Picture 1. Concept of a monitoring system. 6 Picture 2. SensorTag CC2650. 8 Picture 3. The implementation structure. 12 Picture

TURKUUNIVERSITYOFAPPLIEDSCIENCESTHESIS|TamNguyenTruongThanh

33

Table11.SensorstatesdecidedbyDelta.

Delta1 Delta2 Delta3

>C Moving Moving Moving

<=C Atrest Atrest Atrest

Page 35: MONITORING ENVIRONMENTAL VARIABLES USING SENSORTAG · Picture 1. Concept of a monitoring system. 6 Picture 2. SensorTag CC2650. 8 Picture 3. The implementation structure. 12 Picture

TURKUUNIVERSITYOFAPPLIEDSCIENCESTHESIS|TamNguyenTruongThanh

34

7 CONCLUSION

Astheresult,afullyfunctionalmonitoringservermeetstheinitialobjectives:

• Measuresenvironmentalvariablesnamelytemperature,humidity,lightdensity,gyroscopevaluesfromtheSensorTag.

• Hasareal-timevisualizedgraphicalinterface.• High-capacitydatabaseprovidesanalyticaldatainformofgraphs

withexportingfeaturesbuilt-in.• Providesamanaginginterfacecanberemotelyaccessedwidely

fromanytime,anywhere.• Isfullycompatiblewithmostofbrowsersanddevices.

Atthetimethisthesiswaswritten,thisapproachtoSensorTagdevicesisnotpopular.Mostofrecentprojectsusemobiledeviceasarelaydevicetoforwardinformationfromsensortothe“cloud”.Usersthenhavetousewebservicefromtheproviderinwhichitisimplementedtoreviewthereceiveddata.Mostservicesdonotprovidethedatabaseextractionfeature.WiththehelpofacombinationofNodeJSserver,MongoDB,socket.ioandFront-endframeworks,wecanalmostestablishallthewebapplicationinfrastructurenotonlyinacommercialbutalsoinanindustrialenvironment.ThisappisadefiniteexampleoftheInternetofThingsinpracticewhichisatrendinembeddedprogramingnowadays.Inconclusion,theapplicationisusingallthemoderntechnologiessoitispracticalinproduction.Itrunsproperlyandmeetsalltherequirementsasexpectedeventhoughtherearestilllimitsintechnologyaswellastheexperienceoftheauthor.Inordertocompletethestack,manyskillshavebeenrequiredincludingfluencyinprogramminglanguages,manipulatingandhandlingbigdatainanetwork.Moreover,communicationbetweenphysicaldeviceandtheAPIisalsoachallenge.Allinall,thereisspaciousroomforimprovementsinthefuture.Despitethesizeofthisproject,theversatilityandpossibilityareendlessifwecankeepthefoundationandimplementspecificinfrastructureontoptosuiteveryneed.

Page 36: MONITORING ENVIRONMENTAL VARIABLES USING SENSORTAG · Picture 1. Concept of a monitoring system. 6 Picture 2. SensorTag CC2650. 8 Picture 3. The implementation structure. 12 Picture

TURKUUNIVERSITYOFAPPLIEDSCIENCESTHESIS|TamNguyenTruongThanh

35

REFERENCES

[1]TexasInstrumentsSensortag.Consulted30.3.2016.Availableathttp://www.ti.com/tool/cc2650stk#1.[2]SimpleLinkSensorTagDebuggerDevPack.Consulted30.3.2016.Availableathttp://www.ti.com/tool/cc-devpack-debug.[3]BluetoothBLE.Consulted30.3.2016.Availableathttps://www.bluetooth.com/what-is-bluetooth-technology/how-it-works.[4]MithunSatheesh,BrunoJosephD’mello,JasonKrol.2015.WebDevelopmentwithMongoDBandNodeJS.2ndEdition.PacktPublishing.E-book.Consulted5.4.2016.[5]SandeepMistry.2015.Node-sensortag.Consulted15.4.2016.Availableathttps://github.com/sandeepmistry/node-sensortag. [6]FionnKelleher.11.8.2014.Consulted20.4.2016.Availableathttps://nodesource.com/blog/understanding-socketio/.[7]RyanBenedetti,RonanCranley.2011.HeadFirstjQuery.1stEdition.O’ReillyMedia,Inc.Consulted20.4.2016[8]MongoDB.https://docs.MongoDB.com/manual/.Consulted25.4.2016[9]JoeKuan.2015.LearningHighCharts4.PacktPublishing.E-book.Consulted5.5.2016.[10]JimR.Wilson.2013.Node.jstheRightWay.ThePragmaticProgrammers.Consulted10.5.2016.[11]mLab.Consulted11.5.2016.Availableathttps://en.wikipedia.org/wiki/MLab.[12]Misha,9/6/2015.TISensorTag2Powerconsumptionanalysis.Consulted30.5.2016.Availableathttp://mobilemodding.info/2015/06/ti-sensortag-2-power-consumption-analysys/.

Page 37: MONITORING ENVIRONMENTAL VARIABLES USING SENSORTAG · Picture 1. Concept of a monitoring system. 6 Picture 2. SensorTag CC2650. 8 Picture 3. The implementation structure. 12 Picture

Appendix1

TURKUUNIVERSITYOFAPPLIEDSCIENCESTHESIS|TamNguyenTruongThanh

Appendix1-Applicationtree.app.jspackage.jsonbin└── wwwpublic├── images├── javascripts ├── dashboard.js ├── socket.io.js ├── sensortag.js └── report.js└── stylesheets ├── style.css └── report.cssroutesviews├── error.pug├── dashboard.pug├── report.pug└── layout.pug

Page 38: MONITORING ENVIRONMENTAL VARIABLES USING SENSORTAG · Picture 1. Concept of a monitoring system. 6 Picture 2. SensorTag CC2650. 8 Picture 3. The implementation structure. 12 Picture

Appendix2(1)

TURKUUNIVERSITYOFAPPLIEDSCIENCESTHESIS|TamNguyenTruongThanh

Appendix2–Sensortagmodulecodevarasync=require('async');varSensorTag=require('sensortag');//sensortaglibraryvarstatus=0;vartOn,hOn,lOn,gOn;SensorTag.discover(function(tag){ //whenyoudisconnectfromatag,exittheprogram. functiondisconnectTag() { tag.on('disconnect',function(){ console.log('disconnected!'); module.exports.dis=1; process.exit(0); }); } functionconnectAndSetUpMe(){

//attempttoconnecttothetagconsole.log('connectAndSetUp');

tag.connectAndSetUp(enableIrTempMe); //whenyouconnect,callenableIrTempMe

}functionenableIrTempMe(tempON,humiON,luxON,gyroON){

if(tempON){ console.log("Temperaturesensorisenabled!"); tag.enableIrTemperature();}if(humiON){

console.log("Humiditysensorisenabled!"); tag.enableHumidity();}if(luxON){ console.log("Luxometersensorisenabled!"); tag.enableLuxometer();}if(gyroON){ console.log("Gyroscopesensorisenabled!"); tag.enableGyroscope();}

Page 39: MONITORING ENVIRONMENTAL VARIABLES USING SENSORTAG · Picture 1. Concept of a monitoring system. 6 Picture 2. SensorTag CC2650. 8 Picture 3. The implementation structure. 12 Picture

Appendix2(2)

TURKUUNIVERSITYOFAPPLIEDSCIENCESTHESIS|TamNguyenTruongThanh

}functiondisableSensors(){

//disableallsensorstag.disableHumidity(tag.disableLuxometer(tag.disableIrTemperature(tag.disableGyroscope())));console.log("Disableallsensors!!!");disconnectTag();

}functionnotifyMe(tempON,humiON,luxON,gyroON){ console.log('Sensor'+tag.type+'isconnected!'); console.log('Device\'sIDdetected:'+tag.id); console.log('--------------------------------'); console.log(''); tag.unnotifySimpleKey(); if(tempON) { tag.notifyIrTemperature(tag.setIrTemperaturePeriod(1000,listenForTempReading)); } if(humiON) { tag.notifyHumidity(tag.setHumidityPeriod(1000,listenForHumidity)); } if(luxON) { tag.notifyLuxometer(tag.setLuxometerPeriod(1000,listenForLuxometer)); } if(gyroON) { tag.notifyGyroscope(tag.setGyroscopePeriod(1000,listenForGyroscope)); }functionlistenForLuxometer(){ //ListenforLuxometer tag.on('luxometerChange',function(lux)

{ //console.log('luxvalue=',lux);

module.exports.lux=lux.toFixed(1); });}functionlistenForGyroscope(){ //ListenforLuxometer vartempX,tempY,tempZ,state;

Page 40: MONITORING ENVIRONMENTAL VARIABLES USING SENSORTAG · Picture 1. Concept of a monitoring system. 6 Picture 2. SensorTag CC2650. 8 Picture 3. The implementation structure. 12 Picture

Appendix2(3)

TURKUUNIVERSITYOFAPPLIEDSCIENCESTHESIS|TamNguyenTruongThanh

tag.on('gyroscopeChange',function(x,y,z){ //console.log('Gyroscope:'); //console.log('x:',x.toFixed(1)); //console.log('y:',y.toFixed(1)); //console.log('z:',z.toFixed(1)); module.exports.gyro=x.toFixed(1)+"|"+y.toFixed(1)+"|"+z.toFixed(1); if(x.toFixed(1)-tempX>0.8) { state=1; } else { state=0; } module.exports.state=state; tempX=x.toFixed(1); tempY=y.toFixed(1); tempZ=z.toFixed(1); });}//Whenyougetanaccelermeterchange,printitout:functionlistenForTempReading(){

tag.on('irTemperatureChange',function(objectTemp,ambientTemp){ //console.log('\tObjectTemp=%ddeg.C',objectTemp.toFixed(1)); //console.log('\tAmbientTemp=%ddeg.C',ambientTemp.toFixed(1)); varintemp=ambientTemp.toFixed(1); module.exports.temp=ambientTemp.toFixed(1); });}//GetdatafromHumiditySensor(+Temperature)functionlistenForHumidity(){

tag.on('humidityChange',function(temperature,humidity){//console.log('\tTemperature=%ddeg.C',temperature.toFixed(1));//console.log('\tHumidity=%d%H',humidity.toFixed(1));module.exports.humi=humidity.toFixed(1);varintemp=temperature.toFixed(1);varinhumid=humidity.toFixed(1);});}//whenbuttonspressedfunctionlistenForButton(){ tag.on('simpleKeyChange',function(left,right){

console.log("Device:"+tag.type); console.log("DeviceID:"+tag.id);

Page 41: MONITORING ENVIRONMENTAL VARIABLES USING SENSORTAG · Picture 1. Concept of a monitoring system. 6 Picture 2. SensorTag CC2650. 8 Picture 3. The implementation structure. 12 Picture

Appendix2(4)

TURKUUNIVERSITYOFAPPLIEDSCIENCESTHESIS|TamNguyenTruongThanh

if(left){ console.log('leftbuttonPRESSED!'); } if(right){ console.log('rightbuttonPRESSED!'); } //ifbothbuttonsarepressed,disconnect: if(left&&right){ console.log("Device:"+tag.type+"withidof:"+tag.id+"connected!"); enableIrTempMe(); //tag.disconnect(); } }); }//Nowthatyou'vedefinedallthefunctions,starttheprocess:tag.connectAndSetUp( function(){ varintervalID=setInterval(function() { //console.log("Checkstatus:",status); if(status==1) { notifyMe(tOn,hOn,lOn,gOn); enableIrTempMe(tOn,hOn,lOn,gOn);

//connectedsignal clearInterval(intervalID); varsecondIntervalID=setInterval(function(){ if(status==2) { disableSensors(); clearInterval(secondIntervalID); } },1000); } },1000); console.log("SensorType:",tag.type); console.log("SensorID:",tag.id); module.exports.sta=status; module.exports.type=tag.type; tag.notifySimpleKey(listenForButton);//startthebuttonlistener);

Page 42: MONITORING ENVIRONMENTAL VARIABLES USING SENSORTAG · Picture 1. Concept of a monitoring system. 6 Picture 2. SensorTag CC2650. 8 Picture 3. The implementation structure. 12 Picture

Appendix2(5)

TURKUUNIVERSITYOFAPPLIEDSCIENCESTHESIS|TamNguyenTruongThanh

});});module.exports=function(s,tempOn,humiOn,luxOn,gyroOn){ status=s; tOn=tempOn; hOn=humiOn; lOn=luxOn; gOn=gyroOn;}