Integrating Bluetooth Low Energy Peripherals with the Amulet AnnaJ.Knowles SeniorThesis AdvisedbyProfessorDavidKotz DartmouthComputerScienceTechnicalReportTR2016-807 Abstract TheAmuletisahealthmonitor,similarinsizeandshapetoasmartwatchbut specificallydesignedtohavealongerbatterylifeandhandledatasecurely. Itis equippedwithaBluetoothLowEnergy(BLE)radioinordertoreceivedatafrom BLE-enabledsensorsandtransmitdatatosmartphones,butthefullimplementation of BLE communication on the Amulet is still a work in progress. This thesis describesarchitecturalchangesthatimprovetheAmulet’sabilitytoreceivedata fromavarietyofBLE-enabledsensorsandmakeiteasierfordeveloperstointegrate newBLE-enabledsensorswiththeAmuletbyintroducingsupportforconnectingto multiplesensorsatthesametime,rewritingtheradiocodetobemoregeneric,and exposingBLEfunctionalitytotheAmuletOS.Wediscusstherelevantpartsofthe AmuletOSandtheBLEprotocolasbackground,describethecurrentstructureof BLEcommunicationsontheAmulet,anddocumenttheproposedchangestocreate asystemforeasilyintegratingnewBLE-enabledsensorsandhandlingconnections tomultiplesensorssimultaneously. 1 Introduction TheAmuletisawrist-wornhealthmonitor,similarinsizeandshapetoasmartwatchand equippedwithabuilt-inclock,accelerometer,lightsensor,microphone,andtemperature sensor[1].AmuletwasdesignedinaresearchcollaborationbetweenDartmouthCollege andClemsonUniversity. Itisintendedforcontinuousmonitoringofpersonalhealth statisticsandenvironmentalvariables,usefuleitherforresearchstudiesortoempower individualstomonitortheirownhealthwhilekeepingtheirdatasecure. Thebuilt-in sensorsareinsufficientfortherangeofdatathataresearchermightwanttocollect,so theAmuletisalsoequippedwithaBluetoothLowEnergy(BLE)radiothatcanconnect ittoBLE-enabledsensorsandenableittouploaddatatoasmartphoneorserver.Amulet isdesignedtohavelow-powerdemands,acorrespondinglylongbatterylife,andtobe extensiblebyexternaldevelopers[2]. Thearchitectureandsoftwarearedesignedto makeiteasyfordeveloperstowritenewevent-basedapplicationsusingtheexisting APIcalls, however, hardwareislesseasilymodified. Itisthereforeverydifficultto 1 quicklyextendthesensingcapabilitiesoftheAmuletbyaddingnewinternalsensors. Luckily,theBLEradioextendstheAmulet’sdatacollectionabilitieswithouthardware modifications,asitcanbeconnectedtoavarietyofBLE-enabledsensorsthatproduce differenttypesandformatsofdatasimplybymakingsoftwarechanges. The current approach for BLE connections in AmuletOS is hard wired and not extensible,tailoredspecificallytoaHeartRateMonitorthatprovidesdataasdefined bytheBLEstandard. Itworkscorrectlyandefficientlyforreceivingheart-ratemea- surementsbutcannotbeeasilymodifiedtoreceiveotherdata. Toaddaanothertype ofsensor–onethatproducesdatainadifferentformatandwithadifferentlength–a developerwouldhavetomodifycodeonthetwomicrocontrollersthatconstitutethe Amulet’shardware. MuchofthecodeimplementingtheBLEfunctionalityontheradio wouldneedtoberewritten,asitisspecifictotheHeartRateMonitorfunctionalityand formatting;however,simplysubstitutingtheformattingofthenewsensortypewould recreatetheproblemofnon-extensibilityintheradiocode. TheAmuletOSassumes thattheonlytypeofBLEsensorisaheart-ratemonitor,andthecurrentcoreandradio coderequiresubstantialrestructuringtoallowtheAmulettosupporttwodifferenttypes of sensors in the same firmware image. Amulet will be more useful if it is easy to extendthefunctionalityofthedevicebyintegratingnewBLEsensors,agivenfirmware imagecancontaintheformattingandconnectioninformationformorethanonetype ofsensor,andmultiplesensorscanbeconnectedatthesametime. Easy,reliableBLE communicationisessentialtothevisionofAmuletasauseful,extensibleplatformfor futureresearchstudiesorforwideusage[2]. ThisthesisdescribesourredesignoftheAmuletOSBLEarchitecturetosupport newanddifferentexternalsensorsandmakeiteasierforfuturedeveloperstointegrate differenttypesofBLEsensorswithAmuletOS. 2 Background ThefollowingsectionprovidesabriefoverviewofthefeaturesoftheAmuletplatform and the Bluetooth Low Energy protocol that are relevant to the integration of BLE sensorswiththeAmulet. 2.1 Amulet The Amulet is implemented on two microcontrollers: an MSP430 – the application processorforprimarycomputation–andannRF51822M0microcontrollerthatcontains andcontrolstheradio[1]. FordiscussingBLEcommunications,wefinditusefulto think of the Amulet in three layers: the application layer, the core, and the radio as showninFigure??. TheapplicationsandcoreAmuletOSbothrunontheapplication processor,whiletheradiocontrolsrunontheM0.CommunicationbetweentheMSP430 andtheM0occursovertheSPI!(SPI!)bus. Applications: AmuletapplicationsarealleventdrivenandexpressedasaFSM! (FSM!)intheQMframework. Atypicalapplicationtransitionsbetweenawell-defined setofstatesinresponsetosignalsgeneratedbythecoreuponuserinput(bybutton orcapacitivetouchslider),timerinterrupts,orthearrivalofdatafromasensor. Each 2 Figure1: Thehigh-levelarchitectureoftheAmulet state may contain some logic or calls to AmuletOS functions written in a restricted versionofCthatdoesnotallowtheuseofpointersandexecuteduponentryorexit. Theresultinggraphicalrepresentationofthestatemachineistranslatedintostandard C by the compiler. An example blood-pressure application written in QM is shown inFigure??. TheFSM!structuremakesiteasiertoreasonaboutthecorrectnessof applications and, as long as the application is written correctly, prevents them from gettingintounrecoverablestates. ApplicationsonlyinteractwiththeAmuletOSthroughtheAPIfunctionsdefined intheAmulet.hheaderfile. AnXMLfileisusedtoexplicitlyspecifythefunctions inAmulet.hthateachapplicationcanuse. Applicationsareassumedtobepotentially maliciousandarenotgivendirectcontroloftheradiooraccesstootherenergyexpensive functionalitytopreventthemfromrunningdownthebatteryormonopolizingtheradio. The Amulet compilation process includes static analysis to check that applications are only using permitted API calls and are not accessing memory outside of their allotedblock,whiletheQMtranslatorensuresthattheyhaveseparatenamespacesfor all variables and states by appending the application ID to all function and variable names[?]. Togetdatafromasensor,applications“subscribe,”thatis,theyasktoreceivean eventfromthecorewheneverdataarrivesfromthatsensor. Toactuallyreceivethedata anapplicationmustcallanAmuletOSfunctiontoretrieveit,astherestrictiononusing pointersmeansthatitcannotbeincludedintheevent. Core: Thecoremanagesapplicationsandsensorsandhandlesallofthehardware andtimerinterrupts. Itservesthesameroleasanoperatingsystemonafullyfledged computer–hencethename“AmuletOS”.Thecorekeepstrackofapplicationsubscrip- tionstosensorsinaqueueandsendseventstosubscribedapplicationswhendatafrom 3 Figure2: AnexampleapplicationtoreceiveanddisplaybloodpressureontheAmulet asensorarrivesoranapplicationtimerexpires. Itrespondstorequestsbyapplications toretrievedata,displaytextonthescreen,andwritevaluestotheSDcard,andruns applicationswheneventsarriveforthemorabuttonispressed. Forapplicationsthatget datafromBLEsensors,thecoreservesasthemediatorbetweentheapplicationandthe radio. ThecorecodeiswritteninstandardCwithoutrestrictions,butmostofthecode baseonlyusesstaticallyallocatedmemoryforthesakeofspeedandtoavoidmemory leaks. Radio: TheBLEstackisimplementedontheM0microcontroller,whichisrespon- sibleforallBluetoothcommunication. Communicationsbetweentheradioboardand theapplicationprocessorhappenoverInter-ProcessCommunication(IPC)ontheSPI! bus,whichservesasaphysicallinkbetweentheMSP430andtheM0. TheIPCprotocol iscustom-definedfortheAmuletOS,withaheaderformatandfield-valuesdefinedin thecorecode. InthefirstimplementationoftheAmuletOSandradiodrivers,theM0wastheentry pointforallsensordataandapplicationsubscriptionswerecreatedinthecoreandthen mirroredontheM0. AllsubscriptiondatawassentoverIPCtoachievethismirroring, butassendingdataovertheSPIbusisslowandenergy-intensivethecurrentiteration oftheAmulethardwareandarchitectureonlystoressubscriptionsinthecore,onthe MSP430. ArecenthardwareupgradeintroducedanewversionoftheM0totheAmulet, andthefullIPCprotocolandbidirectionalcommunicationbetweenthecoreandM0 havenotyetbeenre-establishedsincethatchange,butsendingunwrappeddatafrom theM0tothecoreovertheSPIbusstillworks. Inthisnewerversionofthehardware theM0doesnotreceivealloftheinternalsensordataandisdedicatedtotheBLEstack andtheradiocontrols. 4 2.2 BluetoothLowEnergy BluetoothLowEnergy,alsoknownasBluetoothSmartorBluetoothVersion4.0+,is anewversionofthestandardBluetoothProtocoldesignedspecificallyforlow-power devices[?]. BLE is a connection-oriented protocol; the connection established between two devices. Eachdevicetakesoneoftwodistinctroles: Asensorisaperipheral. Itisa dataproviderandcanonlysustainoneBLEconnectionatatime. TheAmuletplays theroleofacentral.1 ABLEcentralcancreateandmaintainconnectionstomultiple peripheralsatthesametime[?]. Tocreateaconnection,acentral(theAmulet)initiatesascantodiscoverperipherals (sensors)inthearea,receivingadvertisingpacketsfromanyperipheralsthatareactively broadcastingadvertisements. TheadvertisementformatisdecreedbytheBLEstandard GAP!(GAP!)andprovidessomebasicinformationaboutthedeviceanditsfunctional- ity(seeFigure??). Advertisementsarelimitedto31bytesofadvertisingdata[?]. If theinitialadvertisingpacketindicatesthattheperipheralwillprovideascanresponse, thecentralcanrequestmoreinformationabouttheperipheralwithoutconnecting. This scanresponseisinthesameformatastheadvertisingpacketbutis255byteslong[?]. After collecting advertisements the central selects a device to connect to, either by filtering using the information in the advertising packet or by allowing a user to choosetheperipheralfromalist. ItsendsarequesttoconnectusingtheBD!(BD!) addressofthedevice,whichisasix-bytehexstringthatissimilartotheMACaddress ofanetworkeddevice.2 BLEsupportsseveralmethodsforexchangingasharedsecret andperformingsecurityhandshakingatthebeginningofaconnection,butfordevices without a method of input or complex output (like most sensors) the BLE protocol specifiesa“JustWorks”methodofauthentication,whichsimplyestablishesaconnection withoutasecurelysharedsecret[?]. Oncetheconnectionisestablished,theperipheral stopssendingadvertisingpacketsandmaintainsanexclusiveconnectionwiththecentral. TheBLEstandarddefinesofficialGenericAttributeProfile(GATT)profilesand servicesforvarioustypesofdatathataBLE-enableddevicemightprovide. TheGATT profile specifies the services that a device offers and thus the functionality that the devicemustprovide;characteristicswithintheservice,identifiedbyhandles,definethe formatinwhichthedevicedeliversdata[?]. ForexampleaBLE-enabledbloodpressure monitorwouldimplementtheBLE“BloodPressureProfile,”whichencompassesthe BLE“BloodPressureService.” Thisguaranteesthatthedevicewillsendindications with the blood pressure reading in a certain format, allow reading and writing of characteristics,andmaysendadditionalnotificationsiftheoptionalintermediatecuff pressure characteristic is enabled [?]. For most GATT servers, the client can either read values directly or request a message whenever a value changes by turning on notifications or indications. Blood-pressure monitors and heart-rate monitors both operateontheparadigmoftheclientenablingnotifications(orindications)andthen 1Ifitwassendingdatatoasmartphoneitwouldbetheperipheral 2WeassumeallperipheralstheAmuletconnectstowillhavepublicBD!addressesthatareunchangingfor thelifetimeofthedevice,orastaticrandomaddressthatisthesameforthedurationoftheconnection.The BLEGenericAccessProfilealsoallowsforrandomdeviceaddressesthatchangeduringaconnectionasa securityfeature[?]. 5 Bluetooth HC1 H4 Bluetooth HCI Event – LE Meta HCI Event Total Sub Num Event Peer Data ADVERTISING DATA RSSI Packet code: length: event: reports: type: address length: (dB) type : type: (up to 31 bytes) LE Meta LE Adv. 1 BD_ADDR (6 bytes) HCI (0x3e) Report Event (0x02) (0x04) Length: Type: 1 byte Length Type Actual data 2 Flags of flag (variable bytes, data depends on type) Figure3: TheformatofaBLEadvertisingpacket,derivedfromobservationoftrafficin SudikoffwithWireshark waitingfortheservertonotify(orindicate)theclientwiththenewdata. Thisbehavior isspecifiedintheGATTServicedefinition. Notificationsandindicationsessentially perform the same function by allowing the sensor to push data to the client. The onlydifferenceisthattheindicationrequiresanexplicitacknowledgementfromthe Bluetoothstackontheclientandonlyoneindicationcanbesentperconnectioninterval becauseofthisrequirementofexplicitacknowledgement[?]. BLEhasalowenergy impact because the central and peripheral agree on a connection interval – between 7.5msand4s–whentheywillexchangedata,whichallowsthemtosleepinbetweenthe transmissions[?]. Multiplenotificationscanbesentinthesameconnectioninterval(the nRF51822controller,forexample,cansendsixdatapacketsperconnectioninterval) andtheyrequirenoworkontheclientsideattheapplicationlevelwhenreceiving[?]. Notificationsareacknowledgedinthelinklayer,sothereshouldnotbeanydataloss[?]. 3 Related work TheAmuletgrouphaspublishedseveralpapersonthedevicetodate. Sorberet. al. propose the Amullet and describe the goals of the project – security, privacy, and usuability–ina2012papertitled“AnAmuletforTrustworthWearablemHealth”[2]. Theyalsostatethegoalof“allowingAppdeveloperstofocusonthehealth-relatedlogic anddataprocessingwhiletheAmuletsystemautomatesmanysecurityandnetworking tasks”[2],whichinformsthe“easilyextensible”goalofourcurrentproject. Apaper written by Molina-Markham et. al. in 2014 – “Amulet: A secure architecture for mHealthapplicationsforlow-powerwearabledevices”–moreexplicitlydescribesthe architectureandarchitecturalsecurityfeaturesofthedeviceandexpandsonthegoal of customisability and the ability to install third party applications [?]. This paper introducesthetwo-tieredarchitectureoftheAmuletanddescribestheadvantagesof havingapplicationsasfinite-statemachines,andthemechanismofapplicationisolation bylimitingthefeaturesofCandstaticanalysisatcompiletime[?]. Neitherofthese papershasaddressedtheBluetoothcommunicationsoftheAmuletinanydepth. 6 Ina2016papertitled“Beetle: FlexibleCommunicationforBluetoothLowEnergy,” Levyet. al. describe“Beetle,”a“hardwareinterfacethatvirtualizesperipheralsatthe applicationlayer”andallowsmultipleapplicationsonthecentraltoreceivedatafrom thesameperipheral,implementsaccesscontrolforoperationsandvaluesontheperiph- eral,andenablesperipheraltoperipheralcommunicationthroughagateway[?]. The paperprovidesusefulbackgroundinformationonBLEandthewayexistingoperating systemspresentBLEtoapplications. Theyauthorspresentexampleimplementationson AndroidandLinuxthatinserta“Beetle”layerinbetweentheBLEcontrolsandexisting applicationstointercepttheBLEpacketsandexposeonlythedesiredfunctionalityto theapplicationbypresentingitwithavirtualperipheral. Thecurrentimplementation of AmuletOS and the radio, which hide the internals of the BLE connection to the application and allow two applications to receive data from the same sensor, is not entirelyunlikethisapproach. AlthoughtheAmuletOSisanembeddedoperatingsystem andtheBeetlelayerisdesignedforafull-fledgedOS,theideasaboutaccesscontroland sharingsensorspresentedinthispaperarehighlyrelevanttotheproblemofintegrating BLEsensorswithAmuletOSandsuggestinterestingdirectionsforfuturedevelopment. ToexploreBLEtransmissionsandstructureweusedamodelUA-651BLEBlood PressureMonitormanufacturedbyA&DMedical[?]. A&Dengineeringprovidedan exampleAndroidapplicationforconnectingtotheirBloodPressureMonitorintheir Githubrepository[?]thatwereferencedforhintsonhowtoconnecttothedevice,and providedanexampleoftheAndroidcallbackstructureforhandlingBLEconnections. TheLinuxutitilityGatttool,whichisincludedinthebluezpackage,wasalsoinvaluable indiscoveringdevicecharacteristicsandhowtheBLEprotocolworked. Thesimpleset ofcommandsthatitexposestotheuseratthecommandlineservedastheinspiration forthecollectionofBLEcommandsthatareelevatedtotheAmuletOSintheproposed implementation. 4 Current Implementation ThecurrentversionofAmuletiscapableofBLEcommunicationbuttheimplementa- tionislimitedandinflexible: AmuletBLEonlyworkswithheart-ratemonitorsthat implementtheBLE-definedHeartRateProfileandtheradiocodeisinextricablybound tothesensortypeanddataformattingofthesensor. Continuingtoaddsensorsinthesamewaywouldhaverequiredre-writingcodefor theradioeverytimeanewdataformatwasintroducedandmakingchangesthroughout theAmuletOScorecode,requiringadevelopertofullyunderstandbothpartsofthe systemandreprogrambothmicrocontrollerseverytimetheywantedtoaddanewsensor. Furthermore,thecurrentcasedesignoftheAmuletintentionallymakesitdifficultto accesstheprogrammingportoftheM0. InthecurrentimplementationofBLEandtheradio(Figure??),whenanapplication wantstogetdatafromaheart-ratemonitor,itusesanAPIcallto“subscribe”tothe sensor. Thecorestoresthatsubscriptioninaqueueandturnsontheradioifitisnot alreadyon.Ontheoldhardwarethecorethenbundledthesubscriptioninformationinan IPCheaderandsentittotheradio(M0),whichkeptamirroredcopyofthesubscriptions. ThecurrentversiondoesnotmirrorsubscriptionsontheM0andturningontheradio 7 immediately starts a scan for compatible sensors. The scan results are filtered on theM0untilaperipheralthatimplementstheBluetoothGATTHeartRateProfileis discovered,atwhichpointtheradioattemptsaconnection. Theradioautomatically enablesnotificationsfromtheGATTserverontheperipheralbywritingtoaspecific characteristic. Whenanotificationarrives,theradioextractsthedataandsendsittothe coreontheSPI!bus. Withtheoldhardware,theradiowrappeditintheIPCheader,but thefullIPCprotocolhasnotbeenreimplemented. Thecorereceivesthedata,thensteps throughthesubscriptionqueueandsenda“dataready”eventtoanyapplicationthat hadregisteredasubscriptiontotheHeartRateMonitor. Theapplicationthencallsa getHeartrateDatafunctiontogetthesensordata. Intheoriginalmodel(withsubscriptionsmirroredontheM0)whenanapplication unsubscribed from a sensor, the core simply marked its copy of the subscription as disabled in order to avoid sending an expensive IPC message. Subscriptions were actuallydeletedwhenthey“expired,”afunctionalitythathassincebeendeprecated. Thecurrentimplementationdoesnotactuallydeletethesubscriptionwhenanappliction unsubscribes,eventhoughitissafetodoso. WiththecurrentapplicationstheAmulet is not processing enough subscribe and unsubscribe events to be in any danger of overflowingthesubscriptionqueue,sothismethodisfunctionalifnotscaleable. Inthecurrentimplementation,theonlycontrolthatthecorehasovertheradiois theabilitytoturnitonoroff,andturningontheradioimmediatelyinitiatesascanfor heart-ratemonitors. TheonlydatathatflowsbackfromtheradiototheAmuletOSis theheart-ratereadings,sentovertheSPIbuswithoutheadersorothermetadata. The radioonlyconnectstoheartratemonitorsthatimplementtheGATTHeartRateService. 5 Proposed Model Our proposed redesign of BLE integration with the AmuletOS is not a radical re- architectingoftheflowofcontrolanddatathroughthesystem,butacarefulrestructruc- turingoftheexistingBLEfunctionalityforbetterextensibility. Themostsignificant changeisthatthesensor-type-specificcodeisremovedfromtheM0andAmuletOSis givenfinercontrolovertheBLEradioandmoreerrorsignalsareaddedforbettererror handlinginapplications. TheproposedflowofdataandcommandsareshowninFig- ure??. TheprimarydifferencesfromFigure??arethechangesincommandsandinfor- mationsentfromthecoretotheM0wheninitiatingaconnection,thegenericradiocode, thelook-upofahandlertodealwithreceiveddata,andthegenericAmuletGetData function. Thegenericradiomeansthatfuturedevelopersdonotneedtodoanything withtheradiocodeandtheformattingofthedataandsensor-specificconnectionvalues canbedefinedintheAmuletOS.TheproposedmodelalsoenablestheAmuletOSto keeptrackofsubscriptionstodifferentinstancesofthesametypeofBLEsensorand allowsanapplicationtoownsubscriptionstomultipleBLEsensors. There are two main assumptions made in the conception and description of this model:1)Inter-ProcessorCommunicationwillbere-instatedwithaheaderthatincludes certainfieldsandflags,and2)theradiocodecanbemodifiedtoperformthedesired operationsinagenericmannerthatworkswithmostsensors. Thefirstisanimplemen- tationanddebuggingtask,butthesecondislesscertain,asthemanufacturersofBLE 8 App subscribes to BLE Application Layer App gets event, retrieves HR sensor data AmuletSubscribe() DATA_EVT AmuletGetHR() Core adds subscription to Core receives the data, puts subscription queue, turns on AmuletOS it in a known location the radio if needed turn on radio Extracted data, no headers M0 M0 knows the notification immediately scans for and tries format, and unpacks the data, to connect to a BLE sensor (a M0 (radio) wraps with IPC header and HRM) sends 5. Write success 4. Enable Notifications BLE sensor (Heart-rate) 3. Connect success Notification 2. Connect Notification 1. Advertising data Figure4: Thecurrentdataflow,andinteractionwiththeBLEheartratemonitor. Note thatthecorecanonlyturnontheradio,anddataissentoverIPCwithoutheaders. The functionforretrievingdataisheart-ratespecific App subscribes to BLE App gets event, retrieves HR sensor Application Layer data AmuletSubscribe() DATA_EVT AmuletGetData() Core adds subscription to Core receives data, calls a subscription queue, turns on the AmuletOS sensor specific function to radio if needed, initiates a scan extract it 2. scan 4. Connect 1. turn on by address 5. Write radio 3. adv value to Notifications info handle wrapped in IPC M0 performs generic commands M0 receives data and passes it using parameters and data sent by M0 (radio) up the core 5. Write success 4. Enable Notifications BLE 3. Connect success Notification ENABLED 2. Connect SENSOR Notification 1. Advertising data Figure5: ThenewinteractionwithaBLEsensor,withthecoreplayingamoreactive role.NotetheincreasedcommunicationbetweentheAmuletOSandtheradio,especially whenestablishingaconnection. 9 sensorsallseemtointerpretthestandarddifferentlyandtheinteroperabilityofacentral andaperipheralisnotguaranteedoutofthebox. 5.1 Attheapplicationlevel ThewayanapplicationgetsdatafromaBLE-enabledsensordoesnotchangedramati- callyintheproposeddesign. Anapplicationstillsubscribes,butspecifiesthetypeof BLEsensorthatitisrequestingdatafromasanargument. Toaccommodatemultiple sensors,iftheapplicationsubscribestomorethanoneBLEsensoritmustalsospecify auniqueintegeridentifierforeachofthemintherangeof0toMAX_SENSORS,which isaconstantvaluethatmustbelessthan255. Ifithasonlyonesubscriptiontheidenti- fiermustdefault0. Thisidentifierispassedtothesubscriptionfunctionprovidedby theAmuletOSandisstoredbythecore,givingtheapplicationandthecoreashared referenceforthatindividualsensor. ApplicationsshouldassumethatalloftheirrequeststotheAmuletOSsucceedunless theyexplicitlyreceiveafailureevent.3 Thus,aftersubscribing,anapplicationshould proceeddirectlytostateofwaitingfordata. Theproposedchangesdefineseveralnew eventstoinformtheapplicationofBLEscanorconnectionfailures,asmanyconnection orscanningproblems–specifically,thedesiredsensornotbeingpresent,inrange,or advertising–canbefixedbysimpleuserintervention(turningthedeviceon). Toretrievedata,theapplicationcallsagenericfunction,passinginsufficientinfor- mationforthecoretoidentifythesubscriptionandanarrayforthecoretofillwithdata. Whenapplicationsaretranslatedfromagraphicalfinite-statemachineinQMintoC, arraysarereplacedbystructsthatcontainapointertovaluesandthelengthofthearray topreventout-of-boundserrorsandtogetaroundthe“nopointers”restriction[?]. The corewillonlyreturnasmuchdataaswillfitinthearray. Boththeapplicationandthe coreshouldknowthelengthandtypeoftheexpecteddatafromagivensensor,butthe coredetermineshowmuchdataisactuallyreturnedandwillnotoverflowthegiven array,preventingbufferoverflowerrors. 5.2 Atthecorelevel The proposed changes expose the major actions of establishing a BLE connection andsendingandreceivingdatatothecore, allowingtheAmuletOStoasktheradio to perform the essential functions needed to connect to a BLE sensor and request notifictionsorindicationsfromit. Toenactthechanges,thecorestoresmoreidentifiers andassociationsforeachconnectionthanitdoesinthecurrentimplementation,aseach applicationcanhavemultiplesensors,andthose“multiplesensors”couldbeseparate subscriptionstodifferentinstancesofthesametypeofsensor. 5.2.1 Subscriptionsandconnectingtoasensor Thelogicofsensorsubscriptioninthecurrentmodelassumesthatanyapplicationthat subscribestoaheart-ratemonitorwillreceivethereadingsfromthesingleheart-rate 3IntheAmuletOS,theseeventsaredefinedinanenum.Allofthemareappendedwith SIG 10
Description: