language support for programming interactions among...

123
Faculteit Wetenschappen en Bio-ingenieurswetenschappen Vakgroep Computerwetenschappen Software Languages Lab Language Support for Programming Interactions among Wireless Sensor Network Nodes Proefschrift ingediend met het oog op het behalen van de graad van Master in de Ingenieurswetenschappen: Computerwetenschappen Wouter Amerijckx Promotor: Prof. Dr. Wolfgang De Meuter Begeleiders: Dr. Coen De Roover Christophe Scholliers JUNI 2011

Upload: others

Post on 22-Sep-2020

3 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

Faculteit Wetenschappen en Bio-ingenieurswetenschappenVakgroep ComputerwetenschappenSoftware Languages Lab

Language Support for Programming Interactionsamong Wireless Sensor Network Nodes

Proefschrift ingediend met het oog op het behalenvan de graad van Master in de Ingenieurswetenschappen: Computerwetenschappen

Wouter Amerijckx

Promotor: Prof. Dr. Wolfgang De MeuterBegeleiders: Dr. Coen De Roover

Christophe Scholliers

JUNI 2011

Page 2: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

Faculty of Science and Bio-Engineering SciencesDepartment of Computer ScienceSoftware Languages Lab

Language Support for Programming Interactionsamong Wireless Sensor Network Nodes

Graduation thesis submitted in partial fulfillment of therequirements for the degree of Master of Engineering: Computer Science

Wouter Amerijckx

Promotor: Prof. Dr. Wolfgang De MeuterAdvisors: Dr. Coen De Roover

Christophe Scholliers

JUNE 2011

Page 3: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

Acknowledgements

This dissertation would not have been what it is today without the outstandingsupport of various people.

First of all, I’d like to thank Professor Wolfgang De Meuter for promotingthis thesis and giving me the opportunity to conduct my apprenticeship at theSoftware Languages Lab.

In addition, I’d like to thank my advisors dr. Coen De Roover and ChristopheScholliers for all their support and time spent while keeping me on track. Theinput they’ve given during hours of discussions and after proofreading this thesiswas invaluable for the final result. Even when they were overwhelmed by theirown work, they found the time to give me advice, motivate me and help me outwhen I got stuck.

Next to my advisors, I would also like to thank all other members of theSoftware Languages Lab for their interest and input during the various pre-sentations about my work. Additionally, I’d like to thank the members of theStadium project for inviting me to their meetings and workshops. They intro-duced me to the LooCI middleware, which lies at the basis of the work presentedin this thesis.

Last but not least, I’d like to thank my mother and friends for support-ing me during my education. In particular, for the many talks, laughs andencouragements at the times when I needed them most.

i

Page 4: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

Samenvatting

De vooruitgang in hardware technologie heeft ertoe geleid dat computers krachtiger,kleiner, en goedkoper worden. Samen met de technologische vooruitgang in draadlozenetwerken heeft ze aanleiding gegeven tot een nieuwe vorm van gedistribueerde systemen,de zogenaamde draadloze sensor netwerken (DSN). DSN bestaan uit minuscule toestellenop batterijen die draadloos communiceren. Deze toestellen zijn goedkoop, uitgerust metsensoren en actuatoren, en breed inzetbaar. Tot op heden werden DSN reeds gebruiktvoor het inspecteren van zebra’s en het besturen van aircoconditioning systemen. Eennieuwe trend bestaat erin DSN te gebruiken voor actieve toepassingen waarbij het DSNmoet reageren op de gemeten sensorwaarden. Ondanks deze trend bieden de huidigeprogrammeermodellen voor DSN niet de nodige abstracties om het ontwikkelen van dezetoepassingen te vergemakkelijken.

Het ontwikkelen van actieve toepassingen houdt normaliter in dat de individuele DSNtoestellen, typisch knopen genoemd, een voor een geprogrammeerd dienen te worden.Voor elke knoop moet de ontwikkelaar bepalen hoe die interageert met andere knopen inhet netwerk. In deze interacties worden berichten uitgewisseld en verwerkt om de nodigeacties te starten. Deze berichten bevatten meestal sensorwaarden en kunnen bijvoorbeeldverwerkt worden om een actuator aan te sturen (bvb., een radiator). De huidige pro-grammeermodellen hebben het versturen van deze berichten wel vergemakkelijkt, maarde complexiteit van het verwerken van binnenkomende berichten werd door de meestengenegeerd. Dit deel van de interactie dient typisch geımplementeerd te worden in eenevent handler die aangeroepen wordt bij het ontvangen van elk nieuw bericht. Het isechter reeds aangetoond dat het gebruik van event handlers in strijd is met verscheidenesoftware engineering principes zoals samenstelbaarheid en schaalbaarheid. Een eventhandler kan niet zomaar samengevoegd worden met een andere om bijkomende berichtente verwerken. Bovendien wordt een event handler erg complex indien die moet reagerenop een sequentie van verscheidene berichten die op verschillende ogenblikken ontvangenworden. Dit houdt in dat bijgehouden moet worden welke berichten al dan niet reedsontvangen werden. Ad hoc oplossingen voor het verwerken van binnenkomende berichtenzijn foutgevoelig en dienen daarenboven gedupliceerd te worden in de event handlers vanverschillende knopen.

Deze verhandeling introduceert ondersteuning voor het programmeren van interactiestussen knopen om de hierboven vermelde problemen het hoofd te bieden. We intro-duceren een domein-specifieke programmeertaal die gebruikt dient te worden bovenopevent-gebaseerde middleware. Deze taal laat toe om de interacties van een knoop metanderen uit te drukken via declaratieve regels en vermijdt op deze manier de complex-iteit van event handlers. Daarbovenop introduceren we een macroprogrammeertaal dietoelaat om toepassingen voor DSN in hun geheel te programmeren. Deze taal bevorderthet hergebruik van programmacode binnen en tussen verscheidene toepassingen. Onzebenadering minimaliseert de toevallige complexiteit eigen aan het ontwikkelen van DSNtoepassingen met event-gebaseerde middleware en stelt de ontwikkelaar in staat zich tefocussen op de essentiele complexiteit van de toepassing.

ii

Page 5: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

Abstract

Advances in hardware technology have lead to computing devices becomingsmaller, cheaper and more powerful. Together with the technological advancesin wireless networks, they gave rise to a new form of distributed systems, calledwireless sensor networks (WSNs). WSNs consist of tiny, sensor- and actuator-equipped, battery-powered devices that communicate wirelessly. Due to the lowcost of these devices, WSNs can be widely deployed. For instance, they havealready been deployed for monitoring zebras and controlling air-conditioningsystems. An emerging breed of applications, called sense-and-react applications,tasks a WSN not only with sensing, but also with reacting to sensor readings.However, current programming models for WSNs do not offer appropriate ab-stractions to deal with the complexity of implementing these applications.

Developing sense-and-react applications typically involves programming in-dividual WSN devices, often called nodes, one by one. For each node, the de-veloper has to specify how it interacts with the other nodes in the network. Inthese interactions, messages are exchanged and processed to trigger the appro-priate actions. These messages typically carry sensor data and can, for instance,be reacted to by controlling an actuator (e.g., a heater). While existing pro-gramming models have facilitated transmitting messages, most of them haveignored the difficulties of processing incoming messages. For this part of theinteraction, they force the developer to implement the required logic in an eventhandler that will be invoked whenever a new message is received. However,the use of event handlers has already been shown to violate a range of soft-ware engineering principles including composability, scalability and separationof concerns. For instance, an event handler cannot simply be composed withanother one to have it process additional messages. In addition, reacting to asequence of time-dispersed messages complicates an event handler as it implieskeeping track of what messages have already been received. Ad-hoc solutionsfor processing incoming messages are error-prone and bound to be duplicatedover the event handlers of multiple nodes.

This dissertation introduces language support for programming interactionsamong WSN nodes to address the aforementioned problems. Concretely, weintroduce a new domain-specific programming language to be used on top ofevent-based WSN middleware. This language enables expressing the interac-tions of a node with others through declarative rules and thereby avoids thecomplexity of event handlers. In addition, we introduce a macroprogramminglanguage for programming WSN applications as a whole. This language fos-ters code reuse within and among WSN applications. Our approach minimizesthe accidental complexity inherent to programming WSN applications usingevent-based middleware and enables the developer to focus on the application’sessential complexity instead.

iii

Page 6: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

Contents

1 Introduction 11.1 Problem Statement . . . . . . . . . . . . . . . . . . . . . . . . . . 21.2 Proposed Solution . . . . . . . . . . . . . . . . . . . . . . . . . . 31.3 Document Overview . . . . . . . . . . . . . . . . . . . . . . . . . 4

2 State of the Art 52.1 Traditional Wireless Sensor Networks . . . . . . . . . . . . . . . 5

2.1.1 Raw Data Extraction . . . . . . . . . . . . . . . . . . . . 62.1.2 Programming a Query . . . . . . . . . . . . . . . . . . . . 72.1.3 Interpreted Data Extraction . . . . . . . . . . . . . . . . . 82.1.4 Evaluation . . . . . . . . . . . . . . . . . . . . . . . . . . 9

2.2 Getting More Control over Individual Nodes . . . . . . . . . . . . 92.2.1 Node-centric Programming . . . . . . . . . . . . . . . . . 102.2.2 Support for Interactions among Nodes . . . . . . . . . . . 132.2.3 Network-centric Programming . . . . . . . . . . . . . . . . 22

2.3 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 272.4 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29

3 Node-centric Programming with CrimeSPOT 313.1 Running Example . . . . . . . . . . . . . . . . . . . . . . . . . . 32

3.1.1 Programming Support Requirements . . . . . . . . . . . . 343.2 CrimeSPOT in a Nutshell . . . . . . . . . . . . . . . . . . . . . . 353.3 Architectural Overview . . . . . . . . . . . . . . . . . . . . . . . 36

3.3.1 CrimeSPOT Runtime . . . . . . . . . . . . . . . . . . . . 363.3.2 Interacting with the CrimeSPOT Runtime . . . . . . . . . 383.3.3 Network View on Component Interactions . . . . . . . . . 38

3.4 Inference Engine . . . . . . . . . . . . . . . . . . . . . . . . . . . 393.5 Grammar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 403.6 Facts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40

3.6.1 Controlling a Fact’s Scope . . . . . . . . . . . . . . . . . . 413.6.2 Mapping Events to Facts . . . . . . . . . . . . . . . . . . 41

3.7 Interaction Rules . . . . . . . . . . . . . . . . . . . . . . . . . . . 433.7.1 Conditions . . . . . . . . . . . . . . . . . . . . . . . . . . 443.7.2 Reactions . . . . . . . . . . . . . . . . . . . . . . . . . . . 513.7.3 Precedence . . . . . . . . . . . . . . . . . . . . . . . . . . 53

3.8 Fine-tuning the Reification Engine . . . . . . . . . . . . . . . . . 533.8.1 Specifying Subsumption Strategies . . . . . . . . . . . . . 543.8.2 Dropping Incoming Facts . . . . . . . . . . . . . . . . . . 55

3.9 Revisiting the Running Example . . . . . . . . . . . . . . . . . . 563.10 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59

iv

Page 7: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

CONTENTS v

4 Network-centric Programming with Macro-CrimeSPOT 624.1 Grammar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 634.2 Grouping the Components of a WSN Application . . . . . . . . . 63

4.2.1 Quantifying over Multiple Components . . . . . . . . . . 644.2.2 Using Meta-Variables in CrimeSPOT Expressions . . . . . 654.2.3 Abstracting CrimeSPOT Expressions . . . . . . . . . . . 664.2.4 Organizing Abstract CrimeSPOT Expressions into Libraries 67

4.3 Compiling Macro-Code . . . . . . . . . . . . . . . . . . . . . . . . 674.4 Revisiting the Running Example . . . . . . . . . . . . . . . . . . 684.5 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70

5 Validation 715.1 Illustrative Examples . . . . . . . . . . . . . . . . . . . . . . . . . 71

5.1.1 Fire Detection . . . . . . . . . . . . . . . . . . . . . . . . 715.1.2 Monitoring Temperatures . . . . . . . . . . . . . . . . . . 745.1.3 River Monitoring . . . . . . . . . . . . . . . . . . . . . . . 755.1.4 Range Coverage . . . . . . . . . . . . . . . . . . . . . . . 77

5.2 Expressiveness . . . . . . . . . . . . . . . . . . . . . . . . . . . . 805.3 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81

6 Conclusion 826.1 Contributions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 836.2 Future Work . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83

A CrimeSPOT Prototype Implementation 86A.1 Inference Layer . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86

A.1.1 The CRIME Inference Engine . . . . . . . . . . . . . . . . 86A.1.2 Introducing Time-related Functionality . . . . . . . . . . 89A.1.3 Introducing a Compute Node for the RETE Network . . . 91

A.2 Reification Layer . . . . . . . . . . . . . . . . . . . . . . . . . . . 93A.2.1 Processing Incoming Events . . . . . . . . . . . . . . . . . 93A.2.2 Implementing the Meta-Facts . . . . . . . . . . . . . . . . 94A.2.3 Building a RETE Network for Drop Meta-Facts . . . . . . 94A.2.4 Building a RETE Network for Subsumption Meta-Facts . 95

A.3 Infrastructure Layer . . . . . . . . . . . . . . . . . . . . . . . . . 97A.3.1 LooCI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98A.3.2 Instantiating the Middleware Bridge for the LooCI Mid-

dleware . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98A.4 Macro-CrimeSPOT’s Compilation Target . . . . . . . . . . . . . 100A.5 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101

B Evaluating the CrimeSPOT Prototype 103B.1 Memory Footprint . . . . . . . . . . . . . . . . . . . . . . . . . . 103B.2 Network Overhead . . . . . . . . . . . . . . . . . . . . . . . . . . 105B.3 Performance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106B.4 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107

Page 8: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

List of Figures

2.1 ATaG: Cluster-based data processing - task graph . . . . . . . . 262.2 An overview of the covered State of the Art . . . . . . . . . . . . 30

3.1 Overview of a Wireless Sensor Network application that controlsthe heating and logs the comfort levels of festival tents . . . . . . 33

3.2 Physical view on a Wireless Sensor Network node running event-based component middleware . . . . . . . . . . . . . . . . . . . . 36

3.3 Architectural overview of the CrimeSPOT runtime . . . . . . . . 373.4 Fact publication and Event reification . . . . . . . . . . . . . . . 373.5 Logical view on the possible interactions with the CrimeSPOT

runtime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 383.6 Two CrimeSPOT components exchanging CrimeSPOT events . . 383.7 Event-based components exchanging temp events . . . . . . . . . 393.9 Illustrating the temperature event mapping . . . . . . . . . . . . 423.10 Syntax for an interaction rule with a fact in its head . . . . . . . 433.11 Faulty matching illustrated . . . . . . . . . . . . . . . . . . . . . 463.12 Illustrating Match Expiration . . . . . . . . . . . . . . . . . . . . 473.13 Illustrating Match Verification . . . . . . . . . . . . . . . . . . . 483.14 Scheduling method invocations: evalEvery vs. renewEvery . . . . 503.15 Event reification pipeline . . . . . . . . . . . . . . . . . . . . . . . 533.16 Subsumption impact for adjustHeating facts . . . . . . . . . . . . 543.8 CrimeSPOT Grammar . . . . . . . . . . . . . . . . . . . . . . . . 61

4.1 Macro-CrimeSPOT Grammar . . . . . . . . . . . . . . . . . . . . 634.2 Macro-CrimeSPOT Precompiler . . . . . . . . . . . . . . . . . . . 67

5.1 A Wireless Sensor Network application for detecting and fightingfire . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72

5.2 A Wireless Sensor Network application for monitoring temperatures 745.3 A Wireless Sensor Network application for monitoring a river . . 765.4 A Wireless Sensor Network application with range coverage de-

tection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77

A.1 A RETE Network with a single rule for asserting temperatureIn-Tent facts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88

A.2 A RETE Network with a single meta-fact for dropping tempera-ture facts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95

A.3 A RETE Network with a single meta-fact that specifies the sub-sumption strategy for temperature facts . . . . . . . . . . . . . . 96

A.4 Runtime view on a WSN node running LooCI . . . . . . . . . . . 98

vi

Page 9: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

LIST OF FIGURES vii

B.1 Fact Base Size vs RAM Usage . . . . . . . . . . . . . . . . . . . . 104

Page 10: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

List of Tables

3.1 Functional requirements for a WSN application that controls theheating and logs the comfort levels of festival tents . . . . . . . . 34

3.2 Programming Support Requirements concerning State Management 353.3 Programming Support Requirements concerning Component In-

teractions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35

5.1 Example Applications: General Statistics . . . . . . . . . . . . . 805.2 Example Applications: Total Component Code . . . . . . . . . . 80

B.1 Memory Footprint (ROM) . . . . . . . . . . . . . . . . . . . . . . 103B.2 Memory Footprint (RAM) . . . . . . . . . . . . . . . . . . . . . . 104B.3 Memory Footprint (RAM) vs. Amount of rules . . . . . . . . . . 105B.4 Average time required before a fact will be asserted in the Fact

Base, after receiving the corresponding event . . . . . . . . . . . 106

viii

Page 11: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

Listings

1.1 A simple event handler . . . . . . . . . . . . . . . . . . . . . . . . 32.1 TinyDB: example query . . . . . . . . . . . . . . . . . . . . . . . 62.2 TinyDB: an actuator query . . . . . . . . . . . . . . . . . . . . . 62.3 Regiment: example query . . . . . . . . . . . . . . . . . . . . . . 72.4 DSWare: An Event Definition . . . . . . . . . . . . . . . . . . . . 82.5 nesC: Communication Interfaces . . . . . . . . . . . . . . . . . . 102.6 nesC: Communication Example . . . . . . . . . . . . . . . . . . . 112.7 SunSPOT: Communication Example . . . . . . . . . . . . . . . . 122.8 Logical Neighborhoods: neighborhood template and instantiation 142.9 Logical Neighborhoods: node template and instantiation . . . . . 142.10 LooCI: A Temperature Filter Component . . . . . . . . . . . . . 152.11 LooCI: Interacting with the gateway . . . . . . . . . . . . . . . . 162.12 Abstract Regions: Implementing an object-tracking application . 172.13 TeenyLIME: code for a sensor . . . . . . . . . . . . . . . . . . . . 192.14 TeenyLIME: code for an actuator . . . . . . . . . . . . . . . . . . 192.15 FACTS: a coverage algorithm . . . . . . . . . . . . . . . . . . . . 202.16 Kairos: Constructing a shortest-path routing tree . . . . . . . . . 232.17 ActorNet: An agent/actor looking for the highest temperature in

the WSN . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 242.18 ATaG: Cluster-based data processing - code for the Sampler task 273.1 A temperatureReading fact . . . . . . . . . . . . . . . . . . . . . 403.2 Publishing a temperatureReading fact . . . . . . . . . . . . . . . 413.3 Mapping a temperature event to a temperatureReading fact . . . 413.4 An interaction rule for copying temperatureReading facts to tem-

perature facts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 433.5 Relating humidity readings with online facts . . . . . . . . . . . . 453.6 A condition for matching only recent temperature readings . . . 473.7 A rule with a condition that expects a match at least every minute 483.8 Publishing humidity readings using the is operator . . . . . . . . 493.9 Keeping a history of humidity readings . . . . . . . . . . . . . . . 493.10 Collecting smoke facts using findall . . . . . . . . . . . . . . . . . 513.11 Adding an interaction rule for invoking application logic to the

CrimeSPOT runtime . . . . . . . . . . . . . . . . . . . . . . . . . 523.12 Specifying a subsumption strategy for adjustHeating facts . . . . 543.13 Specifying a subsumption strategy for online facts . . . . . . . . 553.14 Specifying a subsumption strategy for humidityReading facts . . 553.15 Dropping irrelevant facts . . . . . . . . . . . . . . . . . . . . . . . 563.16 Using constants in meta-facts . . . . . . . . . . . . . . . . . . . . 563.17 Publishing online facts from the TemperatureSensor component

using the is operator . . . . . . . . . . . . . . . . . . . . . . . . . 573.18 Reacting to adjustHeating facts . . . . . . . . . . . . . . . . . . . 57

ix

Page 12: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

LISTINGS x

4.1 Macro-CrimeSPOT syntax . . . . . . . . . . . . . . . . . . . . . . 644.2 Implementing the HeatingController in Macro-CrimeSPOT . . . 644.3 Illustrating the universal quantifier . . . . . . . . . . . . . . . . . 654.4 Macro for the temperature event-fact mapping . . . . . . . . . . 664.5 Macro for publishing a component’s presence . . . . . . . . . . . 664.6 Running Example - Universally quantified code block . . . . . . . 684.7 Running Example - Event-Fact Mappings Library . . . . . . . . . 684.8 Running Example - Sensor- and HeatingController components . 694.9 Running Example - ComfortLevelMonitor component . . . . . . 69A.1 RETE Algorithm: a rule for asserting temperatureInTent facts . 87A.2 A rule for motivating fact IDs . . . . . . . . . . . . . . . . . . . . 90A.3 Macro-CrimeSPOT’s compilation target: a CrimeSPOT Compo-

nent in Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101B.1 Artificial rule for the RAM usage experiment . . . . . . . . . . . 105

Page 13: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

1Introduction

Advances in hardware technology have lead to computing devices becomingsmaller, cheaper and more powerful. Together with the technological advancesin wireless networks, they gave rise to a new form of distributed systems, calledwireless sensor networks (WSNs). WSNs consist of tiny, sensor- and actuator-equipped, programmable devices that communicate wirelessly. These devices,often called nodes, have highly constrained computing- and communication re-sources and are typically battery-powered. Even though hardware advancesplay an important role in the development of WSN technology, the most impor-tant factor is the programming model supporting application development [1].Unlike traditional distributed systems, WSNs have a dynamic nature: at anytime, nodes can fail or get disconnected from the network (i.e., disconnectionsare the norm rather than an exception). Due to this dynamic nature, traditionalprogramming models could not cope with the requirements of WSNs and a newbody of programming models was introduced by the academic community.

Two major approaches can be taken when programming WSN applications.The first approach consists of programming every individual node by specifyingits interactions with the other nodes. These interactions typically involve send-ing data around, storing data, or reacting to requests either by actuating, or bysensing and answering the sensed values. This approach is commonly referredto as node-centric programming [2]. While node-centric programming modelsgive the developer fine-grained control over important requirements such as anode’s power- and bandwidth consumption, they also require the developer todeal with low-level details.

The second approach allows the programmer to take distance from low-level details and consists of programming all nodes in the WSN as a whole.This approach is commonly referred to as network-centric programming [2].Network-centric programming models either abstract the WSN as a whole orallow the WSN to be programmed from a macroscopic viewpoint. For instance,a common abstraction represents a WSN as a virtual database of sensors thatcan be queried using an SQL-like language [3], while a common way to allow

1

Page 14: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

CHAPTER 1. INTRODUCTION 2

macroscopic programming consists of supporting mobile code [4]. Of course,using higher level programming models comes at the price of lesser control overthe individual nodes.

To date, WSNs have been used mostly for sense-only applications. Exam-ples are applications for monitoring habitats [5], zebras [6] and glaciers [7], andapplications for detecting intrusions [8], forest fires [9] and flooding rivers [10].Only recently, WSN applications became more active. An example is an ap-plication for controlling heating- and air conditioning systems [11]. Especiallythe development of active applications, typically referred to as sense-and-reactapplications, remains difficult as this requires a high degree of control over theindividual nodes (e.g., to steer actuators).

The following sections show the problem that appears when programmingsense-and-react WSN applications and how our work tackles this problem. Toconclude the introduction, we present a high-level overview of this dissertation.

1.1 Problem Statement

For developing sense-and-react applications, a developer typically relies on anode-centric programming model to program node-level code. This node-levelcode has to process sensor-data obtained through interactions with other nodesand based on this processing, reactions have to be triggered (e.g., steering anactuator). However, contemporary node-centric programming models do notoffer adequate support for programming node interactions.

Node-centric programming models require the developer to program at a lowlevel of abstraction. For instance, programming an interaction with anothernode typically involves encapsulating data in a packet and transmitting thispacket in the node’s one-hop neighborhood. Processing data upon reception,on the other hand, often involves the use of an event handler in which receivedpackets have to be parsed and their data has to be extracted. To raise the levelof abstraction, there exist several solutions that complement node-centric pro-gramming models with additional support for programming interactions. How-ever, while these solutions facilitate transmitting data, most of them do not helpin processing data upon reception. They still rely on the use of event handlersfor this part of the interaction. Not only do event handlers complicate pro-gramming interactions among sensor nodes, they also force the programmer toadopt a programming style that violates several software engineering principles,including composability, scalability and separation of concerns [12].

To illustrate how event handlers complicate programming interactions amongsensor nodes, we can consider the programming model introduced by event-based WSN middleware. Such midleware brings the Publish-Subscribe interac-tion pattern [13] to WSNs and allows sensor nodes to communicate by exchang-ing events via a decentralized event bus. Nodes can publish events of certaintypes, which will then be routed to other nodes that subscribed to these events’types. Published events are usually only routed to subscribers that are online atthe time of publication. While Publish-Subscribe decouples the communicationbetween sensor nodes (i.e., the communicating parties don’t have to be fixedat compile-time), it still requires the processing of received events to be imple-mented in an event handler. Therein, a developer typically dispatches over thepossible event-types that could be received and selects the appropriate reaction.

Page 15: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

CHAPTER 1. INTRODUCTION 3

An example is given in Listing 1.1.

1 public void receive(Event ev) {

2 if(ev.getType () == EventTypes.GET_TEMP)

3 publish(new Event(EventTypes.TEMP , getTemperature ()))

4 }

Listing 1.1: A simple event handler

The example shows a simple event handler that reacts to one particular event-type: when a temperature request is received, the current temperature is mea-sured and published. Typically, however, the event handler becomes larger andmore complex as more event-types have to be reacted to. Extending an eventhandler by composing it with another one typically doesn’t work. Furthermore,it’s not hard to imagine cases in which it might be desired to react to severalrelated but time-dispersed events. One example is a sensor node steering heatersthroughout a house. To steer a heater in a particular room, it is required tocombine sensor-reading events published by temperature- and humidity sensorsin the same room. Implementing this behavior further complicates the eventhandler. It requires additional bookkeeping to keep track of which events havealready been received, additional matching of related events (i.e., events orig-inating from sensors in the same room), and additional state management tomake sure no stale events are used for steering the heaters. While in this exam-ple, events are only related by the room they originate from, more sophisticatedrelations require even more sophisticated event handler implementations (e.g.,specifying a finite state machine that transitions between states upon the re-ception of events).

Without adequate support for processing received data, developers have todeal with the requirements mentioned in the above example by designing ad-hocsolutions that are bound to be duplicated over the event handlers of multiplenodes. Worse, a sensor node’s application logic would be polluted with the codefor dealing with these requirements. As a consequence, the application logicbecomes difficult to understand, to extend, and to reuse. While this problemplagues other event-driven architectures as well, existing solutions like complexevent processing do not readily translate to the setting of wireless sensor net-works as they are not designed for use in distributed systems.

1.2 Proposed Solution

To tackle the aforementioned problem, we propose to introduce additional lan-guage support for programming interactions among WSN nodes. Concretely,we propose both a node-centric- and a network-centric programming language.

The node-centric programming language constitutes a building block, to beused on top of existing event-based WSN middleware. It allows the use ofdeclarative rules to specify the interactions between sensor nodes. This declar-ative model addresses the various problems that using an event handler forprogramming node interactions brings along. The language reduces the com-plexity and improves the modifiability and scalability of the application logicfor WSN nodes. Its runtime employs the well-known Rete algorithm for theevaluation of interaction rules.

The network-centric programming language is a macroprogramming lan-guage that allows each node’s behavior to be specified in a centralized fashion.

Page 16: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

CHAPTER 1. INTRODUCTION 4

This language supports macro-definitions and import statements, thereby fos-tering code reuse when building WSN applications. In addition, it facilitatesdeveloping WSN applications as the interactions between the sensor nodes be-come clearly visible.

1.3 Document Overview

This dissertation introduces a new domain-specific programming language fordeveloping wireless sensor network applications from a node-level perspectiveand a complementary macroprogramming language that enables developmentfrom a network-level perspective.

Chapter 2 gives a non-exhaustive overview of the state of the art for pro-gramming wireless sensor networks. Existing solutions are covered by first fo-cussing on programming models that support the development of traditional,sense-only WSN applications and afterwards focussing on programming modelsthat support the development of the more recent, sense-and-react applications.

Our main solution, the node-centric language dubbed CrimeSPOT, is pre-sented in Chapter 3. All features are explained by incrementally implement-ing the running example presented in Section 3.1. More details concerningCrimeSPOT’s prototype implementation can be found in Appendix A and apreliminary evaluation of its overhead can be found in Appendix B.

In Chapter 4, the focus moves to Macro-CrimeSPOT, our macropro-gramming language that facilitates programming WSN applications using theCrimeSPOT language by moving from a node-level perspective to a network-level perspective. In this chapter, we also revisit the running example anddiscuss its final implementation.

To conclude, we validate our solutions through the implementation of illus-trative example applications in Chapter 5 and discuss our contributions andfuture work in Chapter 6.

Page 17: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

2State of the Art

This chapter gives a non-exhaustive overview of the state of the art for program-ming wireless sensor networks (WSNs). To date, several so-called programmingmodels have been proposed, which each target different requirements [1, 2]. Inthis chapter, we will focus on the typical ones, relevant to the problem at hand.

After introducing programming models for traditional WSNs, the focus movesto programming models for wireless sensor- and actuator networks (WSANs).WSANs are WSNs that employ, next to sensors, actuators to control the en-vironment. As we will discuss, programming WSANs requires more controlover the individual nodes and to this end, the typical programming models fortraditional WSNs are not appropriate.

2.1 Traditional Wireless Sensor Networks

The applications that made wireless sensor networks popular are sense-only ap-plications in which sensor data is extracted from the network. Typical examplesare applications for environmental monitoring and scientific data gathering [5–7].Programming models that support the development of these applications ab-stract the WSN as a single, abstract machine, that can be programmed as such.

The most common abstraction for a WSN is a virtual database of sensors,from which raw sensor data can be extracted through SQL-like queries. By us-ing this database abstraction, a developer can easily extract sensor data withouthaving to worry about how it is actually obtained. However, in some cases, itis desired to express more advanced queries for which SQL-like languages arenot appropriate. To this end, another type of programming models allows de-velopers to program queries through more advanced languages (e.g., functionalprogramming languages). A third typical type of programming models allows adeveloper to register event definitions to extract interpreted data from the net-work. An event definition specifies an event (e.g., an explosion) by listing itscharacteristics (i.e., the corresponding measured sensor values). After register-

5

Page 18: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

CHAPTER 2. STATE OF THE ART 6

ing event definitions, the programming model’s runtime will monitor the WSNand will inform the end-user when the registered events have been detected.

In the following sections, three programming models that are each offeringone of the above functionalities will be discussed in more detail.

2.1.1 Raw Data Extraction

The most straightforward way to extract raw data from a WSN is to make use ofa programming model that offers a database abstraction. Among the models of-fering this abstraction are TAG [14], Cougar [15], SINA [16] and TinyDB [3].In this section, we will give a brief overview of TinyDB, which is representativefor this category of programming models.

In TinyDB, the WSN is abstracted as a large sensors table, which has arow for every WSN node for every moment in time, and a column for each dataitem that can be produced by a node. The programmer can issue queries onthis table from a base station, which are then injected in the network. Thesequeries can be expressed in a language very similar to SQL. Listing 2.1 showsan example query, modified from [3]. Note that TinyDB supports aggregatessuch as AVG, SUM and COUNT, and also allows to define custom aggregates.

1 SELECT AVG(volume), room

2 FROM sensors

3 WHERE floor = 10

4 GROUP BY room

5 SAMPLE PERIOD 30s FOR 10 minutes

Listing 2.1: TinyDB: example query

Assuming that every WSN node provides a room and a floor value, this queryreports the average volume in all rooms on the tenth floor. The query hasa lifetime of ten minutes, in which a new update will be delivered to the basestation every 30 seconds (i.e., the sampling period). In the absence of an explicitsampling period, TinyDB will automatically decide the sampling according tothe query’s lifetime and the remaining battery level of the nodes involved in thequery’s processing. This is only one of the various optimizations that TinyDBuses to be as energy-efficient as possible.

Next to queries for pure data collection, TinyDB also supports actuatorqueries, which will invoke an external command whenever they are satisfied. Asan example, consider the query, modified from [3], in Listing 2.2.

1 SELECT nodeid , temp

2 FROM sensors

3 WHERE temp > 40

4 OUTPUT ACTION power -on-fan(nodeid)

5 SAMPLE PERIOD 60s

Listing 2.2: TinyDB: an actuator query

This query will verify the in-network temperatures every 60 seconds, and willinvoke the power-on-fan command as soon as a measured temperature exceeded40 degrees.

As the above examples illustrate, TinyDB allows programmers to expressdata extraction applications in a very concise notation. While TAG, Cougar,and SINA offer similar functionality, SINA extends this functionality with the

Page 19: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

CHAPTER 2. STATE OF THE ART 7

ability to send tasks to sensor nodes. Any task can be expressed in SINA’sSQTL language and will be executed on the target nodes. Optionally, a taskcan also return results to the base station. For instance, a vehicle trackingalgorithm can be implemented in SQTL [16].

2.1.2 Programming a Query

As mentioned earlier, the SQL-like languages offered by the programming mod-els that employ a database abstraction can be insufficient to express advancedqueries. As an example of an advanced query, consider a query that generatesan output whenever a fire is detected. While a fire can be detected by readingout temperature sensors and verifying whether the readings exceed a certainthreshold, false positives also have to be filtered out. This can be done, forinstance, by verifying whether the nodes in the immediate neighborhood of thenodes detecting a high temperature also measure a high temperature. Clearly,using the database abstraction would require the initiator of the temperaturequery to filter the results manually. However, programming models like Regi-ment [17] allow queries like this to be programmed in their entirety.

Regiment is a functional programming language that is based on the con-cept of Functional Reactive Programming (FRP). It is designed to compile andinstall long-running queries, which can be expressed by manipulations of datastreams. Regiment has two basic concepts: signals and regions. A signalrepresents a data stream (i.e., a time-varying value), while a region representsa collection of multiple signals. For instance, a sensor reading and the resultof a node’s computation are both signals, as they can vary over time. A re-gion, on the other hand, can represent all measured temperature readings ina given geographical region. Additionally, multiple signals within a region canalso be aggregated, resulting in a new signal (e.g., the sum of certain measuredtemperature readings).

To clarify these concepts, we can consider the example from Listing 2.3(modified from [17]), which implements the fire detection query discussed above.

1 fun readTemp(node) { sense("temp",node) }

2 fun tempTuple(node) { (node , readTemp(node)) }

3 fun aboveTresh ((node ,temp)) { temp > TEMP_THRESHOLD }

4 fun sumTempRegion(reg) { rfold ((+), 0, reg) }

56 possibleAlarms = rfilter(aboveTresh , rmap(tempTuple ,world ));

7 hoods = rmap( fun(n,t) { khood(1,n) }, possibleAlarms );

8 tempHoods = rmap( fun(reg) { rmap(readTemp ,reg) }, hoods);

9 tempSums = rmap(sumTempRegion , tempHoods );

10 BASE <- rfilter( fun(ts) { ts > CLUSTER_TEMP_TRESH }, tempSums );

Listing 2.3: Regiment: example query

Four auxiliary functions are defined for the query (lines 1-4): to read out thetemperature sensor of a particular node (readTemp), to place a node’s identifierand its measured temperature in a tuple (tempTuple), to verify whether thetemperature in such a tuple is above a certain threshold (aboveTresh), andto sum all temperatures in a region (sumTempRegion). Note that signals in aregion can be aggregated by using the predefined rfold function together witha combination function and an initial value (e.g., + and 0 in this case).

Page 20: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

CHAPTER 2. STATE OF THE ART 8

The statements on lines 6 to 10 implement the query. To this end, severalregions are defined. possibleAlarms represents the region consisting of temper-ature reading tuples that exceed a certain temperature threshold. This regionis obtained by mapping tempTuple over the predefined world region (i.e., theregion containing all nodes in the WSN) and filtering the results. hoods, onthe other hand, represents a nested region; it contains regions with all nodes ofthe one-hop neighborhood of the nodes in the possibleAlarms region. Theseone-hop neighborhood regions are obtained by mapping the predefined khood

function over the possibleAlarms region. To filter out false positives, the tem-perature has to be measured on each node of these sub-regions and the resultshave to be summed per sub-region (lines 8-9). Finally, fires are detected by veri-fying whether any of these sums exceed a certain cluster temperature threshold,and the exceeding sums are sent to the base station (line 10).

Even though the Regiment language is not as concise as the previouslydiscussed SQL-like languages, it does allow the programmer to program a widerange of queries.

2.1.3 Interpreted Data Extraction

While in the previously discussed programming models, the developer has toissue queries for raw sensor data, other programming models allow the devel-oper to register higher-level events to work with. This notion of event raisesthe level of abstraction as it associates semantics with raw sensor data. For in-stance, it can be specified that an explosion event corresponds to the detectionof a high temperature and an intense light. After registering such event def-initions, they are interpreted by the programming model’s runtime and allowto extract higher-level data from the sensor network. Among the program-ming models that allow to extract interpreted data from a WSN are SemanticStreams [18] and DSWare [19]. Even though both models are similar and al-low the definition of events, Semantic Streams requires the end-user to issuequeries over these events, while DSWare notifies the end-user when the regis-tered events have been detected. In this section, we will give a brief overviewof DSWare.

In DSWare, an event has to be described by a list of sub-events that haveto take place in a given time window and geographical region. A sub-event canbe either a predicate on an observed sensor reading, or another high-level event.In addition, it can be specified that not all sub-events have to take place fora detection of the high-level event to occur. This can be specified by a confi-dence function, which computes the confidence with which the event took place,and a minimum confidence required for the event to be detected. A confidencefunction can be arbitrarily defined and takes as arguments a boolean for everysub-event. This boolean indicates whether the sub-event took place in the giventime window and geographical region.

As an example, consider the definition of the explosion event shown in Listing2.4, modified from [1]. Note that event definitions are registered in an SQLdialect.

1 INSERT INTO EVENT_LIST(explosion , AREA , [0 ,0;200 ,200] , SUBEVENT_SET ,

2 user_base_station , 1 sec ,

3 1 hour)

Page 21: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

CHAPTER 2. STATE OF THE ART 9

45 SUBEVENT_SET (

6 SAFETY_TIMEOUT ,

7 (temperature > 60),

8 (light > 200),

9 (compareSound(sound ,explosionSignature ))

10 )

Listing 2.4: DSWare: An Event Definition

Lines 1 and 2 specify that the runtime should monitor for the explosion eventin the specified geographical area and report detections to the base stationwith a maximum delay of one second. In addition, line 3 specifies that thisdefinition remains valid for one hour. Lines 5 to 10 specify the explosion’s sub-events and the corresponding time window in which they have to take place (i.e.,SAFETY TIMEOUT). For simplicity, there’s no confidence function, nor minimumconfidence level. An explosion is detected as soon as a high temperature, anintense light, and a sound whose signature resembles that of an explosion havebeen detected. Based on this definition, the WSN is configured by DSWare tomeet the QoS requirements and to be as energy-efficient as possible.

2.1.4 Evaluation

Contemporary programming models for WSNs offer high-level and well-suitedabstractions to support the development of traditional, sense-only WSN ap-plications. The WSN is abstracted as a single, abstract machine that can beprogrammed as such. None of the discussed solutions require a programmer toworry about how data is obtained from a WSN (e.g., about which nodes haveto communicate to propagate the sensor data to the base station). As such,traditional WSN applications can be programmed quite straightforwardly.

However, this very high level of abstraction is not always appropriate. Forinstance, when building WSANs, a high degree of control is required over theindividual WSN nodes, which is typically not provided by the aforementionedmodels. With the exception of SINA, none of the models allow the programmerto express instructions that should be executed on individual nodes (e.g., tosteer an actuator). A WSAN programmer has no other option than relying onlower-level and more complex models, which allow the behavior of the individualnodes to be programmed. In the following section, we will discuss some of thesemodels.

2.2 Getting More Control over Individual Nodes

Next to traditional, sense-only WSN applications, wireless sensor- and actua-tor network (WSAN) applications are an emerging trend. Due to technologicaladvancements, sensor nodes become more powerful and become able to steeractuators to control their environment. Applications embracing these techno-logical advancements are often called sense-and-react applications [1]. In theseapplications, sensor data processing is typically moved inside the network, whichrequires complex node interactions to be programmed.

For developing sense-and-react applications, the aforementioned program-ming models are not appropriate. A high degree of control over the individual

Page 22: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

CHAPTER 2. STATE OF THE ART 10

sensor nodes is required, which is most often abstracted away in these mod-els. While developers of sense-and-react applications require control over theindividual nodes to steer actuators, they also require support for programmingthe individual nodes’ interactions, which are essential in the setting of sensornetworks. Programming these interactions is one of the most difficult challengesof WSANs [2].

In this section, we will discuss some representative node-level programmingmodels, solutions to support the specification of node interactions, and modelsthat allow the sensor network to be programmed from a macroscopic viewpointwhile still offering control over the individual nodes.

2.2.1 Node-centric Programming

Models for node-centric programming allow individual sensor nodes to be pro-grammed. As such, the programmer is offered a high degree of control overa node’s behavior. However, these programming models are quite low-level.For instance, interactions with other nodes have to be programmed using ex-plicit and physical addressing. In addition, not all models support reliable radioconnections. As two representative models, this section briefly discusses the pro-gramming models offered by TinyOS [20] and SunSPOT [21]. In the contextof this thesis, we will focus on how interactions can be programmed.

2.2.1.1 TinyOS

A sensor node running the TinyOS operating system can be programmed usingnesC [22] [1]. nesC is an event-driven programming language derived from C inwhich interfaces are one of the most central concepts. An interface lists functionsignatures that are either tagged as commands or events. While commandsignatures represent operations, event signatures represent the functions thatwill be invoked by operations to answer their results (i.e., event handlers). AnesC application consists of several components that interact by providing orusing these interfaces. While a component that provides an interface implementsits commands, a component that uses an interface implements its event handlers.Note that a nesC application’s components are statically fixed at compile-timeand cannot be changed at runtime.

To allow node interactions to be programmed, Active Messages [23] providesa set of interfaces containing basic nesC communication primitives. AMSend

and Receive are the most important interfaces and are shown in Listing 2.5.Other interfaces allow the low-level configuration of the communication primi-tives (e.g., by setting the transmission power).

1 interface AMSend {

2 command uint8_t maxPayloadLength ()

3 command void* getPayload(message_t* msg , uint8_t len)

4 command error_t send(am_addr_t addr , message_t* msg , uint8_t len)

5 command error_t cancel(message_t* msg)

6 event void sendDone(message_t* msg , error_t error)

7 }

8 interface Receive {

9 event message_t* receive(message_t* msg , void* payload , uint8_t len)

10 }

Listing 2.5: nesC: Communication Interfaces

Page 23: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

CHAPTER 2. STATE OF THE ART 11

To illustrate the use of nesC and these interfaces, we can consider a componentthat broadcasts its temperature reading in its one-hop neighborhood and printsout the temperature readings it receives. The code for this component, modifiedfrom [1], is shown in Listing 2.6.

1 module SampleAndPrint {

2 uses interface Boot;

3 uses interface TemperatureSensor;

4 uses interface AMSend;

5 uses interface Receive;

6 }

78 implementation {

9 message_t packet;

1011 event void Boot.booted () {

12 call TemperatureSensor.read ();

13 }

1415 event void TemperatureSensor.readDone(uint16_t temp) {

16 uint16_t* packet_payload = (uint16_t *)( call AMSend.getPayload (&packet , NULL ));

17 *packet_payload = temp;

18 call AMSend.send(AM_BROADCAST_ADDR , &packet , sizeof(uint16_t ));

19 }

2021 event void AMSend.sendDone(message_t* msg , error_t error) {

22 if(msg == &packet && error = SUCCESS) {

23 printf("Successfully sent temperature");

24 }

25 }

2627 event message_t* Receive.receive(message_t* msg , void* payload , uint8_t len) {

28 if(len == sizeof(uint16_t )) {

29 printf("Received temperature %d", *payload );

30 }

31 return msg;

32 }

33 }

Listing 2.6: nesC: Communication Example

To start its application logic, this component uses the Boot interface, whichsignals a booted event when the TinyOS system is successfully started. Theevent handler for this event is implemented on lines 11 to 13 and calls the asyn-chronous read() operation on the TemperatureSensor to obtain the currenttemperature. Note that read() is a split-phase operation, which means that itreturns its result by invoking an event handler (i.e., readDone). In this eventhandler, the measured temperature is encapsulated in a packet and broadcastedusing AMSend’s send operation (lines 15-19). When this operation finishes, thesendDone event handler will be invoked and a debug message is printed (lines21-25). Note that other components on the sensor node can also use AMSend’ssend operation, which would cause this sendDone event handler to be invoked,too. Therefore, it is verified whether the sent packet is the one originating fromthis component before printing the debug message. Finally, the receive eventhandler will be invoked whenever a packet is received from the network. In thisevent handler, the packet is parsed and its contents are printed if it containeda temperature (lines 27-32).

Depending on the sensor hardware, a specific Active Messages implemen-

Page 24: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

CHAPTER 2. STATE OF THE ART 12

tation has to be used. However, in general, the implementations only supportunreliable one-hop unicast or broadcast transmissions.

2.2.1.2 SunSPOT

SunSPOT sensor nodes (SunSPOTs) can be programmed in Java ME. In con-trast to nesC, this allows the object-oriented programming paradigm to be usedfor programming WSN applications. To write node-level sensor code, it sufficesto create a subclass of the MIDlet base-class. A MIDlet can be compared toa component from nesC and one or more MIDlets can run next to each otheron a single SunSPOT. However, as every MIDlet runs in isolation (i.e., in anisolate), MIDlets do not share mutable memory. Note that, unlike nesC’s com-ponents, MIDlets can be dynamically deployed, started, paused, stopped, andundeployed (i.e. at runtime).

For programming node interactions, either a reliable streaming or an unre-liable datagram-style connection can be employed. These connections allow anode to interact with other nodes in its one-hop neighborhood. As in nesC,a node’s transmission power can also be adjusted. Listing 2.7 illustrates theuse of the datagram-style connection (i.e., a radiogram connection) by showingthe code for a MIDlet that broadcasts its temperature reading in its one-hopneighborhood and prints out the temperature readings it receives.

1 public class SampleAndPrint extends MIDlet {

2 protected void startApp () throws MIDletStateChangeException {

3 try {

4 int temp = EDemoBoard.getInstance (). getADCTemperature (). getValue ();

56 DatagramConnection dgConnection = null;

7 Datagram dg = null;

89 dgConnection = (DatagramConnection)Connector.open("radiogram :// broadcast :50");

10 dg = dgConnection.newDatagram(dgConnection.getMaximumLength ());

11 dg.writeInt(temp);

12 dgConnection.send(dg);

13 System.out.println("Successfully sent temperature");

1415 dgConnection = (RadiogramConnection) Connector.open("radiogram ://:50");

16 dg = dgConnection.newDatagram(dgConnection.getMaximumLength ());

17 while(true) {

18 dg.reset ();

19 dgConnection.receive(dg);

20 temp = dg.readInt ();

21 System.out.println("Received temperature " + temp);

22 }

23 } catch(IOException ioe) {

24 /* Error */

25 }

26 }

2728 protected void pauseApp () { }

29 protected void destroyApp(boolean b) throws MIDletStateChangeException { }

30 }

Listing 2.7: SunSPOT: Communication Example

As soon as the MIDlet is started, its startApp() method will be invoked.Remember that a MIDlet can also be paused or destroyed, upon which the

Page 25: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

CHAPTER 2. STATE OF THE ART 13

pauseApp() and destroyApp() methods will be invoked, respectively. How-ever, as these methods are irrelevant for this MIDlet, their implementations areleft blank. When the MIDlet starts, it obtains a temperature reading by readingout a temperature sensor (line 4). Afterwards, a datagram connection is initial-ized for broadcasting and a datagram encapsulating the measured temperatureis sent over the node’s radio (lines 6-13). Finally, to receive and print other tem-perature readings, a new datagram connection is initialized and listened upon(lines 15-22). For identifying the temperature datagrams, they are broadcastedand listened for on channel 50, as specified in the connection initialization state-ments (lines 9,15). Note that the send and receive methods are blocking andwill only return when a new temperature datagram has been successfully sentor received. In case something goes wrong, these methods throw an exception.

2.2.1.3 Evaluation

Node-centric programming models offer a high degree of control over individualsensor nodes as they allow to explicitly specify these nodes’ behavior. However,programming using these models is quite low-level. The programmer is respon-sible to write energy-efficient code and complex interactions among nodes mightrequire the implementation of advanced routing algorithms on top of the verybasic, typically one-hop, communication primitives. Even when interactions arelimited to a node’s one-hop neighborhood, they can become very complex asseveral messages might have to be exchanged with the neighboring nodes (e.g.,for in-network processing). In these cases, application logic (e.g., controllingan actuator) and interaction logic (e.g., encapsulating messages in packets andparsing packets upon reception) become tangled, rendering the code difficult tounderstand, maintain, extend or reuse. To deal with these problem, several solu-tions, typically to be used in combination with these node-centric models, havebeen proposed. The following section discusses some of the most representativeones.

2.2.2 Support for Interactions among Nodes

Programming interactions among nodes, essential in the setting of sensor net-works, is one of the most difficult challenges of WSANs [2]. As discussed in theprevious section, basic communication primitives are often not appropriate tomodel rich interactions. To this end, several solutions have been proposed tofacilitate programming these interactions. This section discusses some of themost representative ones, which either support node communication throughmessage exchanges or date sharing.

2.2.2.1 Communication Through Messages

Typically, sensor nodes communicate by exchanging messages. At a low level,messages are represented as packets that are physically addressed to other nodesin a node’s one-hop neighborhood. To facilitate communication through mes-sages, solutions like Logical Neighborhoods [24] allow messages to be log-ically addressed to groups of nodes anywhere in the network. Solutions likeLooCI [25], on the other hand, abstract messages as events that can be ex-

Page 26: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

CHAPTER 2. STATE OF THE ART 14

changed throughout the network by using a Publish-Subscribe interaction pat-tern [13].

Logical Neighborhoods. Logical Neighborhoods is a programming ab-straction that allows a node to define its neighborhoods based on logical proper-ties of the nodes in the network. This extends the previously mentioned notionof neighborhood, which was based on a node’s radio communication range. De-pending on the definition of a neighborhood, some nodes will be in it, whileother nodes won’t. Note that these nodes might be located anywhere in thenetwork, and not necessarily in the one-hop neighborhood of the node definingthe neighborhood. Neighborhoods can be defined using a declarative program-ming language, called Spidey, which is an extension to an existing node-centricprogramming language (e.g., Spidey has been built on top of TinyOS’s nesC).After defining a neighborhood, variants of the underlying language’s communi-cation primitives (i.e., send in nesC) can be employed to send messages to itsmembers.

As an example, we can consider a WSAN application for detecting andfighting fire. In every room, several smoke sensors have to be deployed, nextto a single actuator node for controlling the sprinklers. To allow the actuatornode to easily communicate with the smoke sensors in its room, it can definethe mySensors neighborhood as shown in Listing 2.8.

1 neighborhood template SmokeSensors(loc)

2 with Function = "sensor" and

3 Type = "smoke" and

4 Location = loc

56 create neighborhood mySensors

7 from SmokeSensors(loc: "auditorium A")

8 max hops 3 credits 30

Listing 2.8: Logical Neighborhoods: neighborhood template and instantiation

A neighborhood definition consists of a template and an instantiation. In thisexample, the template SmokeSensors(loc) includes all smoke sensors located inloc (lines 1-4). As the actuator node is in auditorium A, it creates a mySensors

neighborhood by instantiating the template with the appropriate location (lines6-8). Note that this instantiation also specifies the maximum number of hopsthat a member of the neighborhood can be separated from the actuator, anda limit on the cost for communication in terms of credits (i.e., an application-defined notion of communication costs).

To allow attributes such as Function and Type to be used in a neighborhooddefinition, potential members of the neighborhood should export them. To thisend, all potential members have to instantiate a node-template. Listing 2.9shows the Spidey code to be used by a smoke sensor from the example.

1 node template Device

2 static Function

3 static Type

4 static Location

5 dynamic BatteryPower

67 create node smoke1 from Device

8 Function as "sensor"

9 Type as "smoke"

Page 27: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

CHAPTER 2. STATE OF THE ART 15

10 Location as "auditorium A"

11 BatteryPower as getBatteryPower ()

Listing 2.9: Logical Neighborhoods: node template and instantiation

While the node template (lines 1-5) lists all exported attributes and their nature(i.e., static or dynamic), its instantiation (lines 7-11) provides a node’s valuesfor these exported attributes.

LooCI. LooCI is an event-based WSN middleware that introduces both acomponent infrastructure and a decentralized event-bus to sensor networks. Itallows multiple components to be deployed on the same sensor node and itallows these components to communicate by exchanging events through thedecentralized event-bus. Events abstract messages; they have a particular typeand a payload that contains their values. Components can both publish eventsand subscribe to certain event types. Based on the event-subscriptions (i.e.,so-called wirings), the events published in the sensor network will be routedfrom the publishers to the subscribers. LooCI is available on the SunSPOTplatform where its components can be compared to MIDlets. A componentcan publish events by using the publish(Event) method, and it can processthe events it received by implementing an event handler. In addition, LooCIcomes with a gateway application to run on a back-end entity, which allowsto remotely deploy components on the nodes in the network, and to configurethe wirings amongst these components. As a result, sensor networks using theLooCI middleware can be dynamically (re)configured.

As an example, Listing 2.10 shows the code for a component that acts as atemperature filter (taken from the LooCI website1). This component subscribesto temperature reading events, which it will re-publish only when they exceeda certain threshold. This component has to be wired to a component thatpublishes temperature readings and to other components that subscribe to thesereadings.

1 public class TempFilter extends LooCIComponent {

2 private final int TEMP_THRESHOLD = 20;

34 public TempFilter () {

5 super("TempFilter", // component type

6 new byte []{ EventTypes.TEMP_READING}, // publications

7 new byte []{ EventTypes.TEMP_READING }); // subscriptions

8 }

910 protected void start() { }

11 protected void stop() { }

1213 public void receive(Event event) {

14 if (event.getType () == EventTypes.TEMP_READING) {

15 PayloadBuilder payload = new PayloadBuilder(event.getPayload ());

16 int reading = payload.getIntegerAt (0);

17 System.out.println("[TempFilter] Received temperature: " + reading );

18 if (reading > TEMP_THRESHOLD) {

19 payload = new PayloadBuilder ();

20 payload.addInteger(reading );

21 publish(new Event(EventTypes.TEMP_READING , getComponentID (),

22 payload.getPayload ()));

23 }

1http://code.google.com/p/looci/wiki/FirstComponent

Page 28: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

CHAPTER 2. STATE OF THE ART 16

24 }

25 }

26 }

Listing 2.10: LooCI: A Temperature Filter Component

As soon as the component is started or stopped, its start or stop methodwill be invoked, respectively. However, as no special actions are required onthese moments, the implementation for these methods is left blank (lines 10-11). The component’s main functionality is implemented in its event handler(i.e., the receive(Event) method), which will be invoked whenever a new eventis received. In case the received event is a temperature reading, the measuredtemperature is extracted from the event’s payload, compared to the tempera-ture threshold, and published in a new temperature reading event if it exceededthe threshold (lines 13-25). Finally, the super call in the component’s con-structor specifies the component’s name together with the events it publishesand the events it subscribes to (lines 4-8). Note, however, that this data in theconstructor is only meta-data that can be read using the gateway. To achieveinteractions between components, wirings have to be explicitly configured. Eventhough these wirings can be hard-coded within a component’s implementation,they are typically configured from the gateway.

To illustrate how the above component can be used, Listing 2.11 shows atranscript of an interactive session with the gateway.

1 deploy TempSensor.jar 0000.0000.0000.0001

2 => 3

3 deploy TempFilter.jar 0000.0000.0000.0001

4 => 4

5 wireLocal 101 3 101 4 0000.0000.0000.0001

6 => true

7 wireToAll 101 4 0000.0000.0000.0001

8 => true

9 deploy TempDisplay.jar 0000.0000.0000.0002

10 => 3

11 wireFrom 101 4 0000.0000.0000.0001 101 3 0000.0000.0000.0002

12 => true

Listing 2.11: LooCI: Interacting with the gateway

This transcript assumes the existence of three components: a temperature sen-sor, a temperature filter and a component for displaying temperatures. For theirinteractions, these components all employ temperature reading events, whichhave event type 101. The components are deployed to two different nodes inthe network (lines 1,3,9). Note that the gateway always answers a component’snode-local identifier after deployment (lines 2,4,10). These identifiers have tobe used for wiring the components. As both the temperature sensor and -filterhave been deployed on the same node, they are wired using wireLocal. Thecommand on line 5 states that every temperature event published by the tem-perature sensor has to be delivered to the temperature filter. The temperaturefilter’s published events, on the other hand, should be delivered to all compo-nents wired to it, which is expressed using wireToAll (line 7). Finally, thecomponent for displaying temperature events should obtain these events fromthe temperature filter and is therefore wired to it using wireFrom (line 11).Next to the illustrated commands, wireTo and wireFromAll can also be usedfor wirings components. While the first allows a component to be wired to

Page 29: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

CHAPTER 2. STATE OF THE ART 17

send its events to a specifically addressed other component, the latter allows acomponent to be wired to receive a certain event from any component.

2.2.2.2 Communication Through Data Sharing

Next to communicating by exchanging messages, sensor nodes can also com-municate by sharing data. Solutions that support this kind of communicationintroduce a shared memory space for a particular region of the network in whichnodes can read or write data. This shared data is commonly represented asshared variables or tuples. In this section, we will discuss three representativesolutions: Abstract Regions [26], which allows variables to be shared and ag-gregated, TeenyLIME [27], which allows tuples to be shared and reacted uponthrough event handlers, and FACTS [28], which allows tuples to be shared andreacted upon through declarative rules.

Abstract Regions. Abstract Regions is a collection of communicationprimitives that provide data sharing and aggregation in a particular region ofa sensor network. To share data within a region, a node can export namedvariables, which can be read remotely by other nodes within the region. Inaddition, when several nodes export variables with identical names, their valuescan be aggregated using an associative operator (e.g., sum, max or min). Anode can define an arbitrary number of regions in terms of radio connectivityor geographic location (e.g., a region with all nodes within n radio hops, or thek nearest nodes). To support QoS requirements, the communication primitivesalso return some quality measures (e.g., the amount of nodes that participatedin an aggregation). Based on these measures, low-level communication pa-rameters can be tweaked through a tuning interface. Abstract Regions wasimplemented in nesC and employs a lightweight, thread-like concurrency modelto provide blocking operations.

To illustrate the use of Abstract Regions, we can consider an object-tracking application. This application uses several sensor nodes to take periodicmagnetometer readings. Every node shares its readings and its location, andindividually verifies whether its reading exceeds a certain threshold. In thiscase, an object is detected and its centroid can be computed using the sharedvariables to estimate its location. Listing 2.12 shows the code to be deployedon the sensor nodes (modified from [26]).

1 location = get_location ();

23 // Create a region with the 8 nearest neighbors

4 region = k_nearest_region.create (8);

56 while (true) {

7 reading = get_sensor_reading ();

89 // Store data in shared variables

10 region.putvar(reading_key , reading );

11 region.putvar(reg_x_key , reading * location.x);

12 region.putvar(reg_y_key , reading * location.y);

1314 if (reading > threshold) {

15 // Obtain the ID of the node that measured the highest reading (i.e., the leader)

16 max_id = region.reduce(OP_MAXID , reading_key );

17

Page 30: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

CHAPTER 2. STATE OF THE ART 18

18 // If I am the leader ...

19 if (max_id == my_id) {

20 // Compute the centroid

21 sum = region.reduce(OP_SUM , reading_key );

22 sum_x = region.reduce(OP_SUM , reg_x_key );

23 sum_y = region.reduce(OP_SUM , reg_y_key );

24 centroid.x = sum_x / sum;

25 centroid.y = sum_y / sum;

26 send_to_basestation(centroid );

27 }

28 }

29 sleep(periodic_delay );

30 }

Listing 2.12: Abstract Regions: Implementing an object-tracking application

Every sensor node initializes a region to contain its eight nearest neighbors usingthe k nearest region.create() primitive (line 4). In the main loop (lines 6-30), the magnetometer is read out and the required data is stored in sharedvariables using the putvar() primitive (lines 7-12). If the reading happens tobe above the predefined threshold, an object is detected and its position shouldbe computed. However, to make sure that only a single node computes thisposition, a leader is elected based on the measured magnetometer readings. Tothis end, the reduce() primitive is employed to aggregate the measured readingsusing the OP MAXID operator (line 16). Finally, the node verifies whether it waselected as the leader, and if so, it computes the centroid and sends it to the basestation (lines 18-27).

TeenyLIME. TeenyLIME brings the tuple space abstraction, originally pro-posed in Linda [29], to WSNs. A tuple space (TS) is a repository of tuples, whichrepresent data as a sequence of typed fields (e.g., < ”temp”, 30 >). Every nodehas a local TS, which is shared with other nodes in its one-hop neighborhood,and several operations can be performed on either the local TS, or the union ofall TS’s in the neighborhood (i.e., the shared TS). As in Linda, tuples can bestored using the out operation, read using the rd operation, and removed usingthe in operation. For the latter operations, tuples can be matched throughpattern matching. A pattern is a tuple with fields for which the exact valueshave not been specified (e.g., < ”temp”, ?int >). In contrast to Linda, fieldsin a pattern can also be constrained by a predicate and a pattern can be con-strained only to match tuples of a certain age. In addition, tuples can be setto expire, after which they are automatically removed from the TS. Next to theabove operations, reactions can also be registered on a TS, and the notion ofcapability tuples allows a node to store a pattern in its TS, which it can theninstantiate whenever it is matched by a query from another node. The lattercan be used, for instance, to make a node read out its sensors only on demand.TeenyLIME has been implemented on top of TinyOS and provides an APIfor nesC. As all operations are split-phase operations, they return their resultsby invoking an event handler.

To illustrate the API, we can consider an application for detecting fire, whichbases its detection on very high temperature readings. Under the assumptionthat all temperature sensors are in the one-hop neighborhood of an actuator thatcontrols sprinklers, the code from Listings 2.13 and 2.14, modified from [27], canbe deployed on the sensor- and actuator nodes, respectively.

Page 31: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

CHAPTER 2. STATE OF THE ART 19

1 event void Boot.booted () {

2 call SensingTimer.start(TIMER_REPEAT , SENSING_TIMER );

3 }

45 event result_t SensingTimer.fired() {

6 return call TemperatureSensor.read ();

7 }

89 event void TemperatureSensor.readDone(uint16_t temp) {

10 tuple tempTuple = newTuple(2, actualField_uint16(TEMPERATURE),

11 actualField_uint16(temp ));

12 setExpireIn(tempTuple , 3);

13 call TupleSpace.out(FALSE ,TL_LOCAL ,& tempTuple );

14 return SUCCESS;

15 }

Listing 2.13: TeenyLIME: code for a sensor

1 TLOpId_t tempTupleReaction;

23 event void Boot.booted () {

4 tuple tempPattern = newTuple(2, actualField_uint16(TEMPERATURE),

5 greaterField(TEMPERATURE_SAFETY ));

6 tempTupleReaction = call TS.addReaction(TRUE , TL_NEIGHBORHOOD ,

7 &tempPattern );

8 }

9 event result_t TS.tupleReady(TLOpId_t opId , tuple* tuples , uint8_t number) {

10 if(opId == tempTupleReaction) {

11 // Turn on sprinklers ...

12 }

13 }

Listing 2.14: TeenyLIME: code for an actuator

As soon the temperature sensor is started, it sets a timer to be fired periodically(Listing 2.13, lines 1-3). When this timer fires, the current temperature ismeasured, encapsulated in a tuple and stored in the local tuple space, as specifiedby TL LOCAL in the out operation (lines 5-15). Note that the tuple is set to expireafter 3 epochs2 (line 12). The actuator node, on the other hand, configures itsTS when it is started. To this end, a pattern for matching temperature tupleswith a value exceeding the predefined threshold is created (Listing 2.14, lines4-5) and used to register a reaction on the shared TS, as specified by TL -

NEIGHBORHOOD in the addReaction operation (lines 6-7). As soon as a tuplein the shared TS matches this pattern, the tupleReady event will be fired,and the sprinklers can be turned on (lines 9-13). Note that both out andaddReaction take a boolean as a first argument (Listing 2.13, line 13, Listing2.14, line 6). This boolean indicates whether the tuples for the operation shouldbe communicated reliably. As it is important for the actuator’s reaction to betriggered when a high temperature is observed, this boolean is set to true forthe reaction. In addition, note that every operation in the TeenyLIME APIreturns an operation id, which can be used in the event handler to identify theoperation that completed (Listing 2.14 lines 6,10). Finally, even though tuplescan expire, it is not possible to react to their expiration and therefore specialapplication logic would be required to decide when to turn off the sprinklersfrom the example.

2An epoch is a constant amount of time specified by TeenyLIME.

Page 32: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

CHAPTER 2. STATE OF THE ART 20

FACTS. FACTS introduces a rule-based programming language to WSNs.Its main abstractions are facts, rules, and functions. Facts are named tuplesconsisting of key-value pairs and are stored in a node-local fact repository. Incontrast to TeenyLIME’s tuple space, the fact repository itself is not shared,but a fact can be sent to other nodes (possibly multiple hops away) which willthen add it to their fact repository. As such, a fact repository can contain factsoriginating from several nodes. Whenever a fact is added to the fact repository,it can trigger the execution of rules, which specify a reaction to facts. Rules arenamed and consist of a set of conditions and an ordered list of statements tobe executed whenever their conditions are met. While a condition can verify aboolean expression or the presence of a particular fact in the fact repository, astatement can call a C function or create, remove, modify or publish facts. Forinstance, a C function can read out a sensor and the result can be stored in a newfact. Both conditions and statements can take a slot as a parameter, which hasto be used to select relevant facts from the fact repository. As such, conditionsand statements are entirely independent: while a parametrized condition issatisfied when at least one fact matches its slot, a parametrized statement isexecuted for every fact matching its slot. Finally, FACTS encapsulates relatedrules and facts in a ruleset, which can be compared to a component that providesa certain service. Rulesets can use other rulesets, which fosters code reuse.

As an example, we can consider the implementation of a coverage algo-rithm. In this algorithm, every node broadcasts its range and individually ver-ifies whether it covers the range of any other node. Based on this knowledge,some sensor nodes might, for instance, be put to sleep. Listing 2.15 shows theimplementation for this algorithm (modified from [28]), which can be deployedon every sensor node in the network. A rule is written as its name, followed byits conditions prefixed with <- and its statements prefixed with ->.

1 sendRange

2 <- Exists Timer.expiredSlot

3 -> Retract Timer.expiredSlot

4 -> Define "rangeFact"

5 -> Set ("rangeFact" "xMin") (posXSlot - System.txRadiusSlot)

6 -> Set ("rangeFact" "xMax") (posXSlot + System.txRadiusSlot)

7 -> Set ("rangeFact" "yMin") (posYSlot - System.txRadiusSlot)

8 -> Set ("rangeFact" "yMax") (posYSlot + System.txRadiusSlot)

9 -> Send 0 System.txPowerSlot

10 ("rangeFact" [(("rangeFact" "owner") == nodeIDSlot )])

11 -> Define "rangeSendFact"

1213 xyMinCovered

14 <- Exists "rangeSendFact"

15 <- Eval (( posXSlot - System.txRadiusSlot) < ("rangeFact" "xMin"))

16 <- Eval (( posYSlot - System.txRadiusSlot) < ("rangeFact" "yMin"))

17 -> Define "xyMinCoveredFact"

1819 determineCoverage

20 <- Exists "xyMinCoveredFact"

21 <- Exists "xMaxYMinCoveredFact"

22 <- Exists "xyMaxCoveredFact"

23 <- Exists "xMinYMmaxCoveredFact"

24 -> Define "coveredFact"

Listing 2.15: FACTS: a coverage algorithm

The sendRange rule is triggered by a timer that adds a fact to the fact repos-itory upon firing (lines 1-2). As a reaction, the rule removes the timer’s fact

Page 33: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

CHAPTER 2. STATE OF THE ART 21

and creates a new rangeFact to contain the node’s range (lines 3-8). This factis broadcasted to all nodes in the one-hop neighborhood (line 9-10). Note thatonly the locally created fact has to be broadcasted to avoid re-broadcastingrangeFacts from other nodes. To this end, the fact to be broadcasted is se-lected from the fact repository using a slot with an additional condition onthe fact’s owner, expressed between brackets (line 10). After broadcastingthe fact, a rangeSendFact is added to the fact repository to indicate thatthe range information was published (line 11). Afterwards, a node awaitsthe rangeFacts from its neighbors. Whenever such a fact is received, thexyMinCovered, xMaxYMinCovered, xMinYMaxCovered, and xyMaxCovered ruleswill inspect its data to verify whether the sensor node is covering the receivedrange. For brevity, only the xyMinCovered rule is shown (lines 13-17). Notethat this rule adds a xyMinCoveredFact to the fact repository if the bottom-left of the received range is covered (line 17). When all corners of the receivedrange are covered, the range is covered and a coveredFact is added to the factrepository (lines 19-24). This fact can be used in other rules to act accordingly.

2.2.2.3 Evaluation

This section introduced several representative solutions that aid in specifyinginteractions among sensor nodes when programming sensor network applicationsfrom a node-level perspective. To this end, it categorized the solutions accordingto the type of communication that they support.

While the solutions for communication through messages clearly facilitatesending messages, they do not help in processing these messages upon reception.Indeed, both Active Messages and LooCI require all received messages (orevents) to be parsed and processed in a single event handler. Clearly, thisapproach won’t scale as a node participates in more interactions (e.g., for in-network processing of various data from several nodes).

For the solutions supporting communication through data sharing, more vari-ations were presented. For instance, Abstract Regions allows to elegantlyexpress algorithms that operate on data originating from several nodes in thenetwork through aggregation. As a result, it is very appropriate to programin-network processing logic. However, as it does not provide any means to reactto the appearance of new data, there’s no other option than to actively pullthe shared data in order to process it. TeenyLIME, on the other hand, allowsto react to the appearance of new data in the shared tuple space. Neverthe-less, it suffers from the exact same issues as were identified for the solutionsfor communication through messages: all registered reactions have to be dealtwith in a single event handler. Despite this fact, TeenyLIME also introducedsome interesting ideas. For instance, as tuples commonly contain sensor data,typically only useful for a limited amount of time, the introduction of tupleexpiration and the ability to react to tuples with a maximum age is clearlywell-founded. The ability to react to the expiration of tuples can be consideredas a missing feature. Finally, FACTS’ rules allow to modularize interactions.When a node has to react differently to various facts (i.e., when it participatesin multiple interactions), it suffices to install multiple rules. In addition, unlikeTeenyLIME, FACTS allows to react to the appearance of multiple facts (e.g.,a temperature- and a humidity fact). However, variables can be considered asa missing feature. In the absence of variables, no facts can be related by their

Page 34: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

CHAPTER 2. STATE OF THE ART 22

content. For instance, it’s not possible to express a rule to compute a comfortlevel based on a temperature sensor reading and a humidity sensor reading thatoriginate from the same node or room. Terfloth et al. motivate the absenceof variables by the fact that binding these variables at runtime would be tooexpensive in terms of memory usage for an embedded system [28]. Noteworthy,however, is the idea to modularize rules in rulesets that can be reused by otherrulesets.

2.2.3 Network-centric Programming

Having introduced node-centric programming models and solutions that supportprogramming node interactions from a node-level perspective, we shift our focusto the programming models that allow a sensor network to be programmedfrom a macroscopic viewpoint while still offering control over the individualnodes. These programming models are often referred to as network-centric-or macroprogramming models [2]. As they allow the desired global behaviorof the entire sensor network to be programmed in a centralized fashion, theprogrammer can maintain a high-level overview of the application.

Network-centric programming models can be categorized according to theirtarget applications, which can be either applications exhibiting logical homo-geneity, applications requiring mobile code or applications exhibiting logical het-erogeneity. This section briefly introduces one representative model for eachcategory and thereby completes the picture of the major approaches in thestate of the art for programming wireless sensor networks.

2.2.3.1 Models for Homogeneous Applications

In applications that exhibit logical homogeneity, every sensor node requires thesame behavior. Typical examples are applications for constructing a routingtree or for tracking objects. Among the programming models that support thedevelopment of this kind of applications are Kairos [30] and snLog [31]. WhilesnLog is a declarative, rule-based language, Kairos is a set of abstractions thatcan extend any imperative language. As a representative example for this cat-egory of programming models, we will briefly discuss the latter.

Kairos abstracts a wireless sensor network as a collection of nodes that canall be programmed together in a single program. To this end, it extends anynode-centric programming language with three abstractions: an abstraction fora node, typically a member of a node-set that can be iterated over, an abstrac-tion for a list containing a node’s one-hop neighbors (i.e., a node-set), and anabstraction for remote (read-only) access to a node’s variables. Using these ab-stractions, a WSN application can be programmed in a way that resembles thehigh-level algorithm descriptions found in textbooks. Kairos comes with a pre-compiler to compile its programs to code for the extended node-level language,and a runtime library for this language. Both the precompiler and the run-time have been implemented as an extension to Python. After precompiling aKairos program and compiling the node-level code, the binary can be deployedon every node in the network. By default, the Kairos runtime loosely synchro-nizes state across nodes, which means that reading a remote variable initiallyblocks until the value is obtained and cached, but afterwards immediately re-

Page 35: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

CHAPTER 2. STATE OF THE ART 23

turns the cached value. To reduce communication overhead, these cached valuesare lazily updated as the remote variables are modified, and as such, eventuallyconverge to the most recent values.

To illustrate Kairos’ programming model, we can consider an applicationfor constructing a shortest-path routing tree. In this program, every node pe-riodically queries its neighbors for their distance to the root, selects the nodeat the shortest distance, and updates its own parent node accordingly. Listing2.16 shows the code for this application (modified from [30]).

1 void buildtree(node root)

2 node parent , self;

3 unsigned short dist_from_root;

4 node_list neighboring_nodes , full_node_set;

5 unsigned int sleep_interval =1000;

6 // Initialize every node

7 full_node_set=get_available_nodes ();

8 for (node temp=get_first(full_node_set );

9 temp!=NULL;

10 temp=get_next(full_node_set ))

11 self=get_local_node_id ();

12 if (temp==root)

13 dist_from_root =0;

14 parent=self;

15 else

16 dist_from_root=INF;

17 neighboring_nodes=create_node_list(get_neighbors(temp ));

18 // Start the main loop on every node

19 full_node_set=get_available_nodes ();

20 for (node iter1=get_first(full_node_set );

21 iter1!=NULL;

22 iter1=get_next(full_node_set ))

23 for (;;)

24 sleep(sleep_interval );

25 for (node iter2=get_first(neighboring_nodes );

26 iter2!=NULL;

27 iter2=get_next(neighboring_nodes ))

28 if (dist_from_root@iter2 +1< dist_from_root)

29 dist_from_root=dist_from_root@iter2 +1;

30 parent=iter2;

Listing 2.16: Kairos: Constructing a shortest-path routing tree

Lines 2 to 5 declare the variables relevant to the application. These variablescan be used in the context of the global program (e.g., full node set), or inthe context of a node (i.e., within an iteration over all nodes). By iteratingover all nodes in the sensor network, obtained from get available nodes()

(line 7), every node’s state is first initialized (lines 8-17). Only the root nodeknows its distance to the root, and its parent (i.e., itself). In addition, everynode’s neighboring nodes are obtained using get neighbors(Node) (line 17).Afterwards, the main loop is started on every node (lines 18-30). After a periodof sleep, the distance from each neighbor to the root is remotely read usingdist from root@iter2 (line 28), and a neighbor is set as a node’s parent if itprovides a shorter path to the root than the currently stored one (lines 28-30).Note that, due to the loose state synchronization, the remotely read distanceis not necessary the most recent one. However, as every node keeps loopingto update its state, every node will eventually obtain the right parent on theshortest path to the root node.

Page 36: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

CHAPTER 2. STATE OF THE ART 24

2.2.3.2 Models for Mobile Code

Certain applications or network tasks can be elegantly expressed as agents thatmove throughout a WSN. The implementation of such an agent is often calledmobile code [1]. After injecting an agent in a WSN, it autonomously movesthroughout the network to execute instructions on every visited node, and af-terwards typically returns to the node where it was injected to return some val-ues. Among the programming models that support the development of mobilecode are ActorNet [4], Spatial Programming [32] and SpatialViews [33].ActorNet allows mobile code to be written in a Scheme-like language, and itallows this code to migrate from a node to any other node in its one-hop neigh-borhood. Spatial Programming and SpatialViews, on the other hand,allow regions in the WSN to be specified and allow mobile code to migrate tothe nodes within these regions. Note that, as the position of the nodes mightchange, their membership in a particular region can also change. Since bothSpatial Programming and SpatialViews expect the nodes to have sub-stantial computation and communication resources, an unrealistic scenario inWSNs, we will discuss ActorNet as a representative example for this categoryof programming models.

ActorNet is a Scheme-like language that allows programming mobile agents.To this end, it implements the actor model of distributed computing [34] onWSNs. An agent is represented by an actor, which can migrate itself to anothernode in its one-hop neighborhood. In addition, every node runs, by default, asingle launcher actor. A launcher actor can be sent expressions which it willevaluate. As such, an actor can evaluate expressions on the nodes in its one-hopneighborhood, which can communicate their result back to their originating ac-tor through message passing. In ActorNet, actor migration is implementedin terms of the callcc primitive, which takes a single-parameter function asits operand, and calls this function with the current continuation. Because thestate of an actor is represented by its current continuation and the value thatwill be passed to it, an actor can migrate to a neighboring node by sendingits continuation and its value to that node’s launcher actor. As a result, thelauncher actor will evaluate the continuation and continue the migrated actor’swork. The implementation for the migrate primitive, modified from [4], isshown below:

1 (define (migrate addr value) ; Migrate to actor addressed by addr

2 (callcc (lambda (cc)

3 (send addr cc value ))))

The send primitive is used to send a message to the launcher actor with addressaddr (line 3). Note that send can also be used to send a message to a regularactor, which can access its messages in a queue accessible through the msgq

primitive.To illustrate ActorNet’s programming model, we can consider an actor

that searches a WSN for the node where the highest temperature is measured,turns on a LED on this node, and returns the measured temperature to thebase station to print it. The code for this searching actor, modified from [4], isshown in Listing 2.17.

1 (rec (measure (oriActor) ; Return temp and launcher actor id

2 (send oriActor (io 1) (io 0)))) ; to originating actor

Page 37: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

CHAPTER 2. STATE OF THE ART 25

34 (rec (move returnPath maxTemp) ; Searching Actor

5 (seq

6 ;; evaluate measure on the neighbors

7 (send 0 measure (id))

8 (delay 100) ;;wait for 10 sec

9 (( lambda (maxFromNeighbors)

10 (par

11 ;;if it arrives at an maximal point

12 (cond (<= (car maxFromNeighbors) maxTemp)

13 ;;then turn on LED and return the maxTemp to the base station

14 (seq (io 2)

15 (return migrate returnPath maxTemp ))

16 ;;else migrate to the highest temp. neighbor

17 (move (cons (io 0) returnPath)

18 (migrate

19 (cadr maxFromNeighbors) ; neighbor ’s launcher ID

20 (car maxFromNeighbors )))) ; neighbor ’s temp

21 (setcdr (msgq) nil))) ; reset msgq

22 ; find the max temp neighbor

23 (max (cdr (msgq)) (list 0 0)))))

2425 (rec (return migrate path temp)

26 (cond (equal path nil)

27 (print temp)

28 (return migrate (cdr path) (migrate (car path) temp ))))

Listing 2.17: ActorNet: An agent/actor looking for the highest temperature in theWSN

The searching actor is implemented by the move function (lines 4-23). To obtainthe temperatures in its surroundings, it evaluates measure on its neighboringnodes and waits ten seconds to process the results (lines 6-8). The measure

function sends the measured temperature, obtained through (io 1), and theid of the node’s launcher actor, obtained through (io 0) back to the searchingactor, whose address was passed to the measure function using (id) (line 7).After ten seconds, the searching actor iterates over its message queue to obtainthe message from the neighboring node that answered the highest temperature(lines 22-23). It then verifies whether this temperature is higher than its cur-rently found maximum temperature (lines 11-20). If it is, the searching actormigrates to this neighbor to continue its search for even higher temperatures(lines 17-20). On the other hand, when none of its neighboring nodes answereda higher temperature than the current maximum, the searching actor is on thenode with the highest temperature, turns on the LED using (io 2), and returnsthe found maximum temperature to the base station (lines 14-15). To this end,it employs the return function (lines 25-28) to migrate back to the base stationby following the path that was stored on its search (line 17) back, until the basestation is reached and the temperature can be printed (line 27). Note that thepar primitive is used on line 10 to reset the message queue (line 21) in parallelwith the processing of the message from the highest neighbor.

2.2.3.3 Models for Heterogeneous Applications

In applications that exhibit logical heterogeneity, various nodes need to behavedifferently. A typical example is an application where sensor nodes need tocollect sensor data and actuator nodes need to process this data in order to

Page 38: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

CHAPTER 2. STATE OF THE ART 26

control their actuators. One network-centric programming model that supportsthe development of these applications is ATaG [35, 36].

Abstract Task Graph (ATaG) is a framework providing a mixed declarative-imperative programming paradigm for developing WSN applications from amacroscopic viewpoint. The main abstractions offered are abstract tasks, ab-stract data items and abstract channels. Tasks represent an application’s pro-cessing and can produce or consume data items. Channels, on the other hand,represent the interactions among tasks. They connect data items to the tasksthat produce and consume them. While tasks, data items, and channels haveto be declared declaratively (i.e., graphically in a task graph), tasks have to beimplemented in an imperative language. Therein, the programmer can use twoprimitives: getData() to consume a data item, and putData() to produce adata item. Based on the channel declarations, ATaG’s runtime will move thesedata items between producers and consumers. Finally, given the concrete in-formation of the target network, the ATaG compiler can be used to transforman ATaG program into architecture-specific node-level behaviors and decide ontheir deployment to nodes.

To illustrate this programming model, we can consider a simple applica-tion in which temperature sensors periodically take readings to be processed byseveral cluster-heads, each deployed in a particular region. Figure 2.1, takenfrom [1], depicts the task graph for the corresponding ATaG program. In thisgraph, tasks are represented by ellipses, data items are represented by rectan-gles, and channels are represented by arrows. As expressed by the channels,32 · L. Mottola and G.P. Picco

Fig. 24. A cluster-based data collection program in ATaG.

the rules involved. Optimization goals can also be set at compile-time, e.g., tominimize code size as opposed to data size. Communication is handled using theActive Message stack described in Section 5.1.1.

5.6.3 Hybrid: Abstract Task Graph (ATaG).

Overview. ATaG is a programming framework providing a mixed declarative-imperative approach. The notions of abstract task and abstract data item are atthe core of the programming model. A task is a logical entity encapsulating theprocessing of one or more data items, which represent the information. Differentcopies of the same task may run on different nodes. The flow of information betweentasks is specified declaratively with abstract channels connecting a data item to thetasks that produce or consume it.

The code in a task is written in an imperative language, and relies on a shareddata pool for local communication, allowing tasks to output data or to be no-tified when some data of interest becomes available. To support the former, aputData(DataItem) operation is made available. As for the latter, programmersare provided with a task template that lists an empty handleDataItem() functionfor each incoming channel. ATaG helps programmers in expressing multi-stage,data-centric processing. It is therefore suited to sense-and-react applications, wherethe application typically requires complex operations to decide on the actions totake.

Example. Figure 24 illustrates a sample ATaG program, adapted from [Pathaket al. 2007], specifying a cluster-based data gathering application. Sensors within acluster take periodic temperature readings collected by the corresponding cluster-head. The former behavior is encoded in the Sampler task, while the latter isspecified in Cluster-Head. The Temperature data item is connected to both tasksusing a channel originating from Sampler, and a channel directed to Cluster-Head.

Tasks are annotated with firing and instantiation rules. The former specifywhen the processing in a task must be triggered. In our example, the Sam-pler task is triggered every 10 seconds according to the periodic rule. TheCluster-Head fires whenever at least one data item is available on any of its in-coming channels, according to the any-data firing rule. Tasks run on the indi-

ACM Journal Name, Vol. V, No. N, Month 20YY.

Figure 2.1: ATaG: Cluster-based data processing - task graph

the Sampler tasks produce Temperature data items, which are consumed by aCluster-Head task. Note that both tasks and channels are annotated. Theseannotations are shown in colored squashed rectangles. A task’s annotation hastwo rules: an instantiation rule deciding the task’s instantiation to nodes, anda firing rule deciding when the task will be executed. For instance, the Samplertask is declared to be instantiated on every node in the network (i.e., throughnodes-per-instance:1), while the Cluster-Head is declared to be instantiatedonce every 10 square meters (i.e., through area-per-instance:10sq.m). Inaddition, the Sampler task will be executed every 10 seconds, as specified bythe periodic firing rule, while the Cluster-Head will be executed whenever any

Page 39: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

CHAPTER 2. STATE OF THE ART 27

of the data items it consumes becomes available, as specified by the anydata

firing rule. If a task consumes multiple data items, the all-data firing rulecan also be used to specify that the task should be executed as soon as all ofthese data items are available. Channels are annotated to express the specificinterest of a task in a data item. For instance, the Temperature data itemsproduced by a Sampler task remain local to the node where it was produced,while the Cluster-Heads will gather these data items from the Sampler tasks intheir domain. Roughly speaking, a Cluster-Head ’s domain consists of all nodeshosting a Sampler task within 10 square meters around the Cluster-Head (i.e.,the domain is decided by the task’s area-per-instance instantiation rule).

Based on this task graph, the ATaG compiler will generate templates for thetasks that can be implemented by the programmer. For instance, the code forthe Sampler task, taken from [1], is shown in Listing 2.18. The template itselfcontained only the loop with the sleep instruction, based on the periodic firingrule. Similarly, the template for the Cluster-Head contains an event handler inwhich getData() can be used to consume the available data items. This eventhandler will be invoked when the Temperature data item consumed by the taskbecomes available.

1 // ...

2 while (TRUE) {

3 sleep (10000);

4 // Written by the programmer

5 int temperature = getTemperature ();

6 TemperatureDataItem t = newTemperatureDataItem(temperature );

7 putData(t);

8 }

9 // ...

Listing 2.18: ATaG: Cluster-based data processing - code for the Sampler task

Note that ATaG programs are highly extensible and reusable because thereis no direct task-to-task coupling. The ATaG framework allows users to buildlibraries of ATaG programs that can be reused to build larger applications.

2.2.3.4 Evaluation

Network-centric programming models allow WSN applications to be programmedin a centralized fashion, thereby allowing programmers to maintain a high-leveloverview of their application. In this section, we introduced several network-centric programming models categorized by their application domain. Given thefact that these solutions each provide the appropriate level of abstraction fortheir target applications, the growing interest in macroprogramming of sensornetworks [35] is well-founded. Next to facilitating WSN application develop-ment, these models also foster code reuse. Even ATaG, the model that targetsapplications exhibiting logical heterogeneity, allows tasks and interactions to bereused among various projects. It does, however, still require the programmerto deal with the complexities of event handlers.

2.3 Overview

The table in Figure 2.2 gives an overview of the state of the art for programmingWSNs, as presented in this chapter. While the first columns of this table present

Page 40: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

CHAPTER 2. STATE OF THE ART 28

the general properties of each solution, the remaining columns require additionalexplanation.

Communication. The column for communication presents the properties ofthe solutions’ features that support node interactions. It is only filled in if thesefeatures are visible to the programmer, otherwise the properties are presentedas non-applicable. The addressing property specifies how the nodes to interactwith have to be addressed, which can be either physical (e.g., by their MACaddress or distance in amount of hops) or logical. Through logical addressing,nodes are addressed by their application-level properties (e.g., all nodes collect-ing temperature measurements). Note that interactions have a certain scope.While some solutions allow a node to interact only with nodes in their one-hopneighborhood, others allow a node to interact with nodes anywhere in the net-work. The final communication property describes how a programmer has toprocess the data that was received from other nodes, for which several optionsare applicable:

• Single event handler: all received data has to be processed in a single eventhandler. Therein, the type of the received data has to be dispatched overto select the appropriate processing (i.e., received data has to be parsed).

• Blocking receive operation: a programmer has to anticipate the receptionof a particular data type by invoking a blocking receive operation. Typ-ically, multiple threads are required to receive various data types. Thealternative consists of manually parsing the received data.

• Single message queue: all received data is accessible through a single mes-sage queue and has to be parsed.

• Event handler per data type: for each possible data type that can bereceived, an individual event handler has to implement its processing.

• Variable access: all received data is accessible through logical variableswhose names specify the data type. Additionally, some solutions allowthe values for a particular logical variable to be aggregated using a reduceoperation.

• Declarative rules: rules can be used to specify the processing of one ormore received data types.

Note that the parsing of received data causes logic concerned with various nodeinteractions to be tangled, which is an issue in most programming models. Aswe will discuss in Chapter 3, our work (i.e., CrimeSPOT) addresses this issueby allowing the programmer to use declarative rules to specify the processingof received data.

Support for reuse. The final column of the table presents the means that areavailable to the programmer to reuse interaction- or application logic. While in-teraction logic consists of all code concerned with interactions with other nodes,application logic consists of all code concerned with the rest of the application(e.g., code for steering an actuator, or SQL-like code for extracting temperature

Page 41: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

CHAPTER 2. STATE OF THE ART 29

readings from the network). In both sub-columns, the general keyword repre-sents the typical means for code reuse in the solution’s programming paradigm(e.g., function declarations).

Note that only very few solutions introduce special means for reusing logicwithin or among applications. The only exceptions are FACTS, snLog andATaG. As we will discuss in Chapter 4, our work (i.e., Macro-CrimeSPOT)can also be added to this list of exceptions.

2.4 Conclusion

This chapter gave a non-exhaustive overview of the state of the art for program-ming wireless sensor networks. Several representative programming models wereintroduced for several application domains.

For traditional, sense-only applications, we discussed programming modelsfor raw data extraction, for programming queries, and for interpreted data ex-traction. These models introduce high-level abstractions that are well-suited forsense-only applications, yet too high-level for sense-and-react applications.

For sense-and-react applications (or so-called WSAN applications), a devel-oper requires more control over the individual nodes to steer their actuatorsand to implement in-network processing logic. In the context of these applica-tions, we discussed representative node-centric- and network-centric program-ming models.

Node-centric programming models allow individual WSN nodes to be pro-grammed. As these models only provide limited support for programming inter-actions among nodes, several solutions can be used to complement them. In thiscategory, we introduced solutions supporting message communication and datasharing. However, we had to conclude that these solutions typically don’t helpin processing data upon reception. One exception was FACTS, which allowsthe programmer to modularize node interactions using rules that can moreoverbe reused in several applications.

The discussed network-centric programming models allow WSNs to be pro-grammed as a whole while still offering control over the individual nodes. In thiscategory, we focussed on solutions supporting homogenous applications, mobilecode, and heterogenous applications. We believe that these models introduce theappropriate level of abstraction for programming sense-and-react applications,while also fostering code reuse.

Page 42: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

CHAPTER 2. STATE OF THE ART 30

!""#$%%&'(

)*+,

$

!"#$%"&"$'(&)"*&+,

-!"

#$%&

'#"

($!)*+,

-./0.102

,/34565718/9:;<=>41?/

*@

*$"

*$"

*$"

*$"

*$"

*@0

/;)*"

./0.102

,/34565718/9:;<=>41?/A:)B

C/65718

/+/.

D/..52/:E5..10

2EF

G.1354

*/7H@6?

;1024/:/8/07:F50I4/6

*@0

/*@0

/

.),/

)"00+-/$123

)4(J

#)DJ*

!./0.102

KL0371@

054

*@

*$"

*$"

*$"

*$"

*$"

#/0/

654

5-&3)6)3&37$%"

&"$'(&)"*&+,-

;JD"*

!)%:;!(J

"D;$,;

M"(

J./0.102

,/34565718/9:;<=>41?/

*@

*$"

*$"

*$"

*$"

*$"

*@0

/

8,7

39*3-&)+*$.),/)"0

0+-/

*J;%N!)*+&

;O./0.102:50I:6/53710

2)B

C/65718

/+/.

D/..52/:E5..10

2EF

G.1354

*/12FP@

6.;1024/:/8/07:F50I4/6

#/0/

654

#/0/

654

Q"R"

N;'*;E&!O

./0.102:50I:6/53710

2)B

C/65718

/+/.

D/..52/:E5..10

2EF

G.1354

*/12FP@

6.-4@3?102:6/

3/18/:@C

/6571@0

#/0/

654

#/0/

654

:266

,)&$;,)$8,7

3$5-&3)"*&+,-<

=&#)%"

=:*J)#S

-&(S

&&,;

:N*J;%O

./0.102:50I:6/53710

2,/

34565718/9:;C/

3154>CL6C@

./+/.

D/..52/:E5..10

2=@21354

*/7H@6?

;1024/:/8/07:F50I4/6

#/0/

654

#/0/

654

=&&%):NQ"R

"O./0.102:50I:6/53710

2)B

C/65718

/+/.

D/..52/:E5..10

2EF

G.1354

*/7H@6?

;1024/:/8/07:F50I4/6

#/0/

654

#/0/

654

"-;!("

%!:(J#

)&*;:N*J;%O

./0.102:50I:6/53710

2)B

C/65718

/+/.

,575:;F5610

2EF

G.1354

*/7H@6?

R5615

P4/:533/..A:"

226/2571@

0#/

0/654

#/0/

654

!JJ*

+=)D

J:N*J;%O

./0.102:50I:6/53710

2)B

C/65718

/+/.

,575:;F5610

2EF

G.1354

*/12FP@

6.;1024/:/8/07:F50I4/6

#/0/

654

#/0/

654

K"%!

;./0.102:50I:6/53710

2,/

34565718/9:(L4/>P5./I

+/.

,575:;F5610

2EF

G.1354

*/7H@6?

,/34565718/:6L4/.

(L4/>./7.

(L4/>./7.

!"#$

%&'(

)*+,-

.-/

0120324*52

6*7158932

4:1

8;57593<1=*#>

?17593<1

@10

:595*&A5

7324

'AB0385;

C19D

E7F

:18;57593<1*"G

;10

H12175;

H12175;

83&#,)=9*3-&)+*$.),/)"0

0+-/

T")(&;

./0.102:50I:6/53710

2)B

C/65718

/+/.

,575:;F5610

2EF

G.1354

*/12FP@

6.R5

615P4/:533/..

#/0/

654

#/0/

654

;*=&

#./0.102:50I:6/53710

2,/

34565718/9:(L4/>P5./I

+/.

,575:;F5610

2EF

G.1354

*/12FP@

6.,/

34565718/:6L4/.

*@0

/-L

147>10

:E6/I1357/.

;E"!

)"=R)JM;$;E"!

)"=:E(

&#(

"DD)*#

./0.102:50I:6/53710

2)B

C/65718

/A:D

@P14/:%@I

/+/.

*$"

*$"

*$"

*$"

*$"

#/0/

654

"%!&

(*J!

./0.102:50I:6/53710

2KL0371@

054A:D@P

14/:%@I

/+/.

D/..52/:E5..10

2EF

G.1354

*/12FP@

6.;1024/:B

/..52/:UL/

L/#/

0/654

#/0/

654

"!5#

./0.102:50I:6/53710

2,/

34565718/A:)B

C/65718

/+/.

,575:;F5610

2=@21354

*/7H@6?

J8/0

7:F50I4/6:C/6:I575:7GC/

!5.?:#65CF

.#/

0/654

$-!

"(I!"#$%&'(

)0120324*52

6*7158932

4:1

8;57593<1=*#>

?17593<1

@10

:595*&A5

7324

'AB0385;

C19D

E7F

:18;57593<1*"G

;10

$587E0=*#>

?E790#>

?E790

.C417./0:10:?@4@B

:8@@

6:0@I

/>3/07613:/0://0:8@@6:0/7H@6?>3/076139:*

">V:07:B

//6:0

@I12

)+-./&+

'0#1'

%2&//&'(341

/15+

22.'

&*1/&+'

).,,

+#/36+#3#$

.%$

7#&2

1#83!,

,-&*1/&+'34+

21&'

7#+(#122&'(371

#1"&(2

9+"

$:-$;$-3*+'

/#+-

08,$

7#+*$%%&'(3#$

*$&;$"

3"1/1

<'/=3>+(&*

!,,=3>+(&*

Figure 2.2: An overview of the covered State of the Art

Page 43: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

3Node-centric Programming with

CrimeSPOT

When programming wireless sensor network (WSN) applications from a node-level perspective using event-based WSN middleware, every sensor node hasto be individually programmed by specifying its interactions with other sensornodes. The nodes communicate exclusively via a decentralized event bus towhich they publish events and from which they receive the published events ofthe types they subscribed to. Hence, sensor nodes’ interactions often involvereacting to events published by other sensor nodes. However, the only meansto process received events and specify reactions are event handlers, which havealready been shown to violate several software engineering principles, includingcomposability, scalability and separation of concerns [12].

In this chapter, we introduce CrimeSPOT, a new domain-specific program-ming language for programming individual WSN nodes. This language consti-tutes a building block, to be used on top of event-based middleware for WSNs,that allows the programmer to use declarative interaction rules to specify theinteractions with other sensor nodes. This addresses the various problems thatusing an event handler for this purpose brings along. The programmer no longerhas to dispatch a received event to its appropriate reaction, nor is she required toimplement ad-hoc state management to keep track of which events have alreadybeen received and whether or not they are still valid.

After considering a representative running example and extracting program-ming support requirements, we will show how CrimeSPOT meets these require-ments by discussing its architecture and all of its features. Simultaneously, wewill incrementally implement the running example. To conclude this chapter, wewill revisit the running example and finalize its CrimeSPOT implementation.

While, up till now, we discussed the problem and our solution in the light ofplain event-based middleware, CrimeSPOT can also be used on top of event-based component middleware. Basically, a component encapsulates node-levelapplication logic, while component middleware allows multiple components to

31

Page 44: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

CHAPTER 3. NODE-CENTRIC PROGRAMMING WITH CRIMESPOT 32

run next to each other on the same sensor node. From this point on, we willassume the use of event-based component middleware on top of a Java platformand talk about components rather than sensor nodes when discussing node-levelapplication logic.

3.1 Running Example

To illustrate the need for programming support for building WSN applicationsusing event-based component middleware, this section introduces a representa-tive running example. In the next sections, we will introduce the CrimeSPOTlanguage while referring to this running example to explain the language fea-tures.

As a representative event-based WSN application1, we can consider a sys-tem that controls the heating and logs the comfort levels of festival tents. Suchan application requires several components, each performing their own specifictask. Sensor readings should be made available by temperature- and humiditysensor components, heaters should be controlled by heating controller compo-nents, and the application should be steered by a comfort level monitor com-ponent. Even though some of these components could be deployed on the sameWSN node, for simplicity, we assume that every component is deployed on adifferent node. A high-level overview of the application is depicted in Figure3.1.Within every tent, three components have to be deployed: the HeatingCon-troller, the TemperatureSensor and the HumiditySensor. Typically, these com-ponents are deployed only once within a tent, but for larger tents, multipleredundant components could also be deployed. The ComfortLevelMonitor com-ponent, on the other hand, is deployed only once and controls the entire system.In the figure, a component’s outgoing arrow indicates the events it publishes,while its incoming arrow indicates the events it subscribes to. The Temper-atureSensor and HumiditySensor components publish temperatureReading-and humidityReading events, respectively. The ComfortLevelMonitor, on theother hand, is subscribed to these events and uses them to compute and logthe comfort levels for each tent, and to decide how much the heating in eachtent should be adjusted. To control the heating, it publishes adjustHeating

events, to which the HeatingController components are subscribed. Whenevera HeatingController receives an adjustHeating event, it adjusts its associatedheater accordingly. Next to these basic events, the components deployed withina tent also publish an online event carrying their component type, tent iden-tifier (i.e., an identifier obtained by reading out a GPS sensor), component IDand MAC address. The ComfortLevelMonitor subscribes to these events as itshould know which components are deployed in which tents to process theirevents2 and to send the adjustHeating event to the HeatingControllers in theappropriate tent. In addition, publishing these events allows the componentsto be arbitrarily moved on the festival terrain. For instance, when a Heating-Controller component is moved to another tent, the ComfortLevelMonitor willknow about its new location and will therefore no longer send it adjustHeating

1i.e., a WSN application that uses event-based component middleware.2It is assumed that every event contains its originating component’s MAC address and com-

ponent ID. This way, any event can be related with an online event to obtain the originatingtent.

Page 45: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

CHAPTER 3. NODE-CENTRIC PROGRAMMING WITH CRIMESPOT 33

Tent CTent B

Tent A

Component:ComfortLevelMonitor

Component: TemperatureSensor

Component: HeatingController

Component: HumiditySensor

adjustHeating

temperatureReading

humidityReading

Decentralized Event Bus

temperatureReading

adjustHeating

humidityReading

online

online

online

online

Figure 3.1: Overview of a Wireless Sensor Network application that controls theheating and logs the comfort levels of festival tents

events for the old tent. As shown in the figure, all the events are routed throughthe decentralized event bus offered by the event-based component middleware.

The functional requirements for this application are listed in Table 3.1.While functional requirements 1, 2, 3, and 5 are not that difficult to imple-ment, the other requirements would clearly require to implement ad-hoc timers,state management and event-matching. For instance, to avoid that a heaterkeeps heating when the ComfortLevelMonitor fails or gets disconnected fromthe WSN (i.e., F.R.4), the HeatingController has to reset its associated heaterif no adjustHeating event has been received for a certain amount of time.Functional requirements 6 and 7, on the other hand, require that events arestored in memory upon reception, and that they can later be consulted andrelated with other events. In addition, functional requirement 6 requires thatevents can be send to specific components, rather than being broadcasted to allsubscribers. Finally, functional requirement 8 requires that previously storedevents can be removed from memory when new events have been received.

Clearly, programming this application requires the programmer to deal witha fair amount of accidental complexity, which is inherent to using event-basedWSN middleware. Therefore, the CrimeSPOT language is explicitly designedto deal with this accidental complexity and to allow the programmer to focus

Page 46: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

CHAPTER 3. NODE-CENTRIC PROGRAMMING WITH CRIMESPOT 34

DescriptionF.R.1 The HumiditySensor and TemperatureSensor have to publish

their sensor readings at set intervals.F.R.2 The HumiditySensor, TemperatureSensor and HeatingController

have to publish their online presence and location at set intervals.F.R.3 The HeatingController has to adjust its associated heater accord-

ing to a received adjustHeating event.F.R.4 The HeatingController has to make sure that its associated heater

won’t keep heating when the ComfortLevelMonitor fails or getsdisconnected from the WSN.

F.R.5 The ComfortLevelMonitor has to compute a tent’s heating levelbased on a received temperatureReading event and publish thislevel in an adjustHeating event.

F.R.6 The ComfortLevelMonitor has to control the heating for each tentindividually by sending adjustHeating events only to the Heat-ingControllers in the tent to be heated.

F.R.7 The ComfortLevelMonitor has to relate receivedhumidityReading and temperatureReading events thatoriginate from the same tent and use them to compute and logthat tent’s comfort level.

F.R.8 The ComfortLevelMonitor has to make sure that only the mostrecent sensor readings from a certain tent are used for computingthe heating- and comfort levels.

Table 3.1: Functional requirements for a WSN application that controls the heatingand logs the comfort levels of festival tents

on the application’s essential complexity.

3.1.1 Programming Support Requirements

Because the running example is a representative event-based WSN application,we used its functional requirements to extract the requirements for a program-ming support solution that deals with the aforementioned accidental complexity.We categorized the results in state management- and component interaction re-quirements, which are listed in Table 3.2 and 3.3, respectively. Note that there’sa clear separation between component interaction (i.e., publishing events) andinvoking general application logic.

Every requirement enables one or more functional requirements of the run-ning example. While most requirements are an obvious generalization of therunning example’s requirements, S.R.2 and S.R.3 are not. These requirementsallow events to expire after a certain amount of time and allow programmersto react to such expirations. However, any solution meeting these requirementsprovides an elegant way for dealing with functional requirements such as F.R.4,which require timeouts. Later, we will further motivate the need for storedevents to expire.

It must be noted that these programming support requirements also provethe representativeness of our running example. Analysis showed that variousother WSN applications found in literature (cfr. Section 5.1) can be imple-

Page 47: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

CHAPTER 3. NODE-CENTRIC PROGRAMMING WITH CRIMESPOT 35

Description EnablesS.R.1 A component has to be able to store received events in its

memory.F.R.4F.R.6F.R.7

S.R.2 Events have to be able to expire after a certain amount oftime, after which they are removed from the component’smemory.

F.R.4

S.R.3 A component has to be able to react to the expiration of anevent.

F.R.4

S.R.4 A component has to be able to consult previously receivedevents.

F.R.6F.R.7

S.R.5 A component has to be able to relate events by comparingtheir payloads.

F.R.6F.R.7

S.R.6 A component has to be able to react to the reception of anevent by removing older events from its memory.

F.R.8

Table 3.2: Programming Support Requirements concerning State Management

Description EnablesI.R.1 A component has to be able to invoke application logic at

set intervals and to publish the results in events.F.R.1F.R.2

I.R.2 A component has to be able to react to the reception of anevent by invoking application logic.

F.R.3F.R.7

I.R.3 A component has to be able to react to the reception of anevent by performing a computation and publishing its resultin an event.

F.R.5

I.R.4 A component has to be able to publish events to specificcomponents.

F.R.6

Table 3.3: Programming Support Requirements concerning Component Interactions

mented with a solution meeting these requirements. In the remaining part ofthis chapter, we will show how our solution, dubbed CrimeSPOT, meets allidentified programming support requirements.

3.2 CrimeSPOT in a Nutshell

CrimeSPOT is a declarative, rule-based language to be used on top of event-based component middleware for wireless sensor networks. It provides program-ming support for building event-based WSN applications and is founded on thenotions of facts and interaction rules.

To meet the state management requirements identified earlier, CrimeSPOTreifies received events as facts and stores them in a Fact Base. In general, factscan be added to the Fact Base (i.e., asserted), removed from the Fact Base (i.e.,retracted), and they can expire. When a fact expires, the CrimeSPOT runtimewill retract it from the Fact Base. In addition, a fact can also be published, whichcorresponds to the publication of an event. For a proper conversion betweenevents and facts, the CrimeSPOT runtime can be configured in a declarative

Page 48: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

CHAPTER 3. NODE-CENTRIC PROGRAMMING WITH CRIMESPOT 36

way by adding event-to-fact mappings.The interaction rules mainly support the interaction requirements. They can

be used to specify, in a declarative manner, how a component should react whenit receives a particular event or several related events. Within the conditions(or body) of an interaction rule, one can specify the events to react upon byspecifying their reifying facts, while, in its head, one can specify the reaction(e.g., publishing a fact or invoking application logic). Additionally, interactionrules can also be used to specify that a component should publish a particularfact at certain intervals. For every component interaction, an interaction ruleshould be added to the CrimeSPOT runtime.

3.3 Architectural Overview

To give an idea of how CrimeSPOT is used, Figure 3.2 depicts the physicalview on a WSN node running event-based component middleware. Note that the

ComponentCrimeSPOT

Event-based Component Middleware

WSN Node

ComponentCrimeSPOT

Component

Figure 3.2: Physical view on a Wireless Sensor Network node running event-basedcomponent middleware

CrimeSPOT runtime is part of an event-based component and doesn’t precludesuch a component to interact with the underlying middleware. This is essentialbecause CrimeSPOT is a building block for event-based components. Conse-quentially, CrimeSPOT components (i.e., components using CrimeSPOT) canrun next to regular components without any problems.

3.3.1 CrimeSPOT Runtime

An architectural overview of the three-layered CrimeSPOT runtime is depictedin Figure 3.3.

The infrastructure layer binds the CrimeSPOT runtime to the underlyingmiddleware. To this end, a middleware-specific implementation for the Middle-ware Bridge should be provided which transfers the events received from theevent-based middleware to the Reification Engine. In addition, the Middle-ware Bridge should also implement all required middleware-specific function-ality, which will be invoked by the Reification Engine (e.g., functionality toconstruct and publish an event). Clearly, the Middleware Bridge can be config-ured for any underlying event-based middleware.

The reification layer takes care of reifying events as facts upon reception(i.e., to be asserted in or retracted from the Fact Base), and reifying facts asevents (i.e., to be published through the underlying middleware). To this end,the Reification Engine will use the event-fact mappings from its Configura-tion Base. As we will explain later, the Configuration Base can also contain

Page 49: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

CHAPTER 3. NODE-CENTRIC PROGRAMMING WITH CRIMESPOT 37

CrimeSPOT

Reification Layer

Inference Layer

FactBase

Inference Engine

RuleBase

Middleware Bridge

Infrastructure Layer

Reification Engine

ConfigurationBase

Middleware Bridge

Figure 3.3: Architectural overview of the CrimeSPOT runtime

meta-facts, which further influence the Reification Engine’s behavior. Event-fact mappings and meta-facts are application-specific and can be arbitrarilyadded to the CrimeSPOT runtime by a component. The cooperation of theMiddleware Bridge and the Reification Engine is further illustrated in Figure3.4. On the left-hand side, a fact is published and therefore reified as an event

ComponentCrimeSPOT

Decentralized Event Bus

Middleware Bridge

FactBase

Event

Event

Fact

ComponentCrimeSPOT

Middleware Bridge

FactBase

Event

Event

Fact

Config.Base

Config.Base

Reification Engine

Reification Engine

ComponentCrimeSPOT

Middleware Bridge

FactBase

Event

Fact

Config.Base

Reification Engine

Event

Figure 3.4: Fact publication and Event reification

by the Reification Engine and published to the event bus by the the MiddlewareBridge. On the right-hand side, an event is received from the event bus andtherefore transferred to the Reification Engine by the Middleware Bridge andreified as a fact and asserted in the Fact Base by the Reification Engine.

Next to the Fact Base, the inference layer of the CrimeSPOT runtime alsocontains the Rule Base, which stores the component’s interaction rules. Byevaluating the Rule Base against the Fact Base whenever the Fact Base is up-dated, the Inference Engine will activate the interaction rules as soon as their

Page 50: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

CHAPTER 3. NODE-CENTRIC PROGRAMMING WITH CRIMESPOT 38

conditions are met. Furthermore, because CrimeSPOT is a truth maintenancesystem, the Inference Engine will also deactivate the interaction rules as soon astheir conditions are no longer met. The activation of an interaction rule corre-sponds to the invocation of its reaction (e.g., invoking application logic), whileits deactivation corresponds to undoing its reaction (e.g., invoking compensatingapplication logic).

3.3.2 Interacting with the CrimeSPOT Runtime

Figure 3.5 depicts the logical view on the possible interactions with the CrimeSPOTruntime. The interface of the CrimeSPOT runtime is simple. While all textual

Component CrimeSPOT

processExpression(String)

registerRule(String,Action)

Figure 3.5: Logical view on the possible interactions with the CrimeSPOT runtime

expressions (e.g., facts, plain rules, etc.) can be added to the system throughthe processExpression(String) method, interaction rules invoking applica-tion logic can be added through the registerRule(String,Action) method.

3.3.3 Network View on Component Interactions

Interactions among CrimeSPOT components To illustrate the interac-tions between CrimeSPOT components, Figure 3.6 depicts a network-levelview on two interacting CrimeSPOT components that don’t have any event-fact mappings in their Configuration Base. The absence of these mappings isthe default situation and therefore does not preclude two CrimeSPOT com-ponents to communicate. When a CrimeSPOT component publishes a factthat’s not mapped to a particular event, the CrimeSPOT runtime will encodethis fact in a CrimeSPOT event to which all CrimeSPOT components aresubscribed. In the Figure, the component on the left-hand side publishes a fact

Decentralized Event Bus

CS Event

ComponentCrimeSPOT

C.B.{ }

ComponentCrimeSPOT

C.B.{ }

CS Event

Figure 3.6: Two CrimeSPOT components exchanging CrimeSPOT events

that is reified as a CrimeSPOT event, published to the event bus and receivedby the component on the right-hand side. The receiving component will reifythe CrimeSPOT event as the corresponding fact and assert it in its Fact Base.

Page 51: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

CHAPTER 3. NODE-CENTRIC PROGRAMMING WITH CRIMESPOT 39

Interactions with regular components As shown above, all CrimeSPOTcomponents can interact in the absence of event-fact mappings. However, tointeract with regular components, a CrimeSPOT component should add therequired event-fact mappings to the CrimeSPOT runtime. The reason for thisrequirement is that regular components exchange events with a particular typeand payload whose structure is agreed upon3. The purpose of an event-factmapping is to map the structure of an event to the structure of a fact to allowproper reification. It will be used to reify received events as facts to be stored,and to reify facts as events to be published. For instance, if an event-fact map-ping for temperature events is present in the Configuration Base, CrimeSPOTcomponents can freely exchange these events with regular components. This isdepicted in Figure 3.7, which shows the interactions between two CrimeSPOTcomponents and a regular component. The CrimeSPOT component on theleft-hand side publishes a temperature fact, which is reified as a temperatureevent and published to all components subscribing to this event. Conversely, asshown on the right-hand side, the CrimeSPOT components will use the samemapping to reify received temperature events as facts. As we will explain in Sec-

Decentralized Event Bus

temp

ComponentCrimeSPOT Component

temp

C.B.{temp mapping}

ComponentCrimeSPOT

temp

C.B.{temp mapping}

Figure 3.7: Event-based components exchanging temp events

tion 3.6.2, a component should add an event-fact mapping to the CrimeSPOTruntime for every event it subscribes to, and every event it plans to publish toregular components.

3.4 Inference Engine

The CrimeSPOT interaction rules have to be activated as soon as their condi-tions are met (i.e., as soon as the required events have been received, reified asfacts and asserted in the Fact Base) and deactivated as soon as their conditionsare no longer met (i.e., as soon as the required facts were retracted from theFact Base). Consequentially, the Inference Engine has to re-evaluate all ruleswhenever the Fact Base is updated.

To obtain this functionality, the CrimeSPOT Inference Engine uses a for-ward chaining inference strategy. Forward chaining is a data-driven strategywhich derives all valid conclusions given a fact- and a rule base. Note that thederivation of conclusions corresponds to the triggering of the interaction rules’reactions in the CrimeSPOT setting.

3As as example, one can consider an event with the temperature type and a payloadcontaining one integer that represents the measured temperature in degrees Celsius.

Page 52: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

CHAPTER 3. NODE-CENTRIC PROGRAMMING WITH CRIMESPOT 40

As we will further explain in Appendix A, our forward chaining InferenceEngine is based on the Rete algorithm [37], which allows efficient forwardchaining. This is essential in the setting of wireless sensor networks, becauseWSN nodes only have low processing power available. The Rete algorithmcaches its proofs and whenever the Fact Base is updated, it uses the updateitself (e.g., the assertion of a fact) to derive only the new conclusions ratherthan attempting to derive all valid conclusions from scratch. This significantlyreduces the performance overhead of Fact Base updates.

The original Rete algorithm was extended with various domain-specific fea-tures. For instance, the Inference Engine can be triggered at specific intervalsand facts can expire after a certain amount of time, after which the InferenceEngine will retract them from the Fact Base. In general, our Inference Engineis triggered:

• when a fact is asserted in the Fact Base,

• when a fact is retracted from the Fact Base (e.g., upon its expiration),

• and at specific intervals, specified by the programmer.

3.5 Grammar

The CrimeSPOT BNF grammar is depicted in Figure 3.8. We extended theBackus Naur Form notation with large square brackets to depict optional itemsand large parenthesis suffixed with an asterisk to depict zero or more repetitions.As mentioned earlier, every valid expression can be added to the CrimeSPOTruntime through the processExpression(String) method. In the followingsections, we will introduce all language features shown in the grammar.

3.6 Facts

Our approach is founded on the notion of a fact rather than an event. Eventhough both notions look similar, they are significantly different from a seman-tic point of view [38]. While events are transient, typically only valid at thetime of reception, facts are persistent (i.e., asserted in a Fact Base) and thusremain valid until they are explicitly removed. To blend both notions, we allowassociating an expiration time with a fact.

Every fact has a type and optional attributes (i.e., name-value pairs, sep-arated by the = symbol). Additionally, a fact can also carry meta-attributesrepresenting its meta-data. A fixed number of meta-attributes can be added toa fact by listing them after the @ symbol. An example is depicted in Listing 3.1.

1 temperatureReading(Celsius = 27,

2 Fahrenheit = 81)@[factExpires(Seconds =600)].

Listing 3.1: A temperatureReading fact

The fact represents a temperature reading of 27 degrees Celsius or 81 degreesFahrenheit, which remains valid for ten minutes. When adding this fact to theCrimeSPOT runtime, it will be asserted in the Fact Base and the InferenceEngine will read the factExpires meta-attribute and consequentially retractthe fact after ten minutes.

Page 53: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

CHAPTER 3. NODE-CENTRIC PROGRAMMING WITH CRIMESPOT 41

3.6.1 Controlling a Fact’s Scope

Next to the factExpires meta-attribute, a fact can also carry the to meta-attribute, which can be used to publish the fact to a given destination andthereby control its scope. Within this meta-attribute, the fact’s destinationshould be specified by providing values for the ID- and/or the MAC attribute,which refer to the destination component’s ID and sensor node MAC address,respectively. To broadcast a fact to all sensor nodes, or to all componentsrunning on a particular sensor node, the any keyword can be used as a value forthe MAC - or ID attribute, respectively. Listing 3.2 illustrates the use of the to

meta-attribute.

1 temperatureReading(Celsius = 27)@[to(MAC=any)],

2 factExpires(Seconds =600)].

3 temperatureReading(Celsius = 27)@[to(MAC="1234:1234:1234:1234",ID=3)],

4 factExpires(Seconds =600)].

Listing 3.2: Publishing a temperatureReading fact

When adding these facts to the CrimeSPOT runtime, they will be asserted inthe Fact Base and the fact on line 1 will be broadcasted to all CrimeSPOT com-ponents, while the fact on line 3 will be send only to the specifically addressedcomponent. If the underlying middleware allows directed event publications,the Middleware Bridge can consult the values from the to meta-attribute toemploy this feature. If not, it can consult these values upon event reception andmisaddressed events can be dropped. As discussed earlier, every componentthat receives a fact will assert it in its Fact Base. Additionally, the component’sInference Engine will also read the factExpires meta-attribute, if present, todeal with its expiration.

3.6.2 Mapping Events to Facts

As shown above, a fact is self-explaining. It has a particular type and all of itsattributes are named. An event, on the other hand, is not. Next to its type,it has a particular payload whose structure is agreed upon by the componentsexchanging the event. The payload consists of one or more numbered values(e.g., integers or strings), but only the components exchanging the event knowthe semantics of each value. For instance, components can exchange an event oftype 101 with a payload containing two integers and agree that this event rep-resents a temperature reading measured in degrees Celsius (i.e., the first value)and Fahrenheit (i.e., the second value), which remains valid for ten minutes. Toreify such events as facts and add them to the Fact Base, the structure agree-ment should be made explicit by the programmer. This can be done by addingevent-fact mappings to the CrimeSPOT runtime.

To map the aforementioned temperature event to a temperatureReading

fact with Celsius and Fahrenheit attributes, the programmer can use themapping depicted in Listing 3.3.

1 mapping temperatureReading(Fahrenheit =?tempf ,

2 Celsius =?tempc)@[factExpires(Seconds =600)]

3 <=> Event_101(Integer =?tempc , Integer =?tempf ).

Listing 3.3: Mapping a temperature event to a temperatureReading fact

Page 54: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

CHAPTER 3. NODE-CENTRIC PROGRAMMING WITH CRIMESPOT 42

A mapping starts with the mapping keyword, followed by the reifying fact anda description of the event which are separated by the <=> symbol. The eventdescription, on the right-hand side of the <=>, resembles the fact notation. Ithas a type and one or more fields, which are comparable to attributes but havea type rather than a name. Every field represents a value from the payload:its type represents the value’s type and its position in the event descriptionrepresents the value’s position in the payload. The corresponding values of thefact’s attributes and the event’s fields are related by using identical variables inthe mapping (e.g ?tempc and ?tempf in the example). Note that, unlike thefields of an event, the attributes of a fact are not ordered, but uniquely identifiedby their name.

After adding event-fact mappings to the CrimeSPOT runtime, they will bestored in the Configuration Base and used by the Reification Engine when pro-cessing incoming events (i.e., to reify them as the corresponding fact) and whenpublishing facts (i.e., to reify them as the corresponding event). In addition,the Middleware Bridge can subscribe the component to the mapped event typeas soon as the mapping is added. As a result, mappings allow a CrimeSPOTcomponent to communicate freely with regular components.

3.6.2.1 Event Meta-Data

Next to a payload, most event-based component middleware also associate meta-data with an event. For instance, an event can carry, in addition to its payload,its originating component’s ID and sensor node MAC address. To avoid losingthis data upon event reification, CrimeSPOT also incorporates it in its factsusing the meta-attributes. For every event meta-datum, the Middleware Bridgecan add a meta-attribute to the fact reifying the event. In general, it is as-sumed that a from(ID=..,MAC=..) meta-attribute specifying the fact’s originis present for every fact in the Fact Base.

Decentralized Event Bus

ComponentCrimeSPOT

temperatureReading(Celsius=27, Fahrenheit=81)@[from(MAC="M", ID=3), factExpires(Seconds=600)]

Event 101 from M/3{27,81}

Fact Base

Figure 3.9: Illustrating the temperature event mapping

Figure 3.9 further illustrates the meaning of the mapping in Listing 3.3.When read from top to bottom, the Figure shows how the temperatureReadingfact is reified as an event upon its publication, and conversely, when read frombottom to top, the Figure shows how the temperature reading event is reifiedas a temperatureReading fact upon its reception.

Page 55: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

CHAPTER 3. NODE-CENTRIC PROGRAMMING WITH CRIMESPOT 43

3.7 Interaction Rules

As mentioned before, interaction rules have to be used for specifying a com-ponent’s interactions. An interaction rule consists of a body containing one ormore conditions, and a head containing either a fact or an action (i.e., a Javaobject encapsulating application logic). The head and the body are separatedby the arrow <- symbol.

�expression� ::= �expr�.�expr� ::= �mapping�

| �meta-fact�| �fact� | �rule�

�mapping� ::= mapping �fact� <=> �event��meta-fact� ::= �subsumption� | �drop��subsumption� ::= subsumes!(Incoming=�fact�,Fact=�fact� [ ,When=[�body�] ] )

�drop� ::= drop!(Incoming=�fact� [ ,When=[�body�] ] )

�fact� ::= �type�( [ �attribute� (, �attribute�)* ] ) [ @[ �meta-attributes� ] ]

�attribute� ::= �name� �relop� ( �value� | �variable� )

�meta-attributes� ::= �meta-attribute� (, �meta-attribute�)*�meta-attribute� ::= �assert-meta-attribute�

| �condition-meta-attribute��event� ::= �type�(�field� (, �field�)*)�field� ::= �type� = �variable��rule� ::= �fact� <- �body��body� ::= �condition� (, �condition�)*�condition� ::= �fact�

| �extralogical condition��value� ::= �number� | �quoted text� | �symbol� | �list��list� ::= [ [ (�value� | �variable�) (, (�value� | �variable�))* ] ]

�quoted text� ::= "�text�"�symbol� ::= ‘�text��type� ::= �text��name� ::= �text��variable� ::= ?�name��relop� ::= = | != | <= | >= | < | >

�assert-meta-attribute� ::= to(MAC=(�quoted text� | any))| to(ID=(�number� | any))| factExpires(Seconds=�number�)

�condition-meta-attribute� ::= from(MAC=(�quoted text� | �variable� | this.MAC))| from(ID=(�number� | �variable� | this.ID))| matchExpires(Seconds=�number�)| matchEvery(Seconds=�number�)

�extralogical condition� ::= (�value� | �variable�) is �methodinvocation�| findall(�variable�,[�body�],�variable�)| length(�list�,(�value� | �variable�))| not �fact�| �variable� �relop� (�value� | �variable�)

�methodinvocation� ::= �name�( [ �argument� (, �argument�)* ] ) [ @[�option�] ]

�argument� ::= �value� | (�typecast�)�variable��typecast� ::= Number | Fraction | Text | Symbol | List�option� = evalEvery(Seconds=�number�)

| renewEvery(Seconds=�number�)

Figure 3.10: Syntax for an interaction rule with a fact in its head

As we will extensively explain in the following sections, a condition can beeither logical or extra-logical. A logical condition specifies a fact and obtainsa match for every matching fact in the Fact Base. An extra-logical condition,on the other hand, uses a built-in operator to obtain matches. As soon as allconditions in the body of a rule have a match, the rule itself has a match and willbe activated for this match by the Inference Engine. Depending on the rule’shead, its activation results in either asserting a fact in the Fact Base, which canoptionally be published, or invoking an action’s application logic.

Every time the Fact Base is updated (e.g., when a new event is receivedfrom the event bus or when a fact expires), all rules are re-evaluated againstthe Fact Base (i.e., conceptually). Rules of which a single condition did not yethave a match, can obtain a match upon the next evaluation against the FactBase. Conversely, a rule can also lose a match if one of its conditions lost amatch. As soon as a rule loses a match, the Inference Engine will deactivate itfor this match. Depending on the rule’s head, its deactivation results in eitherretracting a fact from the Fact Base, or invoking an action’s application logic.

The above can be summarized by the invariant that, at any time, an inter-action rule is activated for each of its matches. As an example, consider the rulein Listing 3.4, which asserts a temperature fact for every temperatureReading

fact in the Fact Base.

1 temperature(Celsius =?temp)

2 <- temperatureReading(Celsius =?temp).

Listing 3.4: An interaction rule for copying temperatureReading facts to tempera-ture facts

If the Fact Base contains three matching temperatureReading facts (e.g., with?temp 20, 20 and 24), this rule is activated three times with a correspondingbinding for ?temp and the three corresponding temperature facts will conse-quentially be present in the Fact Base. As soon as a new temperatureReading

fact is asserted in the Fact Base, the rule obtains a new match and hence, itwill be activated for this match and the corresponding temperature fact willbe asserted. Conversely, as soon as one of the temperatureReading facts isretracted from the Fact Base, one of the rule’s matches is lost and hence, the

Page 56: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

CHAPTER 3. NODE-CENTRIC PROGRAMMING WITH CRIMESPOT 44

rule will be deactivated for that match and the corresponding temperature factwill be retracted.

More details concerning the interaction rules’ behavior will be given in Sec-tion 3.7.2. In the next section, we will first elaborate on the conditions that canbe used in an interaction rule’s body.

3.7.1 Conditions

Typically, a condition is used for matching facts from the Fact Base. To this end,one can employ a logical condition which specifies the facts to be matched. Forinstance, if a component should react to the reception of a temperature reading,one of the following conditions can be used in the body of its interaction rule:

1 temperatureReading(Fahrenheit =?temp)

2 temperatureReading(Celsius =?temp)

3 temperatureReading(Celsius =40)

4 temperatureReading(Celsius <40)

Since the first two conditions employ a variable for the measured tempera-ture, the measured value is not constrained. Any temperatureReading witha Fahrenheit attribute will provide a match for the first condition, while anytemperatureReading with a Celsius attribute will provide a match for the sec-ond condition. The third condition is further constrained as it will only bematched when the received temperature reading is 40 degrees Celsius. Thefourth condition employs the < operator and hence will only be matched whenthe received temperature reading is less than 40 degrees Celsius.

Note that it suffices to only specify the attributes required to do the matchingwithin a logical condition. A temperatureReading fact with both Celsius andFahrenheit attributes can also match the previous conditions.

3.7.1.1 Incorporating Meta-Data

As mentioned earlier, every fact carries meta-attributes next to its regular at-tributes. For all event meta-data made available by the underlying event-basedmiddleware, such meta-attributes can be added to the facts reifying the events.To incorporate this meta-data in the interaction rules, the meta-attributes canalso be matched in a condition. For instance, if a component should react tothe reception of a temperature request, the following condition can be used inthe body of its interaction rule:

1 getTemperature ()@[from(MAC=?mac , ID=?id)]

For every match, the variables ?id and ?mac will be bound to the requestingcomponent’s ID and sensor node MAC address, respectively. Since all variablesbound in the body of an interaction rule are available in its head, these variables’values can be used in this example to answer the request by publishing thecurrent temperature to the requesting component.

The this.MAC or this.ID keyword can be used as a value for the MACor ID attribute within the from meta-attribute. While the this.ID keywordsubstitutes for the current component’s ID, the this.MAC keyword substitutesfor the current sensor node’s MAC address. For instance, in the context of ourrunning example, a component that publishes online facts can use the followingcondition to match the online fact that it has published before. A match forthis condition will bind ?tent to the identifier of the current tent.

Page 57: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

CHAPTER 3. NODE-CENTRIC PROGRAMMING WITH CRIMESPOT 45

1 online(Tent=?tent)@[from(MAC=this.MAC , ID=this.ID)]

3.7.1.2 Relating Facts

Wireless sensor network nodes often have to react to the occurrence of relatedevents. For instance, as the ComfortLevelMonitor from the running exampleshould log the comfort levels in each tent, it should relate humidity- and tem-perature readings which originate from the same tent to compute the associatedcomfort level and do the logging. For this purpose, several conditions in an in-teraction rule’s body can be related by using identical variables. Because, withina rule’ match, a variable can be bound to only one value, all occurrences of thesame variable have to be consistent. This behavior is also called unification. Asan example, we can consider the ComfortLevelMonitor component’s interactionrules for logging the comfort levels. These interaction rules relate facts basedon their publisher and based on their contents.

Publisher-based relations As mentioned before, the meta-attributes of afact can be matched within a logical condition. Consequentially, two pre-processing interaction rules can be added to the ComfortLevelMonitor to re-late the received sensor readings with their originating tent. The followingrule relates humidityReading facts with online facts and stores the result inhumidityInTent facts.

1 humidityInTent(Percent =?humid , Tent=?tent)

2 <- humidityReading(Percent = ?humid)@[from(MAC=?hMac , ID=?hId)],

3 online(Tent = ?tent)@[from(MAC = ?hMac , ID = ?hId)].

Listing 3.5: Relating humidity readings with online facts

The body of an interaction rule specifies a conjunction and all conditions areseparated by a comma. Consequentially, this rule requires humidityReading-and online facts to be available in the Fact Base before it will be triggered.However, it also requires these facts to be related. If a humidityReading isreceived, it will match the first condition. The variable ?humid will be bound tothe measured humidity and the variables ?hMac and ?hId will be bound to thepublishing component’s MAC address and ID, respectively. As a consequence,only the online fact published by the very same component will match thesecond condition and will bind ?tent to the originating tent. As soon as bothconditions are matched and the variable bindings are consistent, the rule isactivated and the humidityInTent fact (with ?humid and ?tent substituted bytheir values) will be asserted in the Fact Base. Analogously, a rule for relatingtemperatureReading facts with online facts in temperatureInTent facts canbe added to the ComfortLevelMonitor.

Content-based relations The facts asserted by the aforementioned prepro-cessing rules can now be related in the interaction rule for logging the comfortlevels. Note that this rule has to invoke application logic when it’s activatedand that it therefore requires an action (i.e., logAction) rather than a fact inits head. We will further explain the use of actions in Section 3.7.2.

1 logAction

2 <- humidityInTent(Percent =?humid , Tent=?tent),

3 temperatureInTent(Celsius =?temp , Tent=?tent).

Page 58: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

CHAPTER 3. NODE-CENTRIC PROGRAMMING WITH CRIMESPOT 46

As soon as a humidityInTent fact is asserted in the Fact Base, it will matchthe first condition and the variable ?tent will be bound to the originating tent.Consequentially, only a temperatureInTent fact for the same tent ?tent willprovide a valid match for the second condition. When the rule is activated, theapplication logic in the logAction will be invoked to compute and log the tent’scomfort level.

It must be noted that an interaction rule with a body consisting of multipleconditions does not require these conditions to be matched in any particularorder. A match for such an interaction rule only requires a match for eachcondition with consistent variable bindings.

However, in general, care must be taken to make sure that a conditionmatches only the expected amount of times. To illustrate this, we can reconsiderthe running example. In this application, it is perfectly possible that a certainhumidity sensor node is reset due to some failure. If this happens, the nodewill restart and re-publish its online fact, and as a result, the ComfortLevel-Monitor ’s Fact Base will contain two such facts4. Consequentially, the rule forasserting HumidityInTent facts discussed above will have two matches for thecondition on line 3, and will thus be activated twice for each for each humidityreading from the reseted node’s tent. Figure 3.11 further illustrates this issue.

online(Tent=`A, Component=`HumiditySensor)@[from(MAC="hsMAC", ID=3)]online(Tent=`A, Component=`HumiditySensor)@[from(MAC="hsMAC", ID=3)]

humidityReading(Percent=25)@[from(MAC="hsMAC",ID=3)]

Match 1: <humidityReading(Percent=25)@[from(MAC="hsMAC",ID=3)], online(Tent=`A, Component=`HumiditySensor)@[from(MAC="hsMAC", ID=3)]>

Match 2: <humidityReading(Percent=25)@[from(MAC="hsMAC",ID=3)], online(Tent=`A, Component=`HumiditySensor)@[from(MAC="hsMAC", ID=3)]>

Figure 3.11: Faulty matching illustrated

The humidityReading in the Fact Base will match the condition on line 2and bind ?hMac and ?hId. However, because two online facts with consistentvalues for these variables will match the second condition, the rule itself willhave two matches and will consequentially be activated twice. This results inthe assertion of two humidityInTent facts for a single humidityReading fact.To allow the programmer to deal with this unintended behavior, CrimeSPOToffers functionality to retract old facts when new facts are received. In this case,this would be useful to retract a component’s existing online fact when a newone is received. We will explain the use of this functionality in Section 3.8.

3.7.1.3 Fine-grained Matching Control

When matching facts using logical conditions, it might be desired to get morecontrol over the matching process. To this end, our language offers some built-in

4That is, until the oldest one expires.

Page 59: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

CHAPTER 3. NODE-CENTRIC PROGRAMMING WITH CRIMESPOT 47

meta-attributes that can be added to a fact specification in a condition. Unlikethe meta-attributes specifying a fact’s associated meta-data, these built-in meta-attributes are not part of the facts in the Fact Base, but allow the programmerto exert control over the matching process for the associated fact specification.The built-in meta-attributes can be combined as desired.

Match Expiration In certain cases, it is useful to make a match for a con-dition expire after a specific amount of time. For instance, when dealing withtemperatureReading facts, a more recent temperature reading can have a dif-ferent meaning than an older temperature reading. This can be specified usingthe matchExpires meta-attribute. In case the programmer only wants tempera-ture readings with a maximum age of ten seconds to match an interaction rule’scondition, she can express this using the condition from Listing 3.6.

1 temperatureReading(Celsius =?temp)@[from(MAC=?m, ID=?i),

2 matchExpires(Seconds =10)]

Listing 3.6: A condition for matching only recent temperature readings

Any fact matching a condition with an associated matchExpires meta-attributewill only match this condition for the specified amount of time. Note that the ex-piration of the match does not imply the expiration of the matched fact. Hence,nothing precludes other rules to use such a fact for matching their conditions.Figure 3.12 further illustrates the impact of the matchExpires meta-attribute onthe above condition. At every point in time (denoted in seconds), the contentsof the Fact Base and the matches for the condition are shown. Temperaturereadings are received at 0s and 4s. For simplicity, these temperature readingsare assumed not to expire. However, due to the matchExpires meta-attribute,their match for the above condition does expire after ten seconds. Hence, whilethe facts remain in the Fact Base and therefore can still match other conditions,they do not match this condition for more than ten seconds.

time

received fact temp(C=15)

{temp(C=15)}matches

fact base { }

{ }

{temp(C=15)}

temp(C=20)

0 4 8 12

{temp(C=15) temp(C=20)}

{temp(C=15) temp(C=20)}

{temp(C=15) temp(C=20)}

{temp(C=20)}

16

{temp(C=15) temp(C=20)}

{}

Figure 3.12: Illustrating Match Expiration

Match Verification Additionally, it is also useful to specify the expectedmatching for a condition, for instance, to do some sort of error handling when-ever the expected matching is not obtained. To this end, the matchEvery meta-attribute can be added to a fact specification. Whenever a condition carryingthis meta-attribute isn’t matched in the specified amount of time, a timedOut

fact will be asserted in the Fact Base. Such a timedOut fact specifies exactlywhich condition was violated by specifying the rule in which the condition was

Page 60: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

CHAPTER 3. NODE-CENTRIC PROGRAMMING WITH CRIMESPOT 48

used5, and the type of the fact specification carrying the matchEvery meta-attribute. As an example, we can consider the rule from Listing 3.7.

1 gotReadingFrom(MAC=?m)

2 <- temperatureReading(Celsius =?temp)@[from(MAC=?m, ID=?i),

3 matchEvery(Seconds =60)].

Listing 3.7: A rule with a condition that expects a match at least every minute

As soon as this condition doesn’t get a new match within one minute, thefollowing timedOut fact will be asserted in the Fact Base.

1 timedOut(Head=‘gotReadingFrom_1 , ViolatedCondition=‘temperatureReading ).

To do the appropriate error handling, this fact can be matched in the conditionof another rule to signal the malfunctioning of the sensor node publishing thetemperature readings. As soon as the condition obtains a new match, the cor-responding timedOut fact is retracted from the Fact Base. Figure 3.13 depictsthe impact of the matchEvery meta-attribute. At every point in time (denotedin seconds), the contents of the Fact Base and the matches for the condition areshown6. Temperature readings are expected to be received every 60 seconds,but are for some reason received at 0s and 90s. Due to the matchEvery meta-attribute, a timedOut fact is asserted at 60s because the expected matching wasnot obtained. Afterwards, at 90s, a new temperature reading is received andthe timedOut fact is consequentially retracted.

time

received fact temp(C=15)

{temp(C=15)}matches

fact base { }

{ }

{temp(C=15)}

temp(C=20)

0 30 60 90

{temp(C=15) timedOut(...)}

{temp(C=15)} {temp(C=15)}

120

{temp(C=15) temp(C=20)}

{temp(C=15) timedOut(...)}

{temp(C=15) temp(C=20)}

Figure 3.13: Illustrating Match Verification

3.7.1.4 Extra-logical Conditions

Up till now, we have only considered using logical conditions to match facts fromthe Fact Base and provide variable bindings. While logical conditions are oftensufficient to specify a reaction to incoming events, it is also desirable to bindvariables using other sources (e.g., method invocations), or to add additionalconstraints to the body of an interaction rule. To this end, our language providesthe programmer with some extra-logical conditions, which we will briefly discussin this section.

Incorporating component state The state of the component using CrimeSPOTcan be accessed from within the rules’ bodies using the built-in is-operator. Thisoperator expects either a constant value or a variable on its left-hand side and

5Every interaction rule is uniquely identified by the fact type of the fact in its head, or thekeyword actionRule if the head contains an action, followed by its lexicographical number.

6For simplicity, the gotReadingFrom facts are not shown in the Fact Base.

Page 61: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

CHAPTER 3. NODE-CENTRIC PROGRAMMING WITH CRIMESPOT 49

a method invocation on its right-hand side. It only provides a match if theexpression on the left-hand side can be unified with the result of the methodinvocation. In addition, the arguments for the method to invoke should be ei-ther constants, or variables that were bound by the previous conditions in therule’s body. For instance, one can bind a variable with the current temperatureby invoking one of the component’s methods as shown below.

1 ?temp is getTemperature ()

Another relevant use is to compute a comfort level based on the temperature-and humidity readings originating from the same sensor node. In that case, thefollowing body can be used.

1 humidityReading(Percent = ?h)@[from(MAC=?mac)],

2 temperatureReading(Celsius = ?t)@[from(MAC=?mac)],

3 ?comfortLevel is computeComfortLevel (( Number )?h, (Number )?t)

Note that variable method arguments have to be type-casted to their values’Java type7. For this method invocation to succeed, the component should havea method with the following signature.

1 Attribute computeComfortLevel(Number , Number );

In general, a method is invoked for every match for the previous conditionsin the rule’s body. For instance, in the previous example, computeComfortLevelis invoked for every pair of humidity- and temperature readings originating fromthe same sensor node. In case there are no preceding conditions, the methodis invoked only once. However, the programmer can also specify an invocationschedule by adding a scheduling option to the method invocation. Schedulingoptions employ the same notation as meta-attributes. To illustrate their use, wecan reconsider the sensing components from our running example, which haveto publish their sensor readings at set intervals. An interaction rule specifyingthis behavior for the HumiditySensor component is shown in Listing 3.8.

1 humidityReading(Percent = ?p)@[to(MAC=any),

2 factExpires(Seconds = 600)]

3 <- ?p is getHumidity ()@[renewEvery(Seconds = 600)].

Listing 3.8: Publishing humidity readings using the is operator

The scheduling option added to the method invocation specifies that, wheneverthe method is invoked, it should be re-invoked after ten minutes.

Either the renewEvery- or the evalEvery option can be used to scheduleadditional invocations. While renewEvery invalidates the previous match forthe is-operator, evalEvery keeps the older matches valid. The latter can, forinstance, be used to keep a history of humidity readings in the Fact Base, asshown in Listing 3.9.

1 humidityReading(Percent = ?p)

2 <- ?p is getHumidity ()@[evalEvery(Seconds = 600)].

Listing 3.9: Keeping a history of humidity readings

Every ten minutes, a new humidityReading will be asserted in the Fact Base.Using renewEvery, on the other hand, would replace the asserted humidity read-ing every ten minutes. This can be observed in Figure 3.14, which depicts the

7The most commonly used Java types are Number, Fraction, Symbol, Text and List, whichall subclass Attribute.

Page 62: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

CHAPTER 3. NODE-CENTRIC PROGRAMMING WITH CRIMESPOT 50

matches for the is-operator together with the resulting Fact Base at every pointin time (denoted in minutes).

evalEvery

renewEvery

time

{?p=h0, ?p=h1}

matches

fact base {humid(P=h0)}

{?p=h0}

{humid(P=h0), humid(P=h1)}

0 10 20

{humid(P=h0), humid(P=h1), humid(P=h2)}

{?p=h0, ?p=h1, ?p=h2}

{?p=h1}matches

fact base {humid(P=h1)} {humid(P=h2)}

{?p=h2}

{humid(P=h0)}

{?p=h0}

Figure 3.14: Scheduling method invocations: evalEvery vs. renewEvery

Other useful constructs Finally, four other constructs can be used as acondition in a rule’s body. An External Constraint can be used for specifyingthe required relationship between variables, or between variables and constants.To this end, every relational operator is built-in and expects a variable on itsleft-hand side, and a variable or constant on its right-hand side. It provides amatch if the specified relationship holds. For instance, to react to the occurrenceof two temperature readings where one temperature reading is larger than theother, the following body can be used.

1 temperatureReading(Celsius =?t1),

2 temperatureReading(Celsius =?t2),

3 ?t1 > ?t2

In contrast to external constraints, internal constraints can be used within afact specification. For instance, if the value of the second temperatureReading

is irrelevant to the interaction rule, the above body can be rewritten as shownbelow.

1 temperatureReading(Celsius =?t1),

2 temperatureReading(Celsius <?t1)

The Negation can be used to check for the absence of matching facts. Tothis end, a logical condition can be preceded by the not operator, which onlyprovides a match if the logical condition is unmatched. For instance, to check forthe absence of an adjustHeating fact, the following condition can be employed.

1 not adjustHeating(Level=?l)

The findall operator can be used to accumulate values from several factsin a List. As its second argument, it takes a list of one or more conditions(i.e., its body), which bind certain variables in every match8. In addition, thevariable whose bindings should be accumulated in the list should be given asfindall’s first argument, and the variable to be bound to the resulting list should

8Note that this body is also conceptually re-evaluated whenever the Fact Base changes.

Page 63: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

CHAPTER 3. NODE-CENTRIC PROGRAMMING WITH CRIMESPOT 51

be given as findall’s last argument. At any time, the findall operator providesa match which binds this last variable to the list of accumulated values. As anexample, we can consider the body of an interaction rule residing in a controllerfor smoke detectors. If all smoke detectors publish a smoke event upon smokedetection, and the controller should sound the alarm as soon as three differentsmoke events have been received, the body from Listing 3.10 can be used in theinteraction rule.

1 findall (?m,

2 [smoke()@[from(MAC=?m)]],

3 ?alarmingSensors),

4 length (? alarmingSensors , ?l),

5 ?l >= 3

Listing 3.10: Collecting smoke facts using findall

At all times, ?alarmingSensors will be bound to a list containing the publishersof the smoke facts in the Fact Base. However, the interaction rule will onlybe activated when this list contains at least three values. This example alsoillustrates the use of the length operator, which can be used to compute thelength of a given list.

3.7.2 Reactions

Having discussed the kinds of conditions that can be used in the body of aninteraction rule, we shift our focus to the head. The content of the head (i.e.,either a fact or an action) determines the behavior that corresponds to thetriggering of an interaction rule, or indirectly, it determines the reaction to thereception of events. In general, two reactions can occur: a fact can be assertedin or retracted from the Fact Base, or application logic can be invoked.

3.7.2.1 Fact Assertion or Retraction

If an interaction rule’s head contains a fact, this fact will be asserted in theFact Base for every activation of the rule. On the other hand, when the rule isdeactivated, the corresponding fact will be retracted from the Fact Base. Hence,the view a component has on its world is always up-to-date.

As every match for a rule provides bindings for the variables that occur inits body, these variables can be used in the head. For instance, the previouslydiscussed rule for keeping a history of humidity readings in the Fact Base (cfr.Listing 3.9) asserts humidityReading(Percent=?p) facts in which the variable?p is substituted for its value.

Publishing facts A common reaction to the reception of facts is to publishanother fact. As discussed earlier, facts can be published on the underlying mid-dleware’s event-bus by giving it a to meta-attribute that specifies its destination.For instance, the following interaction rule can be added to the CrimeSPOTruntime to answer temperature requests.

1 temperatureReading(Celsius =?temp)@[to(MAC=?mac , ID=?id)]

2 <- getTemperature ()@[from(MAC=?mac , ID=?id)],

3 ?temp is getTemperature ().

Page 64: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

CHAPTER 3. NODE-CENTRIC PROGRAMMING WITH CRIMESPOT 52

Whenever a getTemperature fact is received, the getTemperature() method willbe invoked and the temperatureReading fact will be published to the requester.

Note that, when an interaction rule is deactivated, its published fact shouldalso be retracted in the remote Fact Bases. To this end, retractions are alsopublished through the underlying middleware9.

Fact Expiration It is often desired to retract a fact from the Fact Base beforethe interaction rule that asserted it is deactivated. To this end, the programmercan add a factExpires meta-attribute to the fact in which its lifetime can beexpressed. Such fact expiration was, for instance, specified in the interactionrule for publishing humidityReading facts:

1 humidityReading(Percent = ?p)@[to(MAC=any),

2 factExpires(Seconds = 600)]

3 <- ?p is getHumidity ()@[renewEvery(Seconds = 600)].

The humidityReading fact expires after ten minutes and will consequentiallybe retracted from the local and remote Fact Bases. As such, this rule, which isre-activated every ten minutes, does not require a retraction for the humidityreading to be published.

3.7.2.2 Invoking Application Logic

Interaction rules that have an action as their head will invoke application logicwhenever they are activated or deactivated. To illustrate this, we can considerthe interaction rule for logging the comfort levels in our running example. Thisrule can be added to the ComfortLevelMonitor component’s Rule Base usingthe registerRule(String,Action) method as shown in Listing 3.11. TheregisterRule method takes the body of the interaction rule as its first argumentand an instance of the abstract Action type as its second argument. To specifythe application logic to invoke, the instance of the Action type should provide animplementation for the activated(TypedObject) and deactivate(TypedObject)

methods. These methods will be invoked whenever the interaction rule is acti-vated and deactivated, respectively.

1 registerRule(

2 "humidityInTent(Percent =?humid , Tent=?tent), " +

3 "temperatureInTent(Celsius =?temp , Tent=?tent)",

4 new Action () {

5 public void activated(TypedObject args) {

6 // Compute and log the comfort level using

7 // args.getValue (" humid "), args.getValue (" temp "),

8 // and args.getValue (" tent ")

9 }

10 public void deactivate(TypedObject args) {

11 // no compensating action for this rule

12 }

13 });

Listing 3.11: Adding an interaction rule for invoking application logic to theCrimeSPOT runtime

Whenever the interaction rule is triggered, the TypedObject instance passed toboth of these methods can be used to consult the bindings for the variables that

9In the example, it is assumed that getTemperature requests remain in the Fact Base, andhence, that the interaction rule will never be deactivated.

Page 65: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

CHAPTER 3. NODE-CENTRIC PROGRAMMING WITH CRIMESPOT 53

occur in the body of the interaction rule. For instance, the binding for ?temp

can be obtained by invoking getValue("temp") on the TypedObject.

3.7.3 Precedence

In CrimeSPOT, the precedence between the interaction rules is determined bythe order in which they were added to the CrimeSPOT runtime. If multiplerules employ a condition that is matched by a newly asserted fact, the rule thatwas added first will be activated first. Conversely, when multiple rules employa condition that is no longer matched due to the retraction of a fact, the sameprecedence is retained for their deactivation.

3.8 Fine-tuning the Reification Engine

Since all facts in the Fact Base are taken into account for triggering the inter-action rules, it’s important to keep only the relevant ones. Up till now, we’vediscussed that facts can expire and are consequentially retracted from the FactBase. However, the expiration of facts is not sufficient to keep the Fact Baseclean. Often, a newly received fact subsumes older facts which should conse-quentially be retracted. In addition, it can occur that an incoming fact shouldbe dropped right away rather than being asserted in the Fact Base.

In CrimeSPOT, these concerns can be expressed through meta-facts, whichcan be added to the CrimeSPOT runtime just like any other textual expression.While meta-facts look like regular facts, they represent the configuration of theReification Engine and are stored in the Configuration Base rather than theFact Base. Whenever the Reification Engine processes an incoming event, itwill act according to its meta-facts. Figure 3.15 depicts the event reificationpipeline. When the Reification Engine receives an event, it will first reify it as afact and verify whether it should be dropped. If the fact shouldn’t be dropped,the Reification Engine will retract all facts that were subsumed by the newlyreceived fact, after which it will assert the new fact in the Fact Base.

Decentralized Event Bus Event Middleware

BridgeReification

Engine

Config.Base

FactBase

Fact

Event Reification Drop? Subsumes? Assert

Reification Process

Figure 3.15: Event reification pipeline

Page 66: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

CHAPTER 3. NODE-CENTRIC PROGRAMMING WITH CRIMESPOT 54

3.8.1 Specifying Subsumption Strategies

The subsumption meta-fact can be used to specify exactly which facts shouldbe removed from the Fact Base when a new fact is received. For instance,for the HeatingController component from our running example, only the lastadjustHeating fact is of relevance. This fact will be used for steering thecomponent’s associated heater and no history of heating levels should be kept.Hence, before asserting a new adjustHeating fact, the previous ones should beremoved. In other words, every new adjustHeating fact subsumes the previ-ously stored one. This subsumption strategy can be expressed by adding thesubsumption meta-fact from Listing 3.12 to the CrimeSPOT runtime.

1 subsumes !( Incoming=adjustHeating(Level = ?new),

2 Fact=adjustHeating(Level = ?old)).

Listing 3.12: Specifying a subsumption strategy for adjustHeating facts

While the Incoming attribute specifies the newly reified event, the Fact attributespecifies which facts should be retracted from the Fact Base before the new factis asserted (i.e., all matching facts10). Because the variables specifying theheating level in either attribute are distinct, their values aren’t required to beequal and hence every adjustHeating fact is retracted from the Fact Base whena new one is received. The impact of this meta-fact on the Fact Base is furtherillustrated in Figure 3.16. At every point in time, the contents of the Fact Baseare shown together with the received adjustHeating fact and the set of factssubsumed by this new fact. Note that, every time a new adjustHeating fact isreceived, the previously stored one is retracted due to the presence of the abovesubsumption meta-fact in the Reification Engine’s Configuration Base.

time

received fact adjustH(L=5) adjustH(L=3)

subsumed facts

fact base { }

{ }

{adjustH(L=5)}

{adjustH(L=5)}

adjustH(L=0)

{adjustH(L=3)}

{adjustH(L=3)}

{adjustH(L=0)}

0 1 2 3

Figure 3.16: Subsumption impact for adjustHeating facts

By using the same variables in both fact specifications, more specific sub-sumption strategies can be expressed as the values bound to these variablesshould be equal for the subsumption to take place. This is useful, for instance,to deal with the unintended matching behavior in the ComfortLevelMonitorcomponent from the running example (cfr. Figure 3.11). At any time, theComfortLevelMonitor should only have a single online fact in its Fact Base forevery running component. To avoid the faulty matching when a running compo-nent fails, restarts, and republishes its online fact, the following subsumptionmeta-fact should be added to the CrimeSPOT runtime:

10In case a certain incoming fact should subsume multiple fact types, multiple subsumptionmeta-facts should be added for this fact.

Page 67: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

CHAPTER 3. NODE-CENTRIC PROGRAMMING WITH CRIMESPOT 55

1 subsumes !( Incoming=online(Tent = ?new , Component = ?comp)@[from(MAC=?mac)],

2 Fact=online(Tent = ?old , Component = ?comp)@[from(MAC=?mac )]).

Listing 3.13: Specifying a subsumption strategy for online facts

When a new online fact is received and the above meta-fact is processed by theReification Engine, ?mac and ?comp will be bound to the new fact’s originat-ing MAC address and component name, respectively. Hence, only the existingonline fact originating from the very same component will match the Factspecification and will consequentially be retracted from the Fact Base beforethe new online fact is asserted. Note that nothing precludes a component torestart in another tent because the variables specifying the tent identifiers aredistinct.

Finally, a subsumption meta-fact can also have a When attribute, specifyinga list of conditions (i.e., its body). These conditions should be satisfied at thetime a new fact is received for the corresponding subsumption to take place.To illustrate its use, we can consider another subsumption meta-fact for theComfortLevelMonitor component of our running example. The following sub-sumption meta-fact expresses that a new humidityReading from a certain tent?tent subsumes all older humidity readings from that same tent:

1 subsumes !( Incoming=humidityReading(Percent = ?new)@[from(MAC=?mac ,ID=?id)],

2 Fact=humidityReading(Percent = ?old)@[from(MAC=?othermac ,ID=? otherid)],

3 When=[ online(Tent = ?tent)@[from(MAC=?mac ,ID=?id)],

4 online(Tent = ?tent)@[from(MAC=?othermac ,ID=? otherid )]]).

Listing 3.14: Specifying a subsumption strategy for humidityReading facts

When a new humidity reading is received and this meta-fact is processed by theReification Engine, ?mac and ?id will be bound to the new reading’s originatingMAC address and component ID, respectively. As a result, the condition on line3 will bind ?tent to the originating tent and only the humidity readings fromthat same tent will be subsumed due to the condition on line 4.

As can be observed, the programmer has the full power of the logical reason-ing engine for expressing her subsumption strategies. It must be noted, however,that the programmer cannot expect the variables used in the Incoming factspecification to be bound before the When clause is evaluated. Consequentially,these variables cannot be used where a bound variable is expected (e.g., as theargument of a method invocation). In addition, while the When clause mightbe unsatisfied after a subsumption, this operation is irreversible and will not beundone.

3.8.2 Dropping Incoming Facts

As various facts can be published to the decentralized event-bus, it is possiblethat a component is not interested in certain facts and hence shouldn’t addthese facts to its Fact Base upon reception. The drop meta-fact can be used tospecify exactly those irrelevant facts. To illustrate its use, we can reconsider therunning example. If for some reason, the HeatingController, TemperatureSensorand HumiditySensor would receive the other components’ online facts, thesefacts could be dropped upon reception because they’re never used by thesecomponents and hence would only pollute their Fact Bases11. To this end, the

11This would be the case if the online facts are published by a rule and carry theto(MAC=any) meta-attribute, implying a broadcast.

Page 68: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

CHAPTER 3. NODE-CENTRIC PROGRAMMING WITH CRIMESPOT 56

drop meta-fact from Listing 3.15 could be added to each of those components.

1 drop!( Incoming=online(Tent = ?tnt , Component = ?c)).

Listing 3.15: Dropping irrelevant facts

Just as in a subsumption meta-fact, the Incoming attribute specifies the newlyreceived fact, which in this case has to be dropped. Whenever an incoming factis dropped, it won’t trigger any subsumption meta-facts and it won’t be assertedin the Fact Base. Consequentially, it also won’t trigger any interaction rules.

Additionally, a drop meta-fact can also have a When attribute, specifying alist of conditions (i.e., its body) to be satisfied at the time a new fact is receivedfor the corresponding fact drop to take place. An example illustrating its useconsists of storing only the maximum received temperature in the Fact Base. Toobtain this behavior, the following meta-facts can be added to the CrimeSPOTruntime:

1 drop!( Incoming=temperatureReading(Celsius =?t),

2 When=[ temperatureReading(Celsius >= ?t)]).

34 subsumes !( Incoming=temperatureReading(Celsius =?t),

5 Fact=temperatureReading(Celsius = ?oldT),

6 When =[? oldT < ?t]).

With these meta-facts in the Configuration Base, the Reification Engine willonly accept a new temperature if it’s strictly larger than any temperature al-ready in the Fact Base (lines 1-2). In addition, an accepted temperature willsubsume all smaller temperatures in the Fact Base (lines 4-6). Therefore, atany time, the Fact Base will contain at most one temperatureReading, whichis the largest one received up till that moment. Again, the programmer cannotexpect the variables used in the Incoming fact specification to be bound beforethe When clause is evaluated, and a drop operation will not be undone whenthe When clause is unsatisfied after the drop took place.

While up till now, the specifications used in the meta-facts employed vari-ables for the attributes’ values, it must be noted that constants can also be usedfor more specific matching. For instance, if one wants to drop all incoming sen-sor readings from a certain MAC address ”1234:1234:1234:1234”, the meta-factfrom Listing 3.16 can be added to the CrimeSPOT runtime.

1 drop!( Incoming=sensorReading(Type=?v)@[from(MAC="1234:1234:1234:1234")]).

Listing 3.16: Using constants in meta-facts

3.9 Revisiting the Running Example

Having introduced the CrimeSPOT language, we will now revisit the runningexample and finalize its CrimeSPOT implementation. To this end, we willuse the functional requirements identified earlier (cfr. Table 3.1). As most ofthe implementation was already explained in the previous sections, we will onlydiscuss the remaining parts.

The sensing components For the sensing components (i.e., the Humidi-tySensor and TemperatureSensor), the following functional requirements wereidentified:

Page 69: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

CHAPTER 3. NODE-CENTRIC PROGRAMMING WITH CRIMESPOT 57

F.R.1 The HumiditySensor and TemperatureSensor have to publishtheir sensor readings at set intervals.

F.R.2 The HumiditySensor and TemperatureSensor have to publishtheir online presence and location at set intervals.

Clearly, these requirements are easily met by using interaction rules in combi-nation with the is-operator to invoke the required application logic and publishthe results at set intervals. The interaction rule for publishing humidity read-ings was already depicted in Listing 3.8. The interaction rules for publishingtemperature readings and online facts (i.e., facts encapsulating a component’slocation) are very similar, which is why only the latter is shown below.

1 online(Tent = ?t, Component = ‘TemperatureSensor)@[to(MAC=any),

2 factExpires(Seconds =3600)]

3 <- ?t is getTentBasedOnGPSReading ()@[renewEvery(Seconds =3600)].

Listing 3.17: Publishing online facts from the TemperatureSensor component usingthe is operator

This rule should be added to the TemperatureSensor component and publishesan online fact every hour. To this end, the identifier for the current tent is ob-tained by reading out a GPS sensor in the getTentBasedOnGPSReading method,which is invoked every hour. After substituting the value for the Componentattribute in the online fact, this rule can also be added to the HumiditySensorcomponent.

The HeatingController component For the HeatingController component,the following functional requirements were identified:

F.R.2 The HeatingController has to publish its online presence and lo-cation at set intervals.

F.R.3 The HeatingController has to adjust its associated heater accord-ing to a received adjustHeating event.

F.R.4 The HeatingController has to make sure that its associated heaterwon’t keep heating when the ComfortLevelMonitor fails or getsdisconnected from the WSN.

While F.R.2 can be met through the rule from Listing 3.17 (i.e., after sub-stituting the value for the Component attribute in the online fact), F.R.3 andF.R.4 require an interaction rule that invokes application logic upon triggering.This rule can be added to the CrimeSPOT runtime as shown below.

1 registerRule("adjustHeating(Level = ?h)",

2 new Action () {

3 public void activated(TypedObject args) {

4 // adjust the heater using args.getValue ("h")

5 }

6 public void deactivate(TypedObject args) {

7 // reset the heater

8 }

9 });

Listing 3.18: Reacting to adjustHeating facts

Page 70: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

CHAPTER 3. NODE-CENTRIC PROGRAMMING WITH CRIMESPOT 58

As soon as the HeatingController receives an adjustHeating fact, this rule willbe activated and the component will steer its heater accordingly. To deal withF.R.4, an adjustHeating fact expires after a specific amount of time, afterwhich this rule will be deactivated and the component will reset its heaterto a neutral setting. Additionally, as we’ve discussed before, only the lastadjustHeating fact should be stored in the Fact Base. To this end, the sub-sumption meta-fact from Listing 3.12 should also be added to the component.

The ComfortLevelMonitor component Finally, the ComfortLevelMonitorcomponent had the following functional requirements:

F.R.5 The ComfortLevelMonitor has to compute a tent’s heating levelbased on a received temperatureReading event and publish thislevel in an adjustHeating event.

F.R.6 The ComfortLevelMonitor has to control the heating for each tentindividually by sending adjustHeating events only to the Heat-ingControllers in the tent to be heated.

F.R.7 The ComfortLevelMonitor has to relate receivedhumidityReading and temperatureReading events thatoriginate from the same tent and use them to compute and logthat tent’s comfort level.

F.R.8 The ComfortLevelMonitor has to make sure that only the mostrecent sensor readings from a certain tent are used for computingthe heating- and comfort levels.

As discussed earlier, F.R.7 can be met by adding three rules to the Com-fortLevelMonitor component. First of all, the humidity- and temperature read-ings have to be related to the online facts to obtain their originating tent.For humidity readings, this can be done through the preprocessing rule de-picted in Listing 3.5, which relates these readings with online facts, and assertshumidityInTent facts. The rule for asserting temperatureInTent facts is verysimilar and therefore not shown for brevity12. The third rule invokes applica-tion logic to compute and log a tent’s comfort level, and was depicted in Listing3.11.

To deal with F.R.5 and F.R.6, the following interaction rule can be addedto the ComfortLevelMonitor component:

1 adjustHeating(Level = ?heatingLevel)@[to(MAC=?hcm , ID=?hci),

2 factExpires(Seconds = 600)]

3 <- temperatureInTent(Celsius = ?temp , Tent = ?tnt),

4 ?heatingLevel is computeHeatingLevel (( Number )?temp),

5 online(Component = ‘HeatingController ,

6 Tent = ?tnt)@[from(MAC = ?hcm , ID=?hci)].

As soon as a temperatureInTent fact is asserted (i.e., as soon as a new tem-perature reading is received), the condition on line 3 will be matched and willbind ?temp to the measured temperature and ?tnt to the originating tent. Thesubsequent method invocation on line 4 will compute the required heating level,

12Remember that these preprocessing rules require the presence of exactly one online factin the Fact Base for each running component and that it’s therefore also a good idea to addthe subsumption meta-fact from Listing 3.13 to the CrimeSPOT runtime.

Page 71: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

CHAPTER 3. NODE-CENTRIC PROGRAMMING WITH CRIMESPOT 59

which has to be published to the HeatingControllers in the tent to be heated. Tothis end, the condition on line 5 will bind ?hcm and ?hci to such a HeatingCon-troller ’s MAC address and component ID, respectively, and the adjustHeatingfact in the rule’s head is published using these values. Note that the conditionon line 5 will have a match for every HeatingController in the tent to be heatedand that this rule will consequentially send the adjustHeating fact to each ofthese controllers. As mentioned before, the adjustHeating fact should expire,which is expressed by its factExpires meta-attribute.

F.R.8 has to be dealt with using subsumption meta-facts. Because all factsin the Fact Base are taken into account for triggering the interaction rules, andconsequentially for computing the heating- and comfort levels, this requirementactually states that every newly received sensor reading from a certain tentsubsumes any older sensor reading from that tent. This subsumption strategywas expressed earlier for humidityReading facts in Listing 3.14. The subsump-tion strategy for temperatureReading facts, which is entirely analog, is shownbelow.

1 subsumes !( Incoming=temperatureReading(Celsius =?new)@[from(MAC=?mac ,ID=?id)],

2 Fact=temperatureReading(Celsius =?old)@[from(MAC=?othermac ,ID=? otherid)],

3 When=[ online(Tent=?tnt)@[from(MAC=?mac ,ID=?id)],

4 online(Tent=?tnt)@[from(MAC=?othermac ,ID=? otherid )]]).

Both subsumption strategies make sure that for every tent, only the lasttemperatureReading and the last humidityReading will be stored in the FactBase, even when multiple redundant TemperatureSensor - or HumiditySensorcomponents have been deployed in the same tent.

3.10 Conclusion

When programming wireless sensor network applications from a node-level per-spective using event-based component middleware, every component has to beindividually programmed by specifying its interactions with other components.These interactions are driven by the exchange of events over a decentralizedevent-bus. However, without additional support, event handlers are the onlymeans to react to the reception of events.

This chapter introduced CrimeSPOT, our programming language that pro-vides additional support for programming interactions among WSN compo-nents. Rather than using event handlers, it advocates the use of declarativeinteraction rules to react to the reception of events. To this end, CrimeSPOTreifies events as facts and stores them in a Fact Base. By allowing the pro-grammer to associate an expiration time with reified events, we reconcile thetransient nature of events with the persistent nature of facts. The interactionrules, each specifying one or more facts to react upon, are re-evaluated when-ever the Fact Base is updated, which indirectly corresponds to the reception orexpiration of events. As soon as an interaction rule’s conditions are met, itsreaction is triggered. In addition, a rule is also triggered when its conditionsare no longer met, which allows its reaction to be compensated for.

By using CrimeSPOT, the programmer no longer has to deal with theaccidental complexity inherent to the use of event-based WSN middleware. Sheno longer has to dispatch a received event to its appropriate reaction in an eventhandler, nor is she required to implement ad-hoc state management to keep track

Page 72: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

CHAPTER 3. NODE-CENTRIC PROGRAMMING WITH CRIMESPOT 60

of which events have already been received and whether or not they are stillvalid. More importantly, CrimeSPOT’s interaction rules facilitate untanglingthe code concerned with application logic and component interactions.

More details about the implementation of the CrimeSPOT language canbe found in Appendix A. The next chapter introduces the Macro-CrimeSPOTextension, which allows programming CrimeSPOT components from a network-level perspective.

Page 73: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

CHAPTER 3. NODE-CENTRIC PROGRAMMING WITH CRIMESPOT 61

�expression� ::= �expr�.�expr� ::= �mapping�

| �meta-fact�| �fact� | �rule�

�mapping� ::= mapping �fact� <=> �event��meta-fact� ::= �subsumption� | �drop��subsumption� ::= subsumes!(Incoming=�fact�,Fact=�fact� [ ,When=[�body�] ] )

�drop� ::= drop!(Incoming=�fact� [ ,When=[�body�] ] )

�fact� ::= �type�( [ �attribute� (, �attribute�)* ] ) [ @[ �meta-attributes� ] ]

�attribute� ::= �name� �relop� ( �value� | �variable� )

�meta-attributes� ::= �meta-attribute� (, �meta-attribute�)*�meta-attribute� ::= �assert-meta-attribute�

| �condition-meta-attribute��event� ::= �type�(�field� (, �field�)*)�field� ::= �type� = �variable��rule� ::= �fact� <- �body��body� ::= �condition� (, �condition�)*�condition� ::= �fact�

| �extralogical condition��value� ::= �number� | �quoted text� | �symbol� | �list��list� ::= [ [ (�value� | �variable�) (, (�value� | �variable�))* ] ]

�quoted text� ::= "�text�"�symbol� ::= ‘�text��type� ::= �text��name� ::= �text��variable� ::= ?�name��relop� ::= = | != | <= | >= | < | >

�assert-meta-attribute� ::= to(MAC=(�quoted text� | any))| to(ID=(�number� | any))| factExpires(Seconds=�number�)

�condition-meta-attribute� ::= from(MAC=(�quoted text� | �variable� | this.MAC))| from(ID=(�number� | �variable� | this.ID))| matchExpires(Seconds=�number�)| matchEvery(Seconds=�number�)

�extralogical condition� ::= (�value� | �variable�) is �methodinvocation�| findall(�variable�,[�body�],�variable�)| length(�list�,(�value� | �variable�))| not �fact�| �variable� �relop� (�value� | �variable�)

�methodinvocation� ::= �name�( [ �argument� (, �argument�)* ] ) [ @[�option�] ]

�argument� ::= �value� | (�typecast�)�variable��typecast� ::= Number | Fraction | Text | Symbol | List�option� = evalEvery(Seconds=�number�)

| renewEvery(Seconds=�number�)

Figure 3.8: CrimeSPOT Grammar

Page 74: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

4Network-centric Programming with

Macro-CrimeSPOT

So far, we have introduced the CrimeSPOT programming language which fa-cilitates programming individual wireless sensor network components. Next tosignificantly reducing the complexity of dealing with events in such components,it also untangles the code concerned with application logic and component in-teractions. However, a few important shortcomings can be identified when pro-gramming WSN applications using CrimeSPOT.

First of all, each component is typically programmed in an individual Javaclass. This makes it difficult to maintain an overview on a large WSN application(i.e., an application consisting of several components). For instance, to find outwhich components interact with each other, a programmer carefully has to gothrough each individual class to inspect the interaction rules that were addedto the CrimeSPOT runtime.

Second, while (nearly) identical interaction rules, event-fact mappings, andmeta-facts are often required in multiple components of the same or differentWSN applications, they cannot be reused through any other means than codeduplication.

Inspired by the state of the art presented in Chapter 2, we decided to tacklethese shortcomings by extending node-centric CrimeSPOT with a network-centric variant. Concretely, we extended CrimeSPOT with a macroprogram-ming language, dubbed Macro-CrimeSPOT, in which CrimeSPOT com-ponents can be programmed from a network-level perspective and in whichmeans for code reuse are provided. Macro-CrimeSPOT comes with a precom-piler, which compiles the macro-code to node-level code. When using Macro-CrimeSPOT, the application code is no longer cluttered with Java statements(e.g., to install CrimeSPOT expressions) and a lucid view on the entire WSNapplication is maintained. As a result, the interactions among the componentsbecome clearer and possible opportunities for code reuse become apparent.

In this chapter, we introduce Macro-CrimeSPOT and its accompanying

62

Page 75: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

CHAPTER 4. NETWORK-CENTRIC PROGRAMMINGWITHMACRO-CRIMESPOT63

precompiler, and discuss the final implementation of our running example.

4.1 Grammar

Figure 4.1 gives an overview of the Macro-CrimeSPOT language. It depictsthe language’s grammar using a Backus Naur Form notation extended with largesquare brackets to depict optional items and large parenthesis suffixed with anasterisk to depict zero or more repetitions. Note that <cs expression> refers to

�application� ::= (�component block�)*�component block� ::= �quantifier� �code block��quantifier� ::= * | �name� (, �name�)*�code block� ::= �crimespot block� | �java block��crimespot block� ::= { �crimespot code� }�java block� ::= :java { �java code� }�crimespot code� ::= (�cs expression�. | �mcs expression�)*�mcs expression� ::= defvar �meta-var�: �meta-var-value�.

| defmacro �name�( [ �meta-var� (, �meta-var�)* ] ): �cs expression�.| �macro�.| import!("�library file path�").

�meta-var� ::= $�name��macro� ::= �name�( [ �meta-var-value� (, �meta-var-value�)* ] )

�library file path� ::= �text��library� ::= �crimespot code��name� ::= �text�

Figure 4.1: Macro-CrimeSPOT Grammar

<expr> from the CrimeSPOT grammar, which was depicted in Figure 3.8. AMacro-CrimeSPOT application can be written in a text file and compiled bythe precompiler, which generates the node-level Java code for the application’scomponents. In the following sections, we will introduce all language featuresshown in the grammar.

4.2 Grouping the Components of a WSN Application

The code base of a CrimeSPOT WSN application is typically small. Each com-ponent is written in a Java class and consists of only a few event-fact mappings,meta-facts, interaction rules and Java methods. Hence, a straightforward wayto switch to the network-level perspective is by collecting the code concerninga single application in one source file.

In Macro-CrimeSPOT, every application is represented as a single filecontaining blocks of code for each component. There are two kinds of blocks:blocks that group the CrimeSPOT expressions governing a component’s in-teractions, and blocks that group the Java code implementing a component’s

Page 76: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

CHAPTER 4. NETWORK-CENTRIC PROGRAMMINGWITHMACRO-CRIMESPOT64

application logic. To introduce the syntax, Listing 4.1 depicts an example ap-plication consisting of two components.

1 TemperatureSensor {

2 online(Tent = ?t, Component = ‘TemperatureSensor)@[to(MAC=any),

3 factExpires(Seconds =3600)]

4 <- ?t is getTentBasedOnGPSReading ()@[renewEvery(Seconds =3600)].

56 temperatureReading(Celsius = ?temp)@[to(MAC=any),

7 factExpires(Seconds = 600)]

8 <- ?temp is getTemperature ()@[renewEvery(Seconds = 600)].

9 }

1011 HumiditySensor {

12 // publish online and humidityReading facts

13 }

Listing 4.1: Macro-CrimeSPOT syntax

Note that each block is delimited by curly braces and preceded by a quanti-fier. This quantifier indicates the component to which the code from withinthe corresponding block should be added. In this example, the blocks groupthe CrimeSPOT expressions for the TemperatureSensor - and HumiditySensorcomponents from our running example.

As it’s often required to introduce rules that invoke application logic, and tospecify their corresponding application logic in Java, every quantifier can alsotake the :java suffix to indicate that the corresponding block’s content is plainJava code. To illustrate this, we can reconsider the HeatingController compo-nent from our running example. This component reacts to adjustHeating factsand steers its associated heater accordingly. Its partial macro-implementationis given below.

1 HeatingController {

2 // ...

3 this.adjustHeater

4 <- adjustHeating(Level = ?h).

5 }

6 HeatingController:java {

7 private Action adjustHeater = new Action () {

8 public void activated(TypedObject args) { ... }

9 public void deactivate(TypedObject args) { ... }

10 };

11 }

Listing 4.2: Implementing the HeatingController in Macro-CrimeSPOT

The precompiler will add all Java code to the component’s Java class withoutfurther processing. Note that the Java variable bound to the instance of theabstract Action type is accessible from within the interaction rule’s head byprefixing it with this.

4.2.1 Quantifying over Multiple Components

When considering the code from Listing 4.1, opportunities for code reuse alreadybecome apparent. Since both the TemperatureSensor and HumiditySensor com-ponents publish their presence using an online fact, the corresponding inter-action rule could just be added to each component by the precompiler ratherthan manually duplicating it. To this end, Macro-CrimeSPOT allows the

Page 77: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

CHAPTER 4. NETWORK-CENTRIC PROGRAMMINGWITHMACRO-CRIMESPOT65

programmer to quantify code blocks over multiple components. Such quantifi-cation can be achieved by either listing multiple component names as a block’squantifier, or by using the universal * quantifier.

The use of the universal * quantifier is illustrated in Listing 4.3. Whenthis quantifier is used, the precompiler will add all code specified within thecorresponding block to each component in the application.

1 * {

2 online(Tent = ?t, Component = ‘$COMPONENT_NAME)@[to(MAC=any),

3 factExpires(Seconds =3600)]

4 <- ?t is getTentBasedOnGPSReading ()@[renewEvery(Seconds =3600)].

5 }

67 *:java {

8 private Attribute getTentBasedOnGPSReading () { ... }

9 }

1011 TemperatureSensor { /* publish temperature readings */ }

12 HumiditySensor { /* publish humidity readings */ }

Listing 4.3: Illustrating the universal quantifier

For this example, the same behavior could be obtained by using TemperatureSensor,

HumiditySensor as the blocks’ quantifier. Listing destination components isespecially useful in applications with multiple components where specific codeshould be added to some, but not all, components.

4.2.2 Using Meta-Variables in CrimeSPOT Expressions

When developing an application using Macro-CrimeSPOT, the programmercan employ meta-variables in her CrimeSPOT expressions. Unlike CrimeSPOT’svariables, Macro-CrimeSPOT’s meta-variables are only valid at compile-timeand will be substituted by their value by the precompiler. Meta-variables areprefixed by a $ sign and are either predefined by the precompiler, or defined bythe programmer in the scope of a particular component.

Within a CrimeSPOT code block, the programmer can use the predefined$COMPONENT NAME meta-variable wherever the component’s name is expected.This is often useful when quantifying over multiple components. For instance,in Listing 4.3, the online fact published by a component has to contain thecomponent’s name, which is therefore represented by $COMPONENT NAME.

Other meta-variables can also be introduced by the programmer. This is,for instance, useful when dealing with several sensing components which publishfacts at set intervals. To configure such an interval for the entire application,the defvar statement can be used within a universally quantified CrimeSPOTblock to bind the interval to a meta-variable.

1 * {

2 defvar $publicationInterval: Seconds = 600.

3 }

When using the above code in combination with the TemperatureSensor andHumiditySensor components from Listing 4.1, the explicit intervals in thesecomponents’ code can be replaced by the $publicationInterval meta-variable.As such, the application becomes easier to reconfigure.

In general, meta-variables and their definitions can only be used withinCrimeSPOT code blocks. The meta-variables can be bound to any textual

Page 78: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

CHAPTER 4. NETWORK-CENTRIC PROGRAMMINGWITHMACRO-CRIMESPOT66

expression without dots, in which commas appear only within balanced paren-theses or brackets. Typically, meta-variables are used for representing very smallsnippets of CrimeSPOT code.

4.2.3 Abstracting CrimeSPOT Expressions

While the possibility to quantify code blocks over multiple components allowsto implicitly reuse code in certain components, any full-fledged CrimeSPOTexpression can also be reused by abstracting it as a macro and explicitly referringto it from within a CrimeSPOT code block.

As an example, we can consider a macro for reusing an event-fact mappingfor temperature readings. If we assume that the $publicationInterval meta-variable is bound where the macro will be used1, the macro-definition fromListing 4.4 can be used for this purpose.

1 * {

2 defmacro temperatureMapping ():

3 mapping temperatureReading(Celsius =?temp)@[factExpires($publicationInterval )]

4 <=> Event_101(Integer =?temp).

5 }

Listing 4.4: Macro for the temperature event-fact mapping

Because the macro is defined in a universally quantified code block, its definitionis available to all components. They can refer to the macro as follows:

1 temperatureMapping ().

Whenever the precompiler encounters a macro-name within a CrimeSPOTcode block, it will expand the macro as specified in its definition. Since inour running example, only the TemperatureSensor and ComfortLevelMonitorcomponents employ temperature readings, this macro can be used in exactlythose components.

If we further reconsider our running example, another useful macro wouldrepresent the interaction rule for publishing the online facts. Since only theTemperatureSensor, HumiditySensor and HeatingController components shouldpublish such facts, this macro could be used in exactly those components. Apossible macro-definition is given in Listing 4.5. This macro takes the $time

meta-variable as an argument.

1 * {

2 defmacro publishPresenceEvery($time):

3 online(Tent = ?tnt , Component = ‘$COMPONENT_NAME)@[to(MAC=any),

4 factExpires($time)]

5 <- ?tnt is getTentBasedOnGPSReading ()@[renewEvery($time )].

6 }

Listing 4.5: Macro for publishing a component’s presence

In general, a macro can take any number of meta-variables as arguments forwhich the values have to be passed whenever the macro is used. As such,expanding a macro also binds meta-variables, but only during this expansion.For instance, the code below can be added to any component to publish anonline fact every hour.

1 publishPresenceEvery(Seconds =3600).

1Our macros are dynamically scoped.

Page 79: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

CHAPTER 4. NETWORK-CENTRIC PROGRAMMINGWITHMACRO-CRIMESPOT67

4.2.4 Organizing Abstract CrimeSPOT Expressions intoLibraries

Finally, we also allow CrimeSPOT expressions and macro- and meta-variabledefinitions to be stored in external files or libraries. Such a library can beimported from within a CrimeSPOT code block using the import! statementas shown below.

1 import !("/path/to/library.mcs").

The precompiler will substitute this statement by the imported library’s con-tents. By providing this feature, our macroprogramming language allows toeasily reuse code among various WSN applications (e.g., a library with generalmacro-definitions or a full-fledged component extension).

4.3 Compiling Macro-Code

As mentioned before, Macro-CrimeSPOT comes with a precompiler thatcompiles the macro-code to node-level Java code for each component. Ourimplementation’s source code can be found online2. While our precompilertargets CrimeSPOT on the SunSPOT platform with the LooCI event-basedcomponent middleware, it could easily be adapted to target any other platform.Figure 4.2 gives an overview of how the precompiler works.

Figure 4.2: Macro-CrimeSPOT Precompiler

As can be observed, compiling macro-code is quite straightforward and typ-ically a three phase process.

In the first phase, the Macro-CrimeSPOT source is parsed to extract theindividual components’ CrimeSPOT- and Java code blocks. In case certaincode blocks were quantified over multiple components, the contents of theseblocks will be added to the corresponding blocks of the individual components.

In the second phase, every component is individually processed. ItsCrimeSPOT code block is parsed to detect errors in the expressions3 and todo macro-expansions, imports, and meta-variable substitutions. In addition, allmethods invoked from within the component’s interaction rules are detected andthe dispatcher method (cfr. Section A.4) is dynamically generated. To end this

2http://soft.vub.ac.be/amop/crime/sunspot3Since all CrimeSPOT expressions are installed at runtime, this error detection makes sure

that all possible errors are detected at compile-time.

Page 80: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

CHAPTER 4. NETWORK-CENTRIC PROGRAMMINGWITHMACRO-CRIMESPOT68

phase, the required Java statements to install the CrimeSPOT expressions aregenerated and all Java code is merged in a full-fledged Sun SPOT Applicationfor the component.

The third phase is optional. In case the components’ node-level Java codedoesn’t have to be refined, the precompiler can produce a JAR for every compo-nent, which is ready for deployment on WSN nodes using LooCI’s over-the-airdeployment tools.

4.4 Revisiting the Running Example

Having introduced Macro-CrimeSPOT, we will now illustrate its use by re-visiting the running example from a network-perspective. The running examplewas explained in Section 3.1 and concerns a wireless sensor network applicationfor controlling the heating and logging the comfort levels of festival tents. Sinceall Java code has already been shown, we won’t discuss the Java code blocks forbrevity.

Listing 4.6 shows the application’s universally quantified code block,which provides the code to be added to each application component.

1 * {

2 import !("mappings -library.mcs").

34 defvar $readingPublicationInterval: Seconds = 600.

5 defvar $onlinePublicationInterval: Seconds = 3600.

67 defmacro publishPresenceEvery($time):

8 online(Tent = ?tnt , Component = ‘$COMPONENT_NAME)@[to(MAC=any),

9 factExpires($time)]

10 <- ?tnt is getTentBasedOnGPSReading ()@[renewEvery($time )].

1112 defmacro newReadingSubsumesOlderFromSameTent($reading , $type):

13 subsumes !( Incoming= $reading($type = ?new)@[from(MAC=?mac)],

14 Fact=$reading($type = ?old)@[from(MAC=? othermac)],

15 When=[ online(Tent = ?tnt)@[from(MAC=?mac)],

16 online(Tent = ?tnt)@[from(MAC=? othermac )]]).

17 }

Listing 4.6: Running Example - Universally quantified code block

Since event-fact mappings are used in various WSN applications, the defaultones have been put in a library that is imported in this application (line 2).As shown in Listing 4.7, this library contains two interesting macros, namelytemperatureMapping($factExp) and humidityMapping($factExp), which pro-vide exactly the event-fact mappings required for this application.

1 defmacro temperatureMapping($factExp ):

2 mapping temperatureReading(Celsius =?temp)@[factExpires($factExp )]

3 <=> Event_101(Integer =?temp).

45 defmacro humidityMapping($factExp ):

6 mapping humidityReading(Percent =?h)@[factExpires($factExp )]

7 <=> Event_102(Integer =?h).

89 // ...

Listing 4.7: Running Example - Event-Fact Mappings Library

Page 81: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

CHAPTER 4. NETWORK-CENTRIC PROGRAMMINGWITHMACRO-CRIMESPOT69

Next to importing the library, two meta-variables and two application-specificmacros are defined. While the meta-variables configure the time intervals rele-vant to this application, the macros define some reusable code. For instance, thenewReadingSubsumesOlderFromSameTent($reading, $type) macro can be usedto install a subsumption meta-fact which specifies that a new $reading fact froma certain tent subsumes all older $reading facts from the same tent.

The implementation for the sensing components and the HeatingCon-troller component is shown in Listing 4.8. Compared to the implementationgiven earlier, the required event-fact mappings are now installed using the li-brary macros (lines 19, 28) and the interaction rule for publishing the online

fact is installed using the publishPresenceEvery macro (lines 20, 29, 37).

18 TemperatureSensor {

19 temperatureMapping($readingPublicationInterval ).

20 publishPresenceEvery($onlinePublicationInterval ).

2122 temperatureReading(Celsius = ?temp)@[to(MAC=any),

23 factExpires($readingPublicationInterval )]

24 <- ?temp is getTemperature ()@[renewEvery($readingPublicationInterval )].

25 }

2627 HumiditySensor {

28 humidityMapping($readingPublicationInterval ).

29 publishPresenceEvery($onlinePublicationInterval ).

3031 humidityReading(Percent = ?p)@[to(MAC=any),

32 factExpires($readingPublicationInterval )]

33 <- ?p is getHumidity ()@[renewEvery($readingPublicationInterval )].

34 }

3536 HeatingController {

37 publishPresenceEvery($onlinePublicationInterval ).

3839 subsumes !( Incoming=adjustHeating(Level = ?new),

40 Fact=adjustHeating(Level = ?old)).

4142 this.adjustHeater

43 <- adjustHeating(Level = ?h).

44 }

Listing 4.8: Running Example - Sensor- and HeatingController components

In addition, the interaction rules for publishing the sensed readings now em-ploy the $readingPublicationInterval meta-variable to specify the intervalat which the readings should be published. Because a published sensor readingfact expires just before a new sensor measurement is taken, no retraction eventshave to be published on the underlying event-bus when these interaction rulesare triggered4.

45 ComfortLevelMonitor {

46 temperatureMapping($readingPublicationInterval ).

47 humidityMapping($readingPublicationInterval ).

4849 subsumes !( Incoming=online(Tent = ?tnt , Component = ?c)@[from(MAC=?m)],

50 Fact=online(Tent = ?otnt , Component = ?c)@[from(MAC=?m)]).

51

4In case the published fact had not expired at the time a new match for the is-operatoris obtained and the old one consequentially becomes invalid, a retraction for the fact wouldhave to be published because the interaction rule got deactivated for the invalidated match.

Page 82: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

CHAPTER 4. NETWORK-CENTRIC PROGRAMMINGWITHMACRO-CRIMESPOT70

52 newReadingSubsumesOlderFromSameTent(humidityReading , Percent ).

53 newReadingSubsumesOlderFromSameTent(temperatureReading , Celsius ).

5455 this.logComfortLevel

56 <- humidityReading(Percent = ?h)@[from(MAC=?hm, ID=?hi)],

57 temperatureReading(Celsius = ?t)@[from(MAC=?tm, ID=?ti)],

58 online(Tent = ?tnt)@[from(MAC = ?hm , ID = ?hi)],

59 online(Tent = ?tnt)@[from(MAC = ?tm , ID = ?ti)].

6061 adjustHeating(Level = ?heatingLevel)@[to(MAC=?hcm , ID=?hci),

62 factExpires($readingPublicationInterval )]

63 <- temperatureReading(Celsius = ?t)@[from(MAC=?tm , ID=?ti)],

64 online(Tent = ?tnt)@[from(MAC = ?tm , ID = ?ti)],

65 ?heatingLevel is computeHeatingLevel (( Number )?t),

66 online(Component = ‘HeatingController ,

67 Tent = ?tnt)@[from(MAC = ?hcm , ID=?hci)].

68 }

Listing 4.9: Running Example - ComfortLevelMonitor component

Listing 4.9 shows the implementation for the ComfortLevelMonitor com-ponent and concludes the macro-implementation of our running example. Com-pared to the implementation given earlier, the ComfortLevelMonitor compo-nent now uses the application’s configuration meta-variables, the mapping li-brary macros, and the newReadingSubsumesOlderFromSameTent macro to reuseas much code as possible. In addition, the preprocessing rules for assertingtemperatureInTent and humidityInTent facts are no longer used. As can beobserved, the CrimeSPOT expressions for the entire WSN application roughlyconsume only 68 source lines of code (i.e., excluding the mappings library).

4.5 Conclusion

This chapter introduced Macro-CrimeSPOT, our macroprogramming lan-guage for programming WSN applications using CrimeSPOT from a network-level perspective. For shifting to a network-level perspective, Macro-CrimeSPOTmerges all components’ code in a single source file per application. However, asWSN components are typically small, this merging doesn’t result in huge sourcefiles. On the contrary, it results in clearer code in which a lucid view on theentire WSN application is retained.

Next to the ability of programming an entire WSN application from anetwork-level perspective, Macro-CrimeSPOT also provides the programmerwith means to reuse code and thereby avoid code duplication. While componentquantification, meta-variables and macros can be used to reuse code within asingle WSN application, code can also be imported from libraries and therebyreused over various applications.

The next chapter will validate both CrimeSPOT and Macro-CrimeSPOTthrough some additional illustrative examples.

Page 83: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

5Validation

To validate both CrimeSPOT and Macro-CrimeSPOT, this chapter dis-cusses the implementation of illustrative example applications. Afterwards, wesummarize the discussed applications’ statistics to evaluate the expressivenessof our language.

5.1 Illustrative Examples

Wireless sensor networks are used for a plethora of applications. Some ex-amples are monitoring applications (e.g., monitoring habitats [5], zebras [6] andglaciers [7]), emergency detection applications (e.g., detecting intrusions [8], for-est fires [9] and flooding rivers [10]), and more active applications like controllingheating- and air conditioning systems [11]. In this section, we will discuss someof these applications together with their Macro-CrimeSPOT implementationto demonstrate the expressiveness of our solution.

5.1.1 Fire Detection

As illustrated in Figure 5.1, an application for detecting and fighting fire requirestwo types of WSN nodes: smoke detectors (D), which have a smoke sensorand publish smoke detection events, and controllers (C), which each monitora certain region and turn on their associated sprinklers, alarms and emergencyexit lights in case a fire is detected. The arrows in the Figure illustrate thenode interactions in a particular region. After a controller informs its smokedetectors that they’re within its region, the smoke detectors will publish theirevents to that controller.

5.1.1.1 Implementation

For each type of WSN node, a component can be developed and afterwardsdeployed on the corresponding nodes. As shown below, we start the development

71

Page 84: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

CHAPTER 5. VALIDATION 72

Fire Detection Region

D

D D

D

C

Figure 5.1: A Wireless Sensor Network application for detecting and fighting fire

by defining some meta-variables in the universally quantified code block toconfigure the application.

1 * {

2 defvar $detectionInterval: Seconds =60.

3 defvar $alarmThreshold: 2.

4 }

While the $detectionInterval configures the interval between every two sub-sequent smoke sensor readouts, the $alarmThreshold configures the amount ofsensors that have to detect smoke in a region before the controller will soundthe alarm.

A Controller component participates in two interactions. After informingits region’s smoke detectors, it listens for their smoke facts to detect fire. Itsimplementation is given below.

5 Controller {

6 mySensor(MAC="MAC1").

7 mySensor(MAC="MAC2").

8 mySensor(MAC="MACn").

910 itsController ()@[to(MAC=? sensorMAC )]

11 <- mySensor(MAC=? sensorMAC ).

1213 this.respond

14 <- findall (?m,

15 [smoke()@[from(MAC=?m)]],

16 ?alarmingSensors),

17 length (? alarmingSensors , ?l),

18 ?l > $alarmThreshold.

19 }

2021 Controller:java {

22 private Action respond = new Action () {

23 public void activated(TypedObject arguments) {

24 // turn on the sprinklers , alarms , and emergency exit lights

25 }

26 public void deactivate(TypedObject arguments) {

27 // turn off the sprinklers , alarms , and emergency exit lights

28 }

29 };

30 }

Page 85: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

CHAPTER 5. VALIDATION 73

Note that the mySensor facts are statically added to the Controller’s Fact Baseto configure its region (lines 6-8)1. The presence of these facts will activatethe first interaction rule, which will configure the listed smoke detectors to sendtheir facts to the controller (lines 10-12). To this end, the Controller sends theman itsController fact which includes its MAC address2.

The second interaction rule is used for detecting and reacting to fire (lines13-18). It explicitly states when the Controller should respond; i.e., whenevermore than $alarmThreshold smoke facts have been received and are still valid.The response itself is defined in the implementation for the respond Actioninstance (lines 22-29). Whenever the rule is activated, the controller will turnon its sprinklers, alarms, and emergency exit lights, and conversely, wheneverthe rule gets deactivated, it will turn them off.

The remaining Smoke Detector component can be defined using thesingle interaction rule shown below.

31 SmokeDetector {

32 smoke()@[to(MAC=?mac), factExpires($detectionInterval )]

33 <- itsController ()@[from(MAC=?mac)],

34 ‘true is smokeDetected ()@[renewEvery($detectionInterval )].

35 }

3637 SmokeDetector:java {

38 private Attribute smokeDetected () { /* read out smoke sensor */ }

39 }

As soon as an itsController fact has been received, the smoke detector is con-figured and will query its sensor at intervals specified by the $detectionIntervalmeta-variable (line 34). Upon smoke detection, it will send a smoke fact to itscontroller. Clearly, a smoke detector can be configured for several controllers,in which case its Fact Base will contain several itsController facts. Conse-quentially, whenever smoke is detected, the interaction rule will be activatedfor every itsController fact and the smoke detector will send a smoke fact toeach controller.

It must be noted that the Smoke Detector can also be implemented as a non-CrimeSPOT, plain event-based component, which might be useful when certainsmoke detector sensor nodes are less powerful or unable to use CrimeSPOTbecause it’s not available on their platform. To this end, the event-based middle-ware should be manually configured such that the plain smoke detectors publishtheir events to the correct controller, and the Controller’s implementation shouldbe augmented with an event-fact mapping to map these events to smoke factsthat can be asserted in its Fact Base. If the smoke events are of type 100 andare published at the same intervals as specified by the $detectionInterval

meta-variable, the following event-fact mapping can be used.

1 mapping smoke()@[factExpires($detectionInterval )]

2 <=> Event_100 ().

1In case several controller components are deployed within the application, every con-troller’s region has to be individually configured. This can, for instance, be done by refiningthe controller’s source code that was produced by the Macro-CrimeSPOT precompiler.

2As explained earlier, a fact’s originating MAC address is implicitly present in its meta-attributes.

Page 86: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

CHAPTER 5. VALIDATION 74

5.1.2 Monitoring Temperatures

Another interesting WSN application monitors the temperature in several re-gions, computes the average temperature in the regions and notifies the regionswith the highest temperature. A possible configuration for this application isdepicted in Figure5.2. The application uses only two components: the Tem-

Figure 5.2: A Wireless Sensor Network application for monitoring temperatures

perature Sensor component (T) has been deployed in all regions and blinks aled when its region has the highest temperature, and the Average Computercomponent (C) is deployed only once to steer the application. In addition, theAverage Computer is connected to a display that outputs the current averagetemperature. While every Temperature Sensor broadcasts its measured temper-ature, the Average Computer sends a notification to the Temperature Sensorsin the regions with the highest temperature.

5.1.2.1 Implementation

The Temperature Sensor component has a simple implementation, whichis shown below.

1 TemperatureSensor {

2 defvar $readingPublicationInterval: Seconds =60.

34 temperatureReading(Celsius = ?temp)@[to(MAC=any),

5 factExpires($readingPublicationInterval )]

6 <- ?temp is getTemperature ()@[renewEvery($readingPublicationInterval )].

78 this.alertMaxTemp

9 <- maximumTemperature ().

10 }

1112 TemperatureSensor:java {

13 private Action alertMaxTemp = new Action () {

14 public void activated(TypedObject args) { /* blink led */ }

15 public void deactivate(TypedObject args) { /* turn off led */ }

16 };

17 }

While the first interaction rule publishes temperatureReading facts at inter-vals specified by the $readingPublicationInterval meta-variable, the secondinteraction rule reacts to the reception of a maximumTemperature fact, which

Page 87: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

CHAPTER 5. VALIDATION 75

indicates that the component is deployed in a region that currently has thehighest measured temperature and should consequentially blink its led.

Even though the implementation for the Average Computer componentis somewhat larger, it’s not necessarily more complex. The implementation isshown below. Next to two interaction rules, the component also requires someadditional Java methods to do its job. However, since these Java methods arestraightforward to implement, only a description of their behavior is given here.

18 AvgComputer {

19 this.outputAverageTemp

20 <- findall (?t, [temperatureReading(Celsius = ?t)], ?temps),

21 ?avgTemp is computeAverage ((List)?temps ).

2223 maximumTemperature(Celsius = ?maxTemp)@[to(MAC=?m)]

24 <- findall (?t, [temperatureReading(Celsius = ?t)], ?temps),

25 ?maxTemp is computeMaximum ((List)?temps),

26 temperatureReading(Celsius =? maxTemp)@[from(MAC=?m)].

27 }

2829 AvgComputer:java {

30 private Action outputAverageTemp = new Action () {

31 public void activated(TypedObject args) {

32 // show args.getValue (" avgTemp ") on the display

33 }

34 public void deactivate(TypedObject args) { /* erase display */ }

35 };

3637 private Attribute computeAverage(List nrLst) {

38 // compute the average Number in the List

39 }

4041 private Attribute computeMaximum(List nrLst) {

42 // compute the maximum Number in the List

43 }

44 }

The first interaction rule computes the average temperature based on the currentvalid readings in the Fact Base. After collecting all temperatures in a List usingthe findall primitive, the average is computed and shown on the display.

The second interaction rule, on the other hand, is used for interacting withthe Temperature Sensor components. Again, all temperature readings are col-lected in a List, but this time, the highest temperature is computed and boundto ?maxTemp. Finally, the last condition of the interaction rule (line 26) uses?maxTemp to obtain the MAC addresses of those Temperature Sensor compo-nents that are deployed in a region that currently has the highest tempera-ture. This interaction rule will be activated for every such component and willconsequentially notify exactly those Temperature Sensors by sending them amaximumTemperature fact.

5.1.3 River Monitoring

In [10], Hughes et al use the LooCI event-based component middleware to deploya river monitoring WSN application, which we have used as an inspiration forthis example. Even though this application doesn’t introduce a lot of newtechniques, it demonstrates a WSN component that publishes sensor readings,but in addition also autonomously acts based on its sensed readings. A possibleconfiguration for this application is shown in Figure5.3. Two components have

Page 88: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

CHAPTER 5. VALIDATION 76

been deployed: the River Monitor (M), which publishes the river’s water level,and the Logger (L), which sends its received data to a connected terminal. Next

Figure 5.3: A Wireless Sensor Network application for monitoring a river

to monitoring the river’s water level, the river monitor component also controlsits associated sluice and detects possible theft attempts.

5.1.3.1 Implementation

Because the Logger component only sends its received data to a terminal byusing interaction rules that invoke application logic, we will not further discussits implementation for brevity.

The implementation of the River Monitor component, which is the mostinteresting one, is shown below. The component is configured with meta-variables that are used in its three interaction rules.

1 Logger { ... }

2 Logger:java { ...}

34 RiverMonitor {

5 defvar $logger: MAC="logger -mac".

6 defvar $verifyRiverLevelInterval: Seconds =600.

7 defvar $floodThreshold: 20.

8 defvar $verifyTheftInterval: Seconds =60.

9 defvar $theftThreshold: 1.

1011 riverLevel(L=?l)@[to($logger),

12 factExpires($verifyRiverLevelInterval )]

13 <- ?l is getRiverLevel ()@[renewEvery($verifyRiverLevelInterval )].

1415 possibleTheft ()@[to($logger )]

16 <- ?a is getAcceleration ()@[renewEvery($verifyTheftInterval )],

17 ?a > $theftThreshold.

1819 this.controlSluice

20 <- ?l is getRiverLevel ()@[renewEvery($verifyRiverLevelInterval )],

21 ?l > $floodThreshold.

22 }

As can be observed, a river monitor only interacts with its logger through thefirst two interaction rules, which are used for sending the measured river levelsand possible theft detections, respectively. To detect a possible theft, the WSNnode’s accelerometer is read every minute to verify whether its value exceeds

Page 89: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

CHAPTER 5. VALIDATION 77

the $theftThreshold. When a possible sensor-theft is detected, the terminalconnected to the logger can, for instance, sound the alarm.

The last interaction rule is used for controlling the sluice when the mea-sured river level rises above the predefined $floodThreshold (e.g., by liftingthe sluice), and when it falls below it afterwards (e.g., by lowering the sluiceagain). Clearly, the river monitor component acts autonomously, as it neverreceives any facts to react upon.

5.1.4 Range Coverage

Finally, we will discuss the implementation of a Range Coverage detection sys-tem [28]. This system can be used to extend a WSN application’s componentsand allow them to individually detect whether their range is covered by othercomponents. A WSN configuration for the bare detection system is shown inFigure5.4. The Range component (R) is deployed on every WSN node and every

Figure 5.4: A Wireless Sensor Network application with range coverage detection

node interacts with every other node by periodically broadcasting its range overthe underlying, decentralized event-bus. This allows every node to individuallydetect whether its range is covered by other nodes. For instance, in the knowl-edge of the other nodes’ ranges from Figure5.4, the green node can detect thatits range is covered by its four adjacent nodes.

5.1.4.1 Implementation

The first part of the Range component’s implementation is straightforwardand shown below.

1 RangeComponent {

2 defvar $rangeBroadcastInterval: Seconds =3600.

34 subsumes !( Incoming=sensorRange(X = ?x, Y = ?y, R = ?r)@[from(MAC=?m)],

5 Fact=sensorRange(X = ?ox, Y = ?oy , R = ?or)@[from(MAC=?m)]).

Page 90: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

CHAPTER 5. VALIDATION 78

67 sensorRange(X = ?x, Y = ?y, R = ?r)@[to(MAC=any),

8 factExpires($rangeBroadcastInterval )]

9 <- ?x is getX()@[renewEvery($rangeBroadcastInterval )],

10 ?y is getY(),

11 ?r is getR ().

The component broadcasts sensorRange facts at intervals specified by the$rangeBroadcastInterval meta-variable. To this end, it obtains its rangethrough the getX(), getY() and getR() methods, whose implementations areoutside the scope of this example. One possible implementation could read outa GPS sensor to obtain these values.

Next to the interaction rule for broadcasting the sensor range, the compo-nent also installed a subsumption meta-fact to make sure that only the lastsensorRange fact from a certain sensor node is kept in its Fact Base. This isimportant because multiple such facts could be received from the same sensornode when multiple range components have been deployed on it.

The remaining part of the implementation is concerned with detecting rangecoverage based on the sensorRange facts in the Fact Base. It is shown below.

12 defmacro verifyPartialCoverage($verificationMethod , $factToAssert ):

13 $factToAssert(byMAC=?m)

14 <- sensorRange(X = ?x, Y = ?y, R = ?r)@[from(MAC=?m)],

15 ?myMAC is getMAC(), ?m != ?myMAC ,

16 ‘true is $verificationMethod (( Number )?x, (Number )?y, (Number )?r).

1718 verifyPartialCoverage(coversTopLeft ,topLeftIsCovered ).

19 verifyPartialCoverage(coversTopRight ,topRightIsCovered ).

20 verifyPartialCoverage(coversBottomLeft ,bottomLeftIsCovered ).

21 verifyPartialCoverage(coversBottomRight ,bottomRightIsCovered ).

2223 myRangeIsCovered(TL=?tlm , TR=?trm , BL=?blm , BR=?brm)

24 <- topLeftIsCovered(byMAC =?tlm),

25 topRightIsCovered(byMAC=?trm),

26 bottomLeftIsCovered(byMAC=?blm),

27 bottomRightIsCovered(byMAC=?brm).

28 }

2930 RangeComponent:java {

31 private Attribute coversTopLeft(Number x, Number y, Number r) {

32 int myTLMinX = getXCoordinate () - getRadius ();

33 int myTLMinY = getYCoordinate ();

34 int myTLMaxX = getXCoordinate ();

35 int myTLMaxY = getYCoordinate () + getRadius ();

3637 if(covers(x.getValue(), y.getValue(), r.getValue(),

38 myTLMinX , myTLMinY , myTLMaxX , myTLMaxY ))

39 return ExpressionFactory.symbol("true");

40 else

41 return ExpressionFactory.symbol("false");

42 }

43 private boolean covers(int x, int y, int r,

44 int bbMinX , int bbMinY ,

45 int bbMaxX , int bbMaxY) {

46 int obbMinX = x - r;

47 int obbMinY = y - r;

48 int obbMaxX = x + r;

49 int obbMaxY = y + r;

5051 return obbMinX <= bbMinX && obbMinY <= bbMinY

Page 91: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

CHAPTER 5. VALIDATION 79

52 && obbMaxX >= bbMaxX && obbMaxY >= bbMaxY;

53 }

54 ...

55 }

As expressed in the rule on lines 23-27, a component’s range coverage is detectedby splitting its range in four parts (i.e., top- and bottom left and right) andverifying whether each of these parts is covered by any other component. Forevery possible covering of a component’s range, a myRangeIsCovered fact isasserted in the Fact Base, which can be reacted to by an application-specificrule. For instance, in case a component’s range is covered, it can choose dropcertain facts to lower its processing load.

Verifying the coverage of each partial range is done by using theverifyPartialCoverage macro on lines 18-21. This macro expands to arule for verifying a specific partial range’s coverage. For instance, thefirst macro usage (line 18) expands to a rule for verifying whether thetop left part of the component’s range is covered. To verify this cover-age, the rule will invoke the coversTopLeft(Number,Number,Number) methodwith the data of each sensorRange()@[from(MAC=?m)] fact, and will assert atopLeftIsCovered(byMAC=?m) fact for every sensor node covering this compo-nent’s top left partial range. Conversely, these facts are retracted when thepartial range is no longer covered.

The Java methods for verifying the top left partial range coverage areincluded on lines 31-53. The implementation is straightforward: for both thecomponent’s top left partial range and the range to verify, a bounding boxis created, and the method checks whether the component’s bounding box isincluded in the other bounding box. If this is the case, the top left partialrange is covered.

To extend another WSN application with this range coverage system,the code from lines 3 to 27 should be stored in a library and imported in thecomponents to be extended as illustrated below. Because the range compo-nent’s Java code cannot be part of the library, it should be added manually tothe extended components’ Java code blocks. However, this allows to specify anapplication-specific implementation for the required Java methods.

1 AnyComponent {

2 defvar $rangeBroadcastInterval: Seconds=n.

3 import !("/path/to/rangecoverage.mcs").

45 // other logic

6 }

7 AnyComponent:java {

8 // application -specific range coverage logic

910 // other logic

11 }

After successfully importing the range coverage system, the extended compo-nents can now use the myRangeIsCovered fact from their Fact Base, knowingthat it will be present whenever other components cover their range.

Page 92: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

CHAPTER 5. VALIDATION 80

5.2 Expressiveness

Having explained several illustrative example applications, we will now discussthe expressiveness of the CrimeSPOT language. Even though it’s difficult tomeasure expressiveness, we made an attempt by analyzing the statistics of ourexample applications. These statistics are presented in Tables 5.1 and 5.2.

Components Macros Meta-VarsRunning Example 4 4 2Fire Detection 2 0 2Temperature Monitoring 2 0 1River Monitoring 2 0 5Range Coverage 1 1 1Average/Application 2,2 1 2,2

Table 5.1: Example Applications: General Statistics

Mappings Meta-Facts Rules Java MethodsRunning Example 4 4 10 6Fire Detection 1 0 3 3Temperature Monitoring 0 0 4 6River Monitoring 0 0 5 7Range Coverage 0 1 6 7Average/Component1 0,3 0,4 2,9 3,3

Table 5.2: Example Applications: Total Component Code

As can be observed in Table 5.2, the average CrimeSPOT component has0, 3 event-fact mappings, 0, 4 meta-facts, 2, 9 rules, and 3, 3 Java methods, whichcorresponds to a relatively small amount of source lines of code. While thesenumbers are quite application-specific, we believe that they give a fair indica-tion of the expressiveness of our language. Implementing the same behavior inplain Java on top of event-based middleware would imply a substantial increasein component code. Such an ad-hoc implementation requires code for eventdispatching, event storage and management and event matching. Worse, thiscode would be tangled with the component’s application logic, rendering thelatter less clear and adaptable. Furthermore, it would be duplicated across eachcomponent.

Complementary to the statistics relevant to CrimeSPOT, Table 5.1 presentsgeneral statistics relevant to Macro-CrimeSPOT. The average amount ofcomponents per application is 2, 2 and the example applications used at most4 macro-definitions and 5 meta-variables. Obviously, using macro-definitionsprovides an increasing benefit as the number of developed components growsand more code can be reused. Analogously, the benefit of using application-levelCrimeSPOT- and Java code (i.e., CrimeSPOT- and Java code to be added toseveral components in the application; specified by quantifying a code block overmultiple components) increases as the number of components in an application

1This average was computed by first taking the average per application and afterwardsaveraging over the applications.

Page 93: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

CHAPTER 5. VALIDATION 81

grows. On the other hand, a larger number of components per application mightrender Macro-CrimeSPOT’s approach of centralized programming less usefulas an application’s source file would become larger. We plan to investigate howwe can better modularize this code in future work.

5.3 Conclusion

This chapter validated the CrimeSPOT and Macro-CrimeSPOT program-ming languages through the implementation of illustrative example applica-tions. As could be observed, developing WSN applications using Macro-CrimeSPOT is quite straightforward. Making a component participate in aninteraction is as simple as adding a new interaction rule to its Rule Base. Fur-thermore, when compared to implementing an event handler to react to events,the interaction rules scale very well while keeping the application logic uncom-plicated.

Next to the interaction rules, the facts also alleviate a developer’s worksignificantly. A developer no longer has to manually store or remove events. Itsuffices to specify how events are reified as facts and which facts subsume whichother facts, and CrimeSPOT will take care of the rest. As required, facts willbe asserted in and retracted from the Fact Base, and interaction rules will beactivated and deactivated.

Appendix B further evaluates our CrimeSPOT prototype implementationin terms of memory footprint, network overhead and performance. The nextchapter will conclude this dissertation by discussing its contributions and futurework.

Page 94: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

6Conclusion

Sense-and-react applications are an emerging breed of wireless sensor networkapplications in which certain nodes steer actuators and the processing of sensordata is typically moved inside the network. The development of these applica-tions requires a high degree of control over the individual nodes and support forprogramming these nodes’ interactions.

This dissertation described our work carried out in the domain of wirelesssensor networks. The main objective of this work was to provide language sup-port for programming interactions among WSN nodes to complement existingnode-centric programming models. As illustrated in Chapter 2, most contem-porary node-centric programming models do not help in processing data uponreception. Instead, they typically force the programmer to process this data inan event handler, even though event handlers have already been shown to violateseveral software engineering principles, including composability, scalability andseparation of concerns [12]. One exception is FACTS, which allows the use ofdeclarative rules for specifying interactions among WSN nodes. This approachwas an inspiration for the CrimeSPOT language that was presented in thefirst part of this thesis (cfr. Chapter 3). Next to presenting the CrimeSPOTlanguage, we also implemented a runtime prototype as a proof of concept (cfr.Appendix A) and presented a preliminary evaluation of its overhead (cfr. Ap-pendix B).

The second part of this thesis focussed on a network-centric programmingapproach. Inspired by the state of the art, we extended CrimeSPOT with anetwork-centric variant, dubbed Macro-CrimeSPOT, which provides facilitiesfor code reuse within and among WSN applications. As a proof of concept, weimplemented a precompiler for compiling Macro-CrimeSPOT code to node-level CrimeSPOT code that targets our runtime prototype (cfr. Chapter 4).

In the last part of this thesis, both CrimeSPOT and Macro-CrimeSPOTwere validated through illustrative examples (cfr. Chapter 5).

82

Page 95: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

CHAPTER 6. CONCLUSION 83

6.1 Contributions

The main contributions of this dissertation are:

• The introduction of the CrimeSPOT node-centric programming languagethat advocates the use of declarative interaction rules to specify a node’sinteractions.

• The introduction of the Macro-CrimeSPOT network-centric program-ming language and its facilities for code reuse within and among WSNapplications.

• The proof of concept implementations for both the CrimeSPOT runtimeand the Macro-CrimeSPOT precompiler.

• Extensions to the well-known Rete algorithm to support CrimeSPOT’smeta-facts and time-related functionality (e.g., the expiration of facts andmatches).

The CrimeSPOT language was based on FACTS’ rule-based approach, whichwas described in Chapter 2 and the CrimeSPOT runtime prototype reusedparts of CRIME’s implementation, as described in Appendix A.

However, CrimeSPOT is significantly different from FACTS. The only as-pect both approaches have in common is the use of declarative rules to specifya node’s interactions. The major features present in CrimeSPOT but missingin FACTS are: the ability to use variables in interaction rules, thereby allowinga sensor node to react to several related facts, and the ability for a sensor nodeto react to the invalidation of an interaction rule’s conditions.

Furthermore, CRIME’s implementation did not readily translate to the set-ting of wireless sensor networks. As discussed in Appendix A, CRIME onlyprovided an initial implementation for CrimeSPOT’s Inference Layer. Thisimplementation was entirely ported to the SunSPOT platform and was more-over adapted to support, amongst others: CrimeSPOT’s time-related func-tionality (e.g., the expiration of facts and matches), the invocation of methodsfrom within a rule’s body and the association of meta-attributes with facts.

6.2 Future Work

There are several opportunities to improve on our work:

• Extending the CrimeSPOT language

– Fact Base Sharing: While CrimeSPOT targets event-based com-ponent middleware, it offers no facilities to share a Fact Base amongall components on the same node. As such sharing might facilitatethe interactions between node-local components, it might be inter-esting to further investigate this feature.

– Rule Priorities: Currently, the programmer is given only limitedcontrol over the interaction rules’ priorities. When triggered, inter-action rules are processed in their installation order. More controlover these priorities can, for instance, be given to the programmerby allowing to associate explicit priorities with rules.

Page 96: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

CHAPTER 6. CONCLUSION 84

– Control over the truth maintenance system: Due toCrimeSPOT’s truth maintenance behavior, every rule is deactivatedwhen it loses a match. While this causes no issues for rules with anAction in their head, it might for rules with a fact in their head. Forthe latter, the programmer is given no control over the behavior thatcorresponds to the deactivation of the rule; the fact that was assertedearlier will simply be retracted. As this is not always the desired be-havior, it might be useful to allow a programmer to disable the truthmaintenance for certain rules. An example of a rule for which thiswould be appropriate is one that reacts to getTemperature requestsby publishing a temperature fact. While the fact representing therequest should be short-living, the answered temperature fact shouldnot be retracted when the request expires.

– Fact Consumption: While currently unsupported, it might be in-teresting to investigate how a rule can consume facts matching itsconditions (i.e., hide them from other rules). One idea is to intro-duce a special consume meta-attribute for logical conditions. Thismeta-attribute can then specify that a fact matching the conditionis consumed by the rule either as soon as it matched the condition,or as soon as the rule was triggered.

– Context-aware rules and meta-facts: Certain rules or meta-factsmight be context-aware, meaning that they should only be activewhen a certain condition holds. To support such context-aware rulesor meta-facts, an additional body can be introduced for specifying theconditions for the rules or meta-facts to be active. As an example ofa context-aware meta-fact, consider one specifying that certain factsshould be dropped upon reception only if these facts will be processedby other nodes in the WSN.

– Fact publication in the n-hop neighborhood: Currently,CrimeSPOT does not offer facilities to publish a fact in a node’sphysical n-hop neighborhood. The publication of facts carrying theto(MAC=any) meta-attribute is assumed to be network-wide. Eventhough the scope of fact publication highly depends on the underlyingevent-based middleware’s capabilities, it might be interesting to in-vestigate how CrimeSPOT can incorporate facilities to publish factsin an n-hop neighborhood. Such facilities would allow CrimeSPOTto be used to implement a wider range of applications.

• Default semantics for the CrimeSPOT language: Even though wehave a rationale for the design choices in the current semantics of theCrimeSPOT language, further experiments are required to decide on agood default semantics. For instance, it might be appropriate to publishfacts by default rather than requiring a to meta-attribute to be associatedwith a fact to be published. Another example of discussion is the truthmaintenance behavior, which is currently enabled by default.

Page 97: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

CHAPTER 6. CONCLUSION 85

• Optimizing the CrimeSPOT prototype: As discussed in AppendixB, the CrimeSPOT prototype implementation is not entirely optimizedfor use on WSN nodes with highly-constrained resources. In particular,its memory footprint and performance can be further improved upon. Forthe latter, the scaffolding technique for the Rete algorithm, described byPerlin [39], can be implemented. Concretely, this implies that the causallinks between facts and reactions are kept. When a fact is subsequentlyretracted, it becomes straightforward to identify exactly those reactionsthat need to be undone. As a consequence, facts can be retracted inconstant time because it’s no longer required to propagate a negated tokenthrough the Rete network.

Additionally, a more efficient implementation for the Middleware Bridgecan be built. Concretely, one that implements unicast fact publication byefficiently registering specific LooCI bindings at runtime.

Page 98: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

ACrimeSPOT Prototype Implementation

This appendix will briefly explain the highlights of the CrimeSPOT prototypeimplementation. The prototype is an extension to the CRIME coordinationlanguage [40] and was instantiated on top of the LooCI event-based compo-nent middleware [25] for the SunSPOT platform. As the prototype’s sourcecode is too voluminous to add to this appendix, the reader can consult it on-line1. In the following sections, we will visit all layers of the CrimeSPOTruntime (cfr. Figure 3.3) and conclude with more details on how to implementa CrimeSPOT component that uses the prototype implementation. Note thatsuch a component is the compilation target for the Macro-CrimeSPOT lan-guage.

A.1 Inference Layer

As mentioned before, the Inference Layer consists of the Fact Base, the RuleBase and the Inference Engine. For implementing this layer, we were able toreuse a large part of the CRIME implementation.

A.1.1 The CRIME Inference Engine

CRIME [40] is a logic-based coordination language that allows applications touse logic rules to specify how they should respond to changes in the environment.These changes are modeled by the addition or removal of facts that containcontext information. Because CRIME allows applications to respond to theremoval of facts, it is also a truth maintenance system.

CRIME conceptually stores its facts in a Fact Base and its rules in a RuleBase. CRIME’s Inference Engine (i.e., a Rete [37] forward chaining inferenceengine) evaluates the rules from the Rule Base against the Fact Base wheneverthe latter changes. Because this behavior is exactly what’s required for the

1http://soft.vub.ac.be/amop/crime/sunspot

86

Page 99: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

APPENDIX A. CRIMESPOT PROTOTYPE IMPLEMENTATION 87

CrimeSPOT language (cfr. Section 3.4), CRIME provided a solid basis for theprototype implementation. Next to the Rete implementation, it also providedsome useful constructs that can be used within the rules (i.e., the not, findall,and length operators, cfr. Section 3.7.1.4).

A.1.1.1 The RETE Algorithm

The most relevant part of the CRIME language is its Inference Engine, whichimplements the Rete algorithm [37]. Rete is an efficient forward chaining in-ference algorithm that optimizes its inference process by using a combination ofsmart caching techniques. To illustrate how the algorithm works, we can con-sider the CRIME rule from Listing A.1. This rule asserts temperatureInTentfacts as soon as the necessary temperature, online and tent facts have beenasserted in the Fact Base. Conversely, when one of these facts is retracted fromthe Fact Base, the rule retracts the corresponding temperatureInTent facts.

1 temperatureInTent(Celsius =?temp , Tent=?tent)

2 <- temperature(Celsius =?temp , FromMAC =?tMac),

3 online(TID=?tentId , MAC=?tMac),

4 tent(ID=?tentId , Name=?tent).

Listing A.1: RETE Algorithm: a rule for asserting temperatureInTent facts

The Rete algorithm transforms rules to a tree-like structure, called a Retenetwork. This network represents the Rule Base and has a single root node, inwhich all new facts are inserted. Because facts are stored in the network, thenetwork also represents the Fact Base. A Rete network consists of two parts.The first part is the alpha network, which contains filter nodes, and the secondpart is the beta network, which contains join- and production nodes. Whenever afact is asserted, it is encapsulated in a token that is inserted in the root node andpropagated through the network. Figure A.1 depicts the Rete network afterinstalling the example rule from Listing A.1 and asserting some facts. Note thattokens are denoted between < and > brackets.

For every condition in a rule’s body, the Rete algorithm generates two fil-ter nodes: one for checking the type of the fact in the condition and one forchecking the inner constraints of the condition. These filter nodes will onlyallow tokens to pass if these tokens satisfy their constraints. For instance, forthe temperature(Celsius=?temp, FromMAC=?tMac) condition, the first filternode verifies that the inserted token has a fact with the temperature type, whilethe second filter node verifies that this fact also has Celsius and FromMAC at-tributes. Note that every filter node also has a memory to cache the insertedtokens that satisfied their constraints. For instance, it can be observed in theFigure that the asserted temperature(Fahrenheit=50) fact passed the con-straint of the temperature filter node (i.e., it has the temperature type), but itdidn’t pass the second filter node for the temperature condition (i.e., it doesn’thave the Celsius and FromMAC attributes).

Every token that passes the second filter node enters the beta network.The top nodes in the beta network are called join nodes and will try tojoin an inserted token with all tokens from the memory of their other par-ent node (i.e., the parent that didn’t insert the token). For instance, when the<temperature(Celsius=30, FromMAC="m1")> token is propagated to the firstjoin node in the example, this join node will attempt to join this token with

Page 100: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

APPENDIX A. CRIMESPOT PROTOTYPE IMPLEMENTATION 88

<temperature(Celsius=30, FromMAC="m1")><temperature(Celsius=25, FromMAC="m1")><temperature(Fahrenheit=50)>

<tent(ID=1,Name="Marquee")><tent(ID=2,Name="Main")>

Alpha Network

temperatureInTent(Celsius=30,Tent="Marquee")temperatureInTent(Celsius=25,Tent="Main")

<online(MAC="m1",TID=1)><online(MAC="m2",TID=2)><online(MAC="m3",TID=2)>

<temperature(Celsius=30,FromMAC="m1"), online(MAC="m1",TID=1)><temperature(Celsius=25,FromMAC="m2"), online(MAC="m2",TID=2)>

temperature

Beta Network

tentonlineMemory T1 Memory E1Memory O1

Memory TO

Memory T2

Memory O2

Memory TO

Memory E2

Root Node

Celsius,FromMAC

MAC,TID

ID,Name

<tent(ID=1,Name="Marquee")><tent(ID=2,Name="Main")>

Memory E2

<online(MAC="m1",TID=1)><online(MAC="m2",TID=2)><online(MAC="m3",TID=2)>

Memory O2

<temperature(Celsius=30, FromMAC="m1")><temperature(Celsius=25, FromMAC="m1")>

Memory T2

<temperature(Celsius=30,FromMAC="m1"),online(MAC="m1",TID=1), tent(ID=1,Name="Marquee")><temperature(Celsius=25,FromMAC="m2"),online(MAC="m2",TID=2), tent(ID=2,Name="Main")>

Memory TOE

Figure A.1: A RETE Network with a single rule for asserting temperatureInTentfacts

all tokens in the memory of the second online filter node. For a pair of tokensto be joinable, the variable bindings that they provide have to be consistent.In the example, this means that the token containing a temperature fact willonly be joined with a token containing an online fact if these tokens providethe same binding for ?tMac. Consequentially, the <temperature(Celsius=30,

FromMAC="m1")> token can only be joined with the <online(MAC="m1",TID=1)>token. Note that every pair of joined tokens is merged into a single token, cachedin the memory of the join node and further propagated through the network.

After the required propagating and joining, a token will eventually reachthe bottom node in the beta network (i.e., the production node), whichmeans that a match for all of the rule’s conditions has been found and thatthe rule’s reaction can be invoked. For instance, whenever the productionnode from the example rule receives a token, it will assert the correspondingtemperatureInTent fact (i.e., the one instantiated with the token’s variablebindings). Note that in this Rete network, no rule has a condition fortemperatureInTent facts and that these facts are therefore not immediatelyuseful.

Whenever a fact is retracted, it is also encapsulated in a token that isinserted in the root node and propagated through the Rete network. To

Page 101: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

APPENDIX A. CRIMESPOT PROTOTYPE IMPLEMENTATION 89

distinguish such a token from a regular token, it carries a negation sign while aregular token carries an addition sign. Unlike positive tokens, negated tokensare not stored in the Rete network. Whenever a negated token passes a nodein the network, the previously stored corresponding token (i.e., the positive onecontaining the same facts) will be removed from that node’s memory before thenegated token is further propagated. When a negated token eventually reachesa production node, the rule corresponding to this production node has lost amatch and will invoke its compensating reaction. For the example rule, thismeans that the temperatureInTent fact corresponding to the negated tokenwill be retracted.

Note that the Rete algorithm gains its efficiency through state-saving.By using memories to store intermediate results in both the alpha and betapart of the network, no previously calculated results have to be recomputedwhen a new fact is asserted or retracted. In addition, the algorithm shares thetype filter nodes among various conditions of various rules and is therefore asmemory-efficient as possible.

A.1.1.2 Sequentializing Access to the RETE Network

CRIME employs a thread-safe agenda to which activations can be added. Allof the agenda’s activations are activated one after another in a first-in first-out order. As an example of an activation, one can consider an activationfor asserting or retracting a fact. When this activation is activated, it willencapsulate the fact in a token and insert this token in the root node of the Retenetwork. This activation is, for instance, added to the agenda whenever a tokenis inserted in a production node (e.g., to assert or retract the correspondingfact) or when a new fact is received from the network.

A.1.2 Introducing Time-related Functionality

While CRIME’s Rete implementation provides a good basis for CrimeSPOT’sInference Layer, it doesn’t provide support for CrimeSPOT’s time-related fea-tures such as fact expiration, match expiration and match verification. To sup-port such functionality, we introduced a timer that can be used to add activa-tions to the aforementioned agenda. This timer runs in a separate thread andallows activations to be scheduled for addition in the agenda after a particularamount of time has passed, or at every interval of a particular amount of time.As we will discuss in the following sections, the activations scheduled in thetimer vary for each of the time-related features.

A.1.2.1 Dealing with Timeouts

Fact Expiration CrimeSPOT’s most notable time-related feature is the ex-piration of facts. As mentioned before, a fact can have an associated factExpiresmeta-attribute that specifies how long this fact remains valid. Whenever a factcarrying this meta-attribute is asserted, an activation for retracting the fact willbe scheduled in the timer. This activation will be added to the agenda after theamount of time that was specified in the factExpires meta-attribute has passed,and the fact will consequentially be retracted.

Page 102: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

APPENDIX A. CRIMESPOT PROTOTYPE IMPLEMENTATION 90

In addition, fact expiration also required the introduction of fact IDs touniquely identify facts. There were two reasons for this requirement. First ofall, it’s perfectly possible to assert the same fact multiple times, in which casethe conceptual Fact Base contains two or more identical facts. Secondly, a factcarrying a factExpires meta-attribute can be retracted before it has expired(e.g., when the rule that asserted it has lost a match). When this happens, thescheduled retraction activation for this fact should be unscheduled. However,when there can be multiple retraction activations for several identical facts,it becomes impossible to decide which activation to unschedule, even thoughall these activations are fundamentally different because they will be added tothe agenda at different times. The rule in Listing A.2 further illustrates thisproblem. This rule asserts a gotReading() fact whenever a reading fact isasserted.

1 gotReading ()@[factExpires(Seconds =999)]

2 <- reading(T=?v).

Listing A.2: A rule for motivating fact IDs

When reading(T="x") is asserted at time t1, and reading(T="x") is assertedat time t2 (with t2 > t1), gotReading() will be asserted twice and scheduledfor retraction at time t1 + 999 and at time t2 + 999. Now, when at a later timet3, the last reading(T="x") gets retracted, the last gotReading() should alsobe retracted and its retraction activation should be unscheduled. However, it’simpossible to decide which retraction activation for gotReading() to unsched-ule: the one that will be added to the agenda at t1 + 999 or the one that will beadded at t2+999. Associating a unique fact ID with every fact solves this issuebecause this ID also uniquely identifies a fact’s retraction activation (if any),which can therefore easily be unscheduled when a fact is retracted.

Match Expiration Another time-related feature is match expiration. Thisfeature is employed whenever a logical condition in a rule’s body carries a match-Expires meta-attribute. This meta-attribute specifies how long a match for theassociated condition remains valid (cfr. Section 3.7.1.3). Note that, in Reteterms, a match for a condition corresponds to the insertion of a positive tokenin the condition’s second filter node (i.e., the one that checks the condition’sinner constraints), while the invalidation of a match for a condition correspondsto the insertion of a negated token in this node.

To introduce match expiration, we extended the aforementioned filter nodesfrom the Rete network with so-called filter actions. A filter action representsadditional logic to be invoked whenever a valid token is inserted in its filter node.Hence, whenever a filter node receives a token that satisfies its constraints, it willnot only store and forward this token, but it will also invoke all of its associatedfilter actions with this token. For every logical condition carrying a matchEx-pires meta-attribute, a special filter action will be added to the filter node thatchecks the condition’s inner constraints (i.e., the condition’s second filter node).Whenever this filter action is invoked with a positive token, it will schedule atoken insertion activation in the timer, which will be added to the agenda afterthe amount of time that was specified in the matchExpires meta-attribute haspassed. This activation will insert a negated copy of the previously insertedtoken in the filter node, which will consequentially be propagated through theRete network and make the match (that was represented by the positive token)

Page 103: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

APPENDIX A. CRIMESPOT PROTOTYPE IMPLEMENTATION 91

expire. Because a condition can also lose a match due to the retraction of a fact(i.e., before the match expired), the aforementioned filter action will, wheneverit is invoked with a negated token, unschedule the previously scheduled tokeninsertion activation because the match no longer has to expire.

Match Verification Finally, the match verification feature is also time-related. This feature is employed whenever a logical condition in a rule’s bodycarries a matchEvery meta-attribute. A matchEvery meta-attribute specifiesthe expected matching for its associated condition and will cause a timedOut

fact to be asserted if the condition isn’t matched in the specified amount of time(cfr. Section 3.7.1.3).

This feature is also implemented using the aforementioned filter actions.For every logical condition carrying a matchEvery meta-attribute, a specialfilter action will be added to the filter node that checks the condition’s innerconstraints (i.e., the condition’s second filter node). Upon initialization, thisfilter action schedules a timeout activation in the timer that will be added tothe agenda after the amount of time that was specified in the matchEvery meta-attribute has passed. When this activation is activated by the agenda, it willassert the timedOut fact for the condition. Whenever the filter action is invokedwith a positive token (i.e., whenever the condition obtained a new match), itwill verify whether the condition already timed out. If it did, the filter actionwill retract the timedOut fact and reschedule the timeout activation in the timersuch that it is added to the agenda after the amount of time that was specifiedin the matchEvery meta-attribute has passed starting from this point in time.If it didn’t, the filter action will only reschedule the timeout activation.

A.1.3 Introducing a Compute Node for the RETE Net-work

Next to the logical conditions for matching facts in the body of a rule,CrimeSPOT also supports extra-logical conditions. Extra-logical conditionsemploy operators and obtain matches by invoking predefined functionality(cfr. Section 3.7.1.4). While some of CrimeSPOT’s extra-logical conditionsare a part of CRIME (i.e., the not, findall, and length operators), the is

operator is not. As discussed earlier, this operator can be used to invoke oneof the component’s methods from within the body of a rule. The syntax for anis-expression (i.e., a condition that employs the is-operator) is shown below.Note that the is-operator will only provide a match if the expression on its

�extralogical condition� ::= (�value� | �variable�) is �methodinvocation�| findall(�variable�,[�body�],�variable�)| length(�list�,(�value� | �variable�))| not �fact�| �variable� �relop� (�value� | �variable�)

�is expression� ::= (�value� | �variable�) is �methodinvocation��methodinvocation� ::= �name�( [ �argument� (, �argument�)* ] ) [ @[�option�] ]

�argument� ::= �value� | (�typecast�)�variable��typecast� ::= Number | Fraction | Text | Symbol | List�option� = evalEvery(Seconds=�number�)

| renewEvery(Seconds=�number�)

left-hand side can be unified with the result of the method invocation on itsright-hand side.

Page 104: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

APPENDIX A. CRIMESPOT PROTOTYPE IMPLEMENTATION 92

For every is-expression in a rule’s body, a compute node is created (i.e.,to invoke the method) and fitted in the Rete network. When the is-expressionis the rule’s first condition, the compute node will not have a parent, whileotherwise, it will have a parent. To simplify the explanation of this node, wewill distinguish between these two cases.

A Compute Node without a parent

Compute

<compute(Result=x)>

MemoryA compute node without a parent can be com-pared to a filter node. It will filter the resultsof method invocations and will only allow theresults that unify with the expression on theleft-hand side of the is-operator to pass.

Unlike a filter node, a compute node is not connected to the Rete network’sroot node. This is because it doesn’t rely on the assertion or retraction of facts todo its work. As soon as the compute node is initialized (i.e., fitted in the Retenetwork), it will invoke its method and verify whether the result can be unifiedwith the expression on the left-hand side of the is-operator. If this unificationsucceeds, the result is placed in a special fact that is encapsulated within atoken. This token is stored in the compute node’s memory and propagated toits child node. Note that this special fact will never be asserted in the FactBase and can therefore not be matched in other conditions. Its sole purpose isto represent the result of the compute node (e.g., to bind a variable, when theexpression on the left-hand side of the is-operator was an unbound variable).

When the is-expression specified a scheduling option for the method invo-cation, the compute node will invoke its method multiple times. In this case,a compute activation will be scheduled in the timer that will be added to theagenda at every interval of the time specified by the option (e.g., every 10 sec-onds). This activation will trigger the compute node. When the evalEveryoption was employed, the compute node will just repeat the aforementionedbehavior when it is triggered. On the other hand, when the renewEvery op-tion was employed, the compute node will first remove the stored token fromits memory, negate it, and forward it to its child node (i.e., to invalidate theprevious match) before repeating the aforementioned behavior.

A Compute Node with a parent.

Compute<f1, .., fn, compute(Result=x)>

Memory A compute node with a parent can becompared to a join node. It will joinevery inserted token with the result ofthe corresponding method invocation.

Due to the presence of a parent, the compute node will do its work as soonas a token has been inserted. When a positive token is inserted, the node

Page 105: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

APPENDIX A. CRIMESPOT PROTOTYPE IMPLEMENTATION 93

will use this token to invoke its method (e.g., to extract values for variablemethod arguments) and to verify the unifiability of the invocation’s result andthe (possibly variable) expression on the left-hand side of the is-operator. Ifthe unification succeeds, the node will merge the inserted token with the tokencontaining the invocation result. The resulting token is stored in the computenode’s memory and propagated to its child node.

On the other hand, when a negated token is inserted, the method shouldnot be re-invoked but the previously propagated positive token should be in-validated. To this end, the node will search its memory for the token with theresult of the method invocation that employed the positive token correspondingto the inserted negated token (i.e., the positive token with the same facts). Thistoken will be removed from its memory, negated, and propagated to its childnode.

When the is-expression specified a scheduling option for the method invoca-tion, the compute node will invoke its method multiple times for every insertedpositive token. Therefore, for every such token, a compute activation is sched-uled in the timer that will be added to the agenda at every interval of the timespecified by the scheduling option. Unlike the aforementioned computation ac-tivation, this activation will trigger the compute node using the token. Whenthe evalEvery option was employed, the compute node will just behave as if anew positive token is inserted when it is triggered. On the other hand, when therenewEvery option was employed, the compute node will first remove the storedtoken with the result of the previous method invocation for the token from itsmemory, negate it, and forward it to its child node (i.e., to invalidate the pre-vious match) before behaving as if a new positive token is inserted. When anegated token is inserted in the compute node, the method will no longer haveto be invoked for the corresponding positive token and therefore, this positivetoken’s compute activation is unscheduled.

A.2 Reification Layer

As explained earlier, the reification layer consists of the Reification Engine andthe Configuration Base. While its main purpose is to reify events as factsupon reception (i.e., to be asserted in or retracted from the Fact Base), and toreify facts as events (i.e., to be published through the underlying middleware),it also takes care of processing the subsumption- and drop meta-facts that areconceptually present in the Configuration Base (cfr. Section 3.8). In this section,we will explain how these meta-facts are implemented.

A.2.1 Processing Incoming Events

The conceptual processing of incoming events has already been illustrated inthe Event reification pipeline (cfr. Figure 3.15). When the Reification Enginereceives an event, it will first reify it as a fact and verify whether it should bedropped. If the fact shouldn’t be dropped, the Reification Engine will retract allfacts that were subsumed by the newly received fact, after which it will assert thenew fact in the Fact Base. To implement this functionality, three activationsare added to the aforementioned agenda after an event was reified as a fact:one for verifying whether the fact should be dropped, one for retracting all

Page 106: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

APPENDIX A. CRIMESPOT PROTOTYPE IMPLEMENTATION 94

facts that were subsumed by the newly received fact, and one for asserting thenew fact in the Fact Base. While the activation for asserting a fact is by nowstraightforward, the following sections will clarify what the other activationsactually do.

A.2.2 Implementing the Meta-Facts

While meta-facts are conceptually represented as entities stored in the Config-uration Base, their functionality is implemented as special-purpose Rete net-works. These networks are rooted in the Reification Layer and employ special-purpose filter-, join- and production nodes. In addition, they are joined withthe previously explained Rete network from the Inference Layer.

A.2.3 Building a RETE Network for Drop Meta-Facts

Whenever a drop meta-fact is added to the CrimeSPOT runtime, the Reifica-tion Layer’s Rete network for drop meta-facts is extended. To this end, thedrop meta-fact is transformed as if it was a rule. To illustrate this transforma-tion, we can consider the following drop meta-fact:

1 drop!( Incoming=temperature(Celsius =?n)@[from(MAC=?m)],

2 When=[ refuseTemp(From=?m)].

This meta-fact specifies that a newly received temperature fact should bedropped when there’s a refuseTemp fact in the Fact Base for the sensor nodethat published the temperature. Figure A.2 depicts the Rete network afterinstalling the above drop meta-fact. While the drop meta-fact’s body (i.e., thevalue of the When attribute) is transformed like a regular rule’s body and addedto the Inference Layer’s Rete network, the incoming fact’s specification (i.e.,the value of the Incoming attribute) is transformed like a regular condition andadded to the Reification Layer’s Rete network for drop meta-facts. Note thatthe filter-, join- and production nodes in the Reification Layer’s drop Rete net-work are different than the previously discussed ones. First of all, the filter-and join nodes do not cache any tokens. Furthermore, while the filter nodebehaves the same, the join node will only try to join an inserted token from thesecond temperature filter node with the tokens in memory R2 (and not the otherway around). As soon as one pair of tokens was joined, the join node will notattempt to join the inserted token with any other token from memory R2. Itwill immediately propagate the merged token to the production node. Finally,when a token reaches the production node, this node will immediately invokeits functionality (i.e., rather than scheduling an activation in the agenda).

When an activation for verifying whether a received fact should be droppedis activated2, the received fact is encapsulated in a token that is inserted in theroot node of the Reification Layer’s network for drop meta-facts. As an exam-ple, consider the reception of a temperature(Celsius=-1)@[from(MAC="m2")]

fact. The token encapsulating this fact will be passed by both the first andthe second filter node in the drop network because it has the temperaturetype and a Celsius attribute. When it reaches the join node, the join nodewill be able to join it with <refuseTemp(From="m2")> and will propagate

2Remember, this activation was added to the agenda by the Reification Engine after itreified a received event as a fact.

Page 107: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

APPENDIX A. CRIMESPOT PROTOTYPE IMPLEMENTATION 95

Root Node

Root Node

temperature

Celsius

<refuseTemp(From="m1")><refuseTemp(From="m2")>

refuseTempMemory R1

From

<refuseTemp(From="m1")><refuseTemp(From="m2")>

Memory R2

Alpha Network

Beta Network Memory R2

Any

Drop!

Inference Network Reification (Drop)Network

Figure A.2: A RETE Network with a single meta-fact for dropping temperaturefacts

<refuseTemp(From="m2"),temperature(Celsius=-1)@[from(MAC="m2")]>

to the production node. The latter will immediately invoke its functionality:as the received fact should be dropped, it will remove both the activation forretracting all facts that were subsumed by the received fact, and the activationfor asserting the received fact from the agenda.

If we consider the reception of a humidity(Percent=50)@[from(MAC="m2")]fact, this fact’s token will never pass the first filter node and therefore, theremaining activations for dealing with subsumptions and for asserting the factin the Fact Base will not be removed from the agenda but will just be activatedone after another as soon as the token propagation stopped.

Note that this drop Rete network introduces a minimal overhead when atoken is inserted in its root node. All required results in the Inference Layer’snetwork are cached and don’t have to be recomputed.

A.2.4 Building a RETE Network for Subsumption Meta-Facts

Whenever a subsumption meta-fact is added to the CrimeSPOT runtime, theReification Layer’s Rete network for subsumption meta-facts is extended. Tothis end, the subsumption meta-fact is transformed as if it was a rule. Toillustrate this transformation, we can consider the following subsumption meta-fact:

1 subsumes !( Incoming=temperature(Celsius =?new)@[from(MAC=?m)],

Page 108: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

APPENDIX A. CRIMESPOT PROTOTYPE IMPLEMENTATION 96

2 Fact=temperature(Celsius =?old)@[from(MAC=? otherm)],

3 When=[ online(Tent=?tnt)@[from(MAC=? otherm)],

4 online(Tent=?tnt)@[from(MAC=?m)]]).

This meta-fact specifies that a received temperature fact subsumes all exist-ing temperature facts that originate from the same tent. Figure A.3 depictsthe Rete network after installing the above subsumption meta-fact. Before

Root Node

Root Node

temperature

Celsius

online <online(T="A")@[from(MAC="m1")]><online(T="A")@[from(MAC="m2")]><online(T="B")@[from(MAC="m3")]>

Memory O1

Tent Memory O2b

Alpha Network

Beta Network

Memory TOO

Any

Subsumption!

Inference NetworkReification

(Subsumption)Network

<online(T="A")@[from(MAC="m1")]><online(T="A")@[from(MAC="m2")]><online(T="B")@[from(MAC="m3")]>Tent

Memory O2a<online(T="A")@[from(MAC="m1")]><online(T="A")@[from(MAC="m2")]><online(T="B")@[from(MAC="m3")]>

<temperature(C=30)@[from(MAC="m1")]><temperature(C=25)@[from(MAC="m3")]>

temperatureMemory T1

Celsius

<temperature(C=30)@[from(MAC="m1")]><temperature(C=25)@[from(MAC="m3")]>

Memory T2

<temperature(C=30)@[from(MAC="m1")], online(T="A")@[from(MAC="m1")]><temperature(C=25)@[from(MAC="m3")], online(T="B")@[from(MAC="m3")]>

Memory TO

Memory T2

Memory O2a

<temperature(C=30)@[from(MAC="m1")], online(T="A")@[from(MAC="m1")], online(T="A")@[from(MAC="m1")]><temperature(C=30)@[from(MAC="m1")], online(T="A")@[from(MAC="m1")], online(T="A")@[from(MAC="m2")]><temperature(C=25)@[from(MAC="m3")], online(T="B")@[from(MAC="m3")], online(T="B")@[from(MAC="m3")]>

Memory TOOMemory TO

Memory O2b

Figure A.3: A RETE Network with a single meta-fact that specifies the subsumptionstrategy for temperature facts

transforming the subsumption meta-fact’s body (i.e., the value of the Whenattribute), it is merged with the fact-to-subsume’s specification (i.e., the valueof the Fact attribute). For instance, the above meta-fact’s body is actually:temperature(Celsius=?old)@[from(MAC=?otherm)], online(Tent=?tnt)

@[from(MAC=?otherm)], online(Tent=?tnt)@[from(MAC=?m)]. This bodywill be transformed like a regular rule’s body and added to the Inference Layer’sRete network3. The incoming fact’s specification (i.e., the value of the Incomingattribute), on the other hand, is transformed like a regular condition and added

3Note that the above network also illustrates the sharing of type filter nodes: the type filternode for online facts is shared among both online conditions in the subsumption meta-fact’sbody.

Page 109: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

APPENDIX A. CRIMESPOT PROTOTYPE IMPLEMENTATION 97

to the Reification Layer’s Rete network for subsumption meta-facts. Mostnodes in this subsumption network are identical to the ones of the aforemen-tioned drop network. However, the join node will attempt to join any insertedtoken from the second temperature filter node with all tokens from memoryTOO and will consequentially propagate all successfully joined tokens to its child(i.e., the production node). Note that this network construction allows the pro-duction node to easily identify the subsumed facts: a subsumed fact will be inthe first position of an inserted token.

To illustrate how the above network functions, we can now consider theactivation for retracting all facts that were subsumed by a newly received fact4.When this activation is activated, the newly received fact is encapsulated ina token that is inserted in the root node of the Reification Layer’s networkfor subsumption meta-facts. As an example, consider the reception of atemperature(Celsius=28)@[from(MAC="m2")] fact that wasn’t dropped.The token encapsulating this fact will be passed by both the first and thesecond filter node in the subsumption network because it has the temperaturetype and a Celsius attribute. When it reaches the join node, the join nodewill be able to join it with <temperature(Celsius=30)@[from(MAC="m1")],

online(Tent="A")@[from(MAC="m1")], online(Tent="A")@[from(MAC="m2")]>

and will propagate <temperature(Celsius=30)@[from(MAC="m1")],

online(Tent="A")@[from(MAC="m1")], online(Tent="A")@[from(MAC="m2")],

temperature(Celsius=28)@[from(MAC="m2")]> to the production node. Thelatter will immediately invoke its functionality: because a token was inserted,an incoming fact subsumed another fact (i.e., the one in the first position ofthe inserted token: temperature(Celsius=30)@[from(MAC="m1")]), and thissubsumed fact is consequentially retracted from the Fact Base.

Note that, just like the drop Rete network, the subsumption network in-troduces a minimal overhead when a token is inserted in its root node. Allrequired results in the Inference Layer’s network are cached and don’t have tobe recomputed.

A.3 Infrastructure Layer

The Infrastructure Layer binds the CrimeSPOT runtime to the underlying mid-dleware. To this end, a middleware-specific implementation for the MiddlewareBridge should be provided which transfers the events received from the event-based middleware to the Reification Engine. In addition, the Middleware Bridgeshould also implement all required middleware-specific functionality, which willbe invoked by the Reification Engine.

For CrimeSPOT’s prototype implementation, we used the LooCI event-based component middleware for the SunSPOT platform and instantiated themiddleware bridge accordingly. This section will introduce the LooCI mid-dleware and give more details regarding the implementation of its middlewarebridge.

4Remember, this activation was added to the agenda by the Reification Engine after itreified a received event as a fact.

Page 110: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

APPENDIX A. CRIMESPOT PROTOTYPE IMPLEMENTATION 98

A.3.1 LooCI

The LooCI [25] middleware introduces both a component infrastructure and adecentralized event-bus to wireless sensor networks. It allows multiple compo-nents to be deployed on the same WSN node and it allows these components tocommunicate by exchanging events through the decentralized event-bus. Com-ponents can both publish events and subscribe to certain event types. Based onthe event-subscriptions (i.e., wirings in the LooCI jargon), the events publishedin the WSN application will be routed from the publishers to the subscribersthrough the decentralized event-bus. This is illustrated in Figure A.4 (takenfrom the LooCI website5), which depicts a runtime view on a WSN node run-ning LooCI. Next to the components and the event-bus, it also depicts the Re-

Figure A.4: Runtime view on a WSN node running LooCI

configuration Engine, which is the heart of the LooCI middleware and controlsthe components running on the WSN node. To allow a developer to control theReconfiguration Engine, LooCI comes with a gateway application. This gate-way should run on a back-end entity and can, for instance, be used to remotelydeploy components on the nodes in the wireless sensor network.

A.3.2 Instantiating the Middleware Bridge for the LooCIMiddleware

To instantiate the Middleware Bridge, an implementation for the followingmethods has to be provided:

• void subscribeToEvent(EventDescription desc) subscribes to theevents of the given Event Description. This method is called whenevera new event-fact mapping has been added to the CrimeSPOT runtime.

5http://code.google.com/p/looci/

Page 111: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

APPENDIX A. CRIMESPOT PROTOTYPE IMPLEMENTATION 99

• Object toEvent(GenericFact fact, Mappings m, Boolean

isAssertion) converts the given fact to an event and returnsit.

• void publish(Object event) publishes the given event.

• GenericFact toFact(Object event, Mappings m) converts a receivedevent to a GenericFact and returns it. This method can return null

if the event is misaddressed, which is useful for middleware that doesn’tallow directed event publications.

• Boolean isAssertion(Object event, Mappings m) decides whetherthe event represents a fact to be asserted or retracted.

Given the LooCI API, the implementation for these methods is quitestraightforward. We assigned a specific event type for publishing non-mappedfacts and for publishing fact retractions and subscribed each CrimeSPOT com-ponent to these event types (i.e., by registering so-called toAll and fromAllwirings with LooCI’s Reconfiguration Engine). All of the mapped facts orevents are converted to events or facts using the mappings. Note that LooCIdoes not support directed event publications and that this functionality is there-fore simulated in our middleware bridge implementation by verifying an event’sdestination at the receiver.

Subscribing to events Using the LooCI API, it is possible to subscribe acomponent to a specific event type at runtime by registering so-called toAll - andfromAll wirings with the Reconfiguration Engine. The implementation of thesubscribeToEvent(EventDescription) method registers these wirings when-ever it is called (i.e., after an event-fact mapping was added to the CrimeSPOTruntime).

Converting Facts to Events Depending on whether the toEvent methodis called to create an event for a fact assertion or a fact retraction, the fact isconverted to a potentially mapped event or a retraction event (i.e., an event ofthe aforementioned fact retraction type).

In the case of a fact assertion, the Mappings dictionary is first searched for amapping for this fact. If such a mapping is found, the fact is converted to thecorresponding event. In addition, extra fields are added to this event’s payloadto store the fact’s ID and destination (i.e., the destination MAC address andcomponent ID). As LooCI does not allow directed publications, such publi-cations are simulated: the extra destination fields will be read in the toFact

method to decide whether or not to accept a received event. Regular LooCIcomponents will typically not read these extra fields. On the other hand, if nomapping is found, an event of the aforementioned event-type for non-mappedfacts is created. This event has, as its payload, a single String containing thefact’s textual representation.

In the case of a fact retraction, an event of the event-type for fact retractionsis created. This event has, as its payload, a String containing the network-uniqueidentifier for the fact (i.e., a combination of the originating component’s MACaddress, its component ID, and the fact ID). In addition, it also has extra fields

Page 112: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

APPENDIX A. CRIMESPOT PROTOTYPE IMPLEMENTATION 100

containing the destination component’s MAC address and component ID (i.e.,to simulate a directed publication).

Publishing Events The publish(Object) method maps exactly on thepublish(Event) method that’s provided by the LooCI API.

Converting Events to Facts Converting an event to a fact is analog to theinverse process.

In the case the event type is present in the Mappings dictionary or is equalto the non-mapped fact event type, the event is converted to a fact accord-ingly. To convert a fact’s textual representation to a fact (i.e., in the case of anon-mapped fact event type), the CrimeSPOT runtime provides a conversionmethod to parse the textual representation. Misaddressed events are detectedby comparing the fact’s destination address (if any), with the current compo-nent’s address.

Else, if the event type is of the fact retraction type, the corresponding factis obtained from the CrimeSPOT runtime by querying the Fact Base using thefact’s unique identifier.

Deciding on fact assertion or retraction Due to the above implementa-tion, the implementation of isAssertion is simple. It suffices to verify whetherthe event carries the fact retraction event type to decide whether a given eventrepresents a fact assertion or -retraction.

A.4 Macro-CrimeSPOT’s Compilation Target

As we’ve explained earlier, Macro-CrimeSPOT code compiles to node-level component code (cfr. Section 4.3). This node-level code employs theCrimeSPOT prototype implementation that was discussed in this appendix.In this section, we will show what this node-level code looks like, or, how acomponent can be implemented by using only the CrimeSPOT language.

When using the CrimeSPOT prototype implementation, a componentcan be implemented by extending the CrimeSPOTComponent class. A com-ponent has to provide an implementation for two methods: the execute()

method, which will be invoked when the component is started, and theinvoke(String,Object[]) method, which is a dispatcher method for dispatch-ing method names to method invocations. An implementation for the dispatchermethod is required to allow the CrimeSPOT runtime to invoke methods on thecomponent in the absence of reflection on the SunSPOT platform.6 For everymethod that’s invoked from within an interaction rule’s body, there should bean entry in this dispatcher method.

Listing A.3 depicts an example component’s implementation in Java. Thiscomponent publishes temperatureReading facts and reacts to adjustHeating

facts by steering its associated heater accordingly.

6Because interaction rules are added to the CrimeSPOT runtime at runtime, the methodsto invoke from within these rules’ bodies are also only known at runtime. Dynamically invokingmethods at runtime requires some form of reflection, which is not available on the SunSPOTplatform.

Page 113: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

APPENDIX A. CRIMESPOT PROTOTYPE IMPLEMENTATION 101

1 public class ExampleComp extends CrimeSPOTComponent {

2 public ExampleComp () { super("Example Component"); }

34 public void execute () {

5 processExpression("temperatureReading(Celsius =?temp)@[factExpires(Seconds =600)," +

6 "to(MAC=\" any \")]" +

7 " <- ?temp is getTemperature ()@[renewEvery(Seconds =600)].");

89 registerRule("adjustHeating(Level =?h)",this.adjustHeater );

10 }

1112 private Action adjustHeater = new Action () {

13 public void activated(TypedObject arguments) { /* adjust heater */ }

14 public void deactivate(TypedObject arguments) { /* reset heater */ }

15 };

1617 public Attribute invoke(String method , Object [] args){

18 if(method.equals("getTemperature__"))

19 return getTemperature ();

20 else

21 return ExpressionFactory.attribute("ERROR: Method not in the dispatcher!");

22 }

23 }

Listing A.3: Macro-CrimeSPOT’s compilation target: a CrimeSPOT Component inJava

Note that, because the getTemperature() method is invoked from within aninteraction rule’s body, there’s an entry for this method in the dispatchermethod. Its implementation, however, is not required in this class. ThegetTemperature() method is part of the predefined I/O methods provided bythe CrimeSPOTComponent class. Other predefined I/O methods are: getMac(),getLight(), getAcceleration() and turnOnLeds(amount,color).

For a component of a Macro-CrimeSPOT application, both the execute

and invoke methods are implemented by Macro-CrimeSPOT’s precompiler.However, to allow a Macro-CrimeSPOT programmer to initialize her compo-nent using Java logic, the initialize() method can be overridden in a Javacode block. This method is invoked whenever a component is started.

A.5 Conclusion

In this appendix, we presented the most important aspects of the CrimeSPOTprototype implementation7 by discussing the highlights of its three layers. Forthe Inference Layer, CRIME’s Inference Engine (i.e., a Rete engine) was partlyreused, yet also extended. We covered the most important extensions, whichwere required for CrimeSPOT’s time-related functionality (i.e., fact expiration,match expiration and match verification) and for propagating the results ofmethod invocations through the Rete network. The Reification Layer wasentirely built from scratch. The most notable aspects of this layer were thespecial purpose Rete networks for implementing CrimeSPOT’s meta-facts.Finally, we also discussed the interface for the Infrastructure Layer’s MiddlewareBridge. This interface should be implemented for specific event-based WSNmiddleware in order to use the CrimeSPOT prototype on top of it. As an

7The source code can be consulted at http://soft.vub.ac.be/amop/crime/sunspot.

Page 114: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

APPENDIX A. CRIMESPOT PROTOTYPE IMPLEMENTATION 102

example, we showed how the Middleware Bridge can be instantiated for theLooCI event-based component middleware.

Next to discussing the CrimeSPOT prototype implementation, we alsoshowed how this prototype can be used. While implementing a CrimeSPOTcomponent is simple, the implementation of the dispatcher method can be con-sidered cumbersome. However, using Macro-CrimeSPOT and its accompa-nying precompiler relieves a programmer from this burden.

In the next appendix, we will evaluate our CrimeSPOT prototype imple-mentation in terms of memory footprint, network overhead and performance.

Page 115: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

BEvaluating the CrimeSPOT Prototype

Having explained the CrimeSPOT prototype implementation, we will nowgive a preliminary evaluation of its overhead. All required experiments wereconducted on standard SunSPOT motes (180MHz ARM9 CPU, 512KB RAM,4MB Flash, SQUAWK VM version ’RED-100104’) running the LooCI middle-ware version 1.0 beta (20101011).

B.1 Memory Footprint

We measured CrimeSPOT’s memory footprint both in terms of ROM andRAM.

Table B.1 summarizes the results for the ROM usage. Clearly, the

LooCI CrimeSPOT Average ComponentROM 52,14kB 406,66kB 1,99kB

Table B.1: Memory Footprint (ROM)

CrimeSPOT implementation consumes a considerable amount of Flash mem-ory (i.e., 9,7% of the SunSPOT’s Flash). We expected this result as our pro-totype implementation includes the CRIME implementation which is not yetentirely cleaned up and optimized for use on sensor motes with small Flashmemory. Further cleaning up the implementation is left for future work. How-ever, like the LooCI middleware, the CrimeSPOT prototype has been includedin the SunSPOT library and hence should never be remotely deployed usingthe LooCI gateway. Thereby, we avoided long component deployment delays.The CrimeSPOT components on the other hand, which have to be remotelydeployed, have a minimal footprint. By taking the average of the sizes of ourexample applications’ components, we ended up with an average component sizeof 1,99kB.

103

Page 116: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

APPENDIX B. EVALUATING THE CRIMESPOT PROTOTYPE 104

SunSPOT App LooCI Comp CrimeSPOT CompRAM 43,28kB 119,57kB 131,96kB∆ 43,28kB 76,29kB 12,39kB

Table B.2: Memory Footprint (RAM)

Table B.2 summarizes some RAM measurements. We verified the RAMusage by creating a SunSPOT application, a LooCI component, and aCrimeSPOT component, which all did nothing but outputting the RAM usageafter a garbage collection. Since a CrimeSPOT component is actually a LooCIcomponent, it comes as no surprise that running one with an empty Rule- andFact Base doesn’t introduce a lot of RAM overhead. A running CrimeSPOTsystem only consumes an additional 12,39kB of RAM when compared to adummy LooCI component, bringing the total RAM usage to 131,96kB.

Since these RAM measurements only give an indication of the CrimeSPOTRAM usage at initialization time, we performed two additional experiments formeasuring the RAM usage after adding to the Fact- and Rule Base, respectively.

Figure B.1: Fact Base Size vs RAM Usage

Figure B.1 shows the RAM usage versus the amount of facts in the FactBase. For this experiment, we asserted facts with two attributes each; onerandom Number between 0 and 50, and a constant Text value. This simulatesa Fact Base filled with numerical sensor readings which have an additionaldescription, a plausible scenario for CrimeSPOT components. In addition,we installed a rule with a matching condition that measured the RAM usageupon triggering. We kept asserting new facts until running out of memory. The

Page 117: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

APPENDIX B. EVALUATING THE CRIMESPOT PROTOTYPE 105

results are not very surprising: every asserted fact consumed an average of 3kBRAM and we were unable to assert more than 102 facts. However, these resultsclearly emphasize the importance of keeping the Fact Base clean (e.g., by usingthe subsumes and drop meta-facts).

1 Rule 2 Rules 3 Rules 10 RulesRAM 168,43kB 199,98kB 230,36kB 443,85kB

Table B.3: Memory Footprint (RAM) vs. Amount of rules

Table B.3 shows the RAM usage versus the amount of rules in the Rule Base.Since our example applications’ rules have at most six conditions, we filled ourRule Base with distinct variants of the rule shown in Listing B.1 until runningout of memory.

1 fact(A=?x, B=?y, C=?z)

2 <- c1(A=?x, B=?y, C=?z), c2(A=?x, B=?y, C=?z),

3 c3(A=?x, B=?y, C=?z), c4(A=?x, B=?y, C=?z),

4 c5(A=?x, B=?y, C=?z), c6(A=?x, B=?y, C=?z).

Listing B.1: Artificial rule for the RAM usage experiment

The artificial rule more or less represents a worst-case scenario in terms ofmemory consumption, as the body is quite large and the corresponding Retenetwork is therefore too. Furthermore, since all conditions are distinct, there’sno reuse of filter nodes in the network. As shown in the results, the rule con-sumes around 30,5kB of RAM, and we were unable to instantiate it more thanten times. We attribute this considerable amount of memory consumption tothe fact that the prototype implementation is not yet entirely cleaned up andoptimized. Even though none of our example applications employed ten rules,and the average amount of conditions in their rules was smaller than six, theresults of this experiment indicate considerable room for improvements, whichare left for future work.

B.2 Network Overhead

A CrimeSPOT component doesn’t introduce a lot of network overhead whencompared to a regular LooCI component. Only two forms of network overheadcan be identified: overhead in the publication of mapped facts, and overheaddue to the publication of retraction events.

When publishing mapped facts, the predefined LooCI event payload is ex-tended with the fact ID and -destination (i.e., the target MAC address andcomponent ID). These extra fields are introduced for fact identification andunicast publication purposes, respectively. However, since the fact ID is onlyan integer, we consider this addition as a minimal overhead.

The remote retraction of published facts upon retracting them in the sender’sFact Base can also be observed as network overhead. However, the events pub-lished to retract published facts are restricted to a minimum. A retraction eventdoesn’t carry the entire fact to be retracted, but only the data required for iden-tifying that fact and its destination (i.e., the fact identifier and its destinationMAC address and component ID). Furthermore, the publication of a retraction

Page 118: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

APPENDIX B. EVALUATING THE CRIMESPOT PROTOTYPE 106

event only occurs when the retracted fact has not yet expired, as this expirationwould’ve also occurred at the CrimeSPOT components who received the fact.

B.3 Performance

To verify the performance of the CrimeSPOT prototype, we measured thetime required for the work to be performed upon event reception. This sectionillustrates the computational overhead introduced by our prototype implemen-tation.

When the received event entails the assertion of a fact, the event hasto be transformed to a fact and the drop and subsumption meta-facts have tobe verified before the fact can be asserted in the Fact Base. The average timerequired between receiving an event and asserting the associated fact is shownin Table B.4. For simplicity, we assumed the absence of matching drop andsubsumption meta-facts. As the event transformation process is different for an

Encoded fact Mapped factTime (ms) 80,33 34,22

Table B.4: Average time required before a fact will be asserted in the Fact Base,after receiving the corresponding event

event containing an encoded fact (i.e., the fact’s textual representation, e.g.,fact(Number=1, Text="a description")), and a mapped event, we timedboth. In this experiment, the event’s corresponding fact to be asserted sim-ulates a sensor reading or a typical application-fact; it has two attributes: aNumber and a Text. We repeated the experiment ten times and ended up withan average delay of 80,33ms before asserting an encoded fact, and an averagedelay of 34,22ms before asserting a mapped fact. As expected, processing anevent containing an encoded fact consumes more time as the complex textualrepresentation has to be parsed before the corresponding fact can be asserted.The processing of mapped events is more efficient as a predefined event signa-ture is typically small and the parsing is less complex (i.e., obtaining the fieldsfrom the event, and creating the corresponding fact suffices).

The presence of matching drop or subsumption meta-facts also introducescomputational overhead. However, these meta-facts’ bodies (i.e., the values oftheir When attribute) are almost completely verified before receiving a fact.When a newly received fact matches a meta-fact, the only work left to do is tojoin the token encapsulating this fact with the tokens for the meta-fact’s body(i.e., in the join node that joins the Inference Layer’s Rete network with theReification Layer’s network), which requires extra time linear in the amountof tokens for the body. In case there’s a satisfied drop meta-fact, no furtherwork is required and the fact is immediately dropped. In case there’s a satisfiedsubsumption meta-fact, extra time will be required for retracting each subsumedfact.

To give an indication of the time required between the assertion of a factand the activation of a rule, we re-used the artificial rule from Listing B.1. Thisrule is quite complex as it has six conditions and each condition shares variables

Page 119: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

APPENDIX B. EVALUATING THE CRIMESPOT PROTOTYPE 107

with all other conditions, requiring all these variables to be checked within thejoin nodes in the rule’s RETE network. In the experiment, a matching fact waspresent for conditions c2 to c6, and we measured the time between the assertionof a matching c1 fact and the activation of the rule (i.e., the assertion of the factfrom the rule’s head). This simulates a worst-case scenario for this rule as thefilter node for c1 is at the top of the RETE-network representing the rule, andthe assertion of a matching c1 fact will thus introduce the most work (i.e., thetoken in which it is encapsulated will have to be propagated all the way from thetop to the bottom of the RETE-network, passing every join node). We repeatedthis experiment ten times and ended up with an average delay of 141,20ms. Itmust be noted that this average delay is only valid in this scenario. The realdelay between asserting a matching fact and activating a rule depends on thatrule’s complexity, on the presence of matching facts for its other conditions,and on the amount of other rules with a condition matching the asserted factpreceding that rule in the Rule Base.

When the received event entails the retraction of a fact, the corre-sponding fact has to be looked up in the Fact Base before it can be retracted,requiring constant time (i.e., an average of 28ms in our experiments).

To give an indication of the time required between the retraction of a factand the deactivation of a rule, we performed about the same experiment as forthe assertion of a fact. The rule from Listing B.1 was installed, a matching factis present for all conditions, the rule has been activated, and we measured thetime between retracting the matching c1 fact and the deactivation of the rule(i.e., the retraction of the fact from the consequence). For the same reasonsas mentioned earlier, this experiment represents a worst-case scenario for thiscomplex rule (i.e., the token has to propagate from the top to the bottom ofthe network). After repeating the experiment ten times, we ended up withan average delay of 188,90ms, which is surprisingly about 47ms higher thanthe delay introduced between asserting a matching c1 fact and activating therule. Since fact retraction involves more or less the same processing as factassertion, we attribute this difference to the fact that removing data from thedata-structures employed within the RETE implementation, which is requiredupon fact retraction, is less efficient than adding data, which is required uponfact assertion. For the same reasons as discussed earlier, it must be noted thatthis average delay between retracting the fact and deactivating the rule is onlyvalid in this scenario.

B.4 Conclusion

This appendix presented the preliminary evaluation of our CrimeSPOT proto-type implementation. Since this implementation is not yet entirely cleaned upand optimized, we believe that the current results look quite promising. In thefuture, we expect to improve on these results by further reducing the memoryfootprint in terms of ROM and RAM requirements. Furthermore, additional op-timizations and hardware advances could also improve the overall performanceof our language.

Page 120: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

Bibliography

[1] L. Mottola and G. P. Picco, “Programming wireless sensor networks: Fun-damental concepts and state of the art,” ACM Computing Surveys, vol. 43,no. 3, pp. 19:1–19:51, 2011.

[2] R. Sugihara and R. K. Gupta, “Programming models for sensor networks:A survey,” ACM Transactions on Sensor Networks, vol. 4, no. 2, pp. 1–29,2008.

[3] S. R. Madden, M. J. Franklin, J. M. Hellerstein, and W. Hong, “Tinydb:an acquisitional query processing system for sensor networks,” ACM Trans-actions on Database Systems (TODS), vol. 30, no. 1, pp. 122–173, 2005.

[4] Y. Kwon, S. Sundresh, K. Mechitov, and G. Agha, “Actornet: an actor plat-form for wireless sensor networks,” in Proceedings of the 5th internationaljoint conference on Autonomous Agents and MultiAgent Systems (AAMAS’06), pp. 1297–1300, 2006.

[5] A. Mainwaring, D. Culler, J. Polastre, R. Szewczyk, and J. Anderson,“Wireless sensor networks for habitat monitoring,” in Proceedings of the1st ACM international workshop on Wireless Sensor Networks and Appli-cations (WSNA ’02), pp. 88–97, 2002.

[6] P. Juang, H. Oki, Y. Wang, M. Martonosi, L. S. Peh, and D. Rubenstein,“Energy-efficient computing for wildlife tracking: design tradeoffs and earlyexperiences with zebranet,” in Proceedings of the 10th international confer-ence on Architectural Support for Programming Languages and OperatingSystems (ASPLOS ’02), pp. 96–107, 2002.

[7] K. Martinez, J. K. Hart, and R. Ong, “Environmental sensor networks,”Computer, vol. 37, no. 8, pp. 50–56, 2004.

[8] A. Arora, P. Dutta, S. Bapat, V. Kulathumani, H. Zhang, V. Naik, V. Mit-tal, H. Cao, M. Demirbas, M. Gouda, Y. Choi, T. Herman, S. Kulkarni,U. Arumugam, M. Nesterenko, A. Vora, and M. Miyashita, “A line in thesand: a wireless sensor network for target detection, classification, andtracking,” Computer Networks, vol. 46, no. 5, pp. 605–634, 2004.

[9] C. Hartung, R. Han, C. Seielstad, and S. Holbrook, “Firewxnet: a multi-tiered portable wireless system for monitoring weather conditions in wild-land fire environments,” in Proceedings of the 4th international conferenceon Mobile Systems, Applications and Services (MobiSys ’06), pp. 28–41,2006.

108

Page 121: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

BIBLIOGRAPHY 109

[10] D. Hughes, K. Thoelen, W. Horre, N. Matthys, J. del Cid, S. Michiels,C. Huygens, W. Joosen, and J. Ueyama, “Building wireless sensor networkapplications with looci,” International Journal of Mobile Computing andMultimedia Communications, vol. 2, no. 4, pp. 38–64, 2010.

[11] A. Deshpande, C. Guestrin, and S. R. Madden, “Resource-aware wirelesssensor-actuator networks,” IEEE Data Engineering, vol. 28, no. 1, 2005.

[12] I. Maier, T. Rompf, and M. Odersky, “Deprecating the observer pattern,”tech. rep., Ecole Polytechnique Federale de Lausanne, Lausanne, Switzer-land, 2010.

[13] P. T. Eugster, P. A. Felber, R. Guerraoui, and A.-M. Kermarrec, “Themany faces of publish/subscribe,” ACM Computing Surveys, vol. 35,pp. 114–131, 2003.

[14] S. Madden, M. J. Franklin, J. M. Hellerstein, and W. Hong, “Tag: a tinyaggregation service for ad-hoc sensor networks,” ACM SIGOPS OperatingSystems Review, vol. 36, pp. 131–146, 2002.

[15] Y. Yao and J. Gehrke, “The cougar approach to in-network query process-ing in sensor networks,” ACM SIGMOD Record, vol. 31, no. 3, pp. 9–18,2002.

[16] C. Srisathapornphat, C. Jaikaeo, and C. chung Shen, “Sensor informationnetworking architecture and applications,” IEEE Personal Communica-tions, vol. 8, no. 4, pp. 52–59, 2001.

[17] R. Newton, G. Morrisett, and M. Welsh, “The regiment macroprogrammingsystem,” in Proceedings of the 6th international conference on InformationProcessing in Sensor Networks (IPSN ’07), pp. 489–498, 2007.

[18] K. Whitehouse, J. Liu, and F. Zhao, “Semantic streams: a framework forcomposable inference of sensor data,” in Proceedings of the 3rd EuropeanWorkshop on Wireless Sensor Networks (EWSN ’06), pp. 5–20, 2006.

[19] S. Li, Y. Lin, S. H. Son, J. A. Stankovic, and Y. Wei, “Event detectionservices using data service middleware in distributed sensor networks,”Telecommunication Systems, vol. 26, no. 2, pp. 351–368, 2004.

[20] J. Hill, R. Szewczyk, A. Woo, S. Hollar, D. Culler, and K. Pister, “Systemarchitecture directions for networked sensors,” ACM SIGPLAN Notices,vol. 35, no. 11, pp. 93–104, 2000.

[21] D. Simon, C. Cifuentes, D. Cleal, J. Daniels, and D. White, “Java (tm) onthe bare metal of wireless sensor devices: the squawk java virtual machine,”in Proceedings of the 2nd international conference on Virtual ExecutionEnvironments (VEE ’06), pp. 78–88, 2006.

[22] D. Gay, P. Levis, R. von Behren, M. Welsh, E. Brewer, and D. Culler, “Thenesc language: A holistic approach to networked embedded systems,” ACMSIGPLAN Notices, vol. 38, no. 5, pp. 1–11, 2003.

Page 122: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

BIBLIOGRAPHY 110

[23] D. E. Culler, J. Hill, P. Buonadonna, R. Szewczyk, and A. Woo, “Anetwork-centric approach to embedded software for tiny devices,” in Pro-ceedings of the 1st international workshop on Embedded Software (EM-SOFT ’01), pp. 114–130, 2001.

[24] L. Mottola and G. P. Picco, “Logical neighborhoods: A programming ab-straction for wireless sensor networks,” in Proceedings of the 2nd interna-tional conference on Distributed Computing in Sensor Systems (DCOSS’06) (P. Gibbons, T. Abdelzaher, J. Aspnes, and R. Rao, eds.), no. 4026 inLecture Notes on Computer Science, (San Francisco (CA, USA)), pp. 150–167, Springer, June 2006.

[25] D. Hughes, K. Thoelen, W. Horre, N. Matthys, J. D. Cid, S. Michiels,C. Huygens, and W. Joosen, “Looci: a loosely-coupled component infras-tructure for networked embedded systems,” in Proceedings of the 7th in-ternational conference on Advances in Mobile Computing and Multimedia(MoMM ’09), pp. 195–203, 2009.

[26] M. Welsh and G. Mainland, “Programming sensor networks using abstractregions,” in Proceedings of the 1st conference on Symposium on NetworkedSystems Design and Implementation (NSDI ’04), vol. 1, 2004.

[27] P. Costa, L. Mottola, A. L. Murphy, and G. P. Picco, “Programming wire-less sensor networks with the teenylime middleware,” in Proceedings of theACM/IFIP/USENIX 2007 international conference on Middleware (Mid-dleware ’07), pp. 429–449, 2007.

[28] K. Terfloth, G. Wittenburg, and J. Schiller, “Facts - a rule-based middle-ware architecture for wireless sensor networks,” in Proceedings of the 1stinternational conference on COMmunication System softWAre and Mid-dlewaRE (COMSWARE ’06), pp. 1–8, 2006.

[29] D. Gelernter, “Generative communication in linda,” ACM Transactions onProgramming Languages and Systems (TOPLAS), vol. 7, no. 1, pp. 80–112,1985.

[30] R. Gummadi, O. Gnawali, and R. Govindan, “Macro-programming wirelesssensor networks using kairos,” in Proceedings of the international conferenceon Distributed Computing in Sensor Systems (DCOSS), 2005.

[31] D. Chu, L. Popa, A. Tavakoli, J. M. Hellerstein, P. Levis, S. Shenker, andI. Stoica, “The design and implementation of a declarative sensor networksystem,” in Proceedings of the 5th international conference on Embeddednetworked Sensor Systems (SenSys ’07), pp. 175–188, 2007.

[32] C. Borcea, C. Intanagonwiwat, P. Kang, U. Kremer, and L. Iftode, “Spa-tial programming using smart messages: Design and implementation,” inProceedings of the 24th International Conference on Distributed ComputingSystems (ICDCS’04), pp. 690–699, 2004.

[33] Y. Ni, U. Kremer, A. Stere, and L. Iftode, “Programming ad-hoc networksof mobile and resource-constrained devices,” in Proceedings of the 2005ACM SIGPLAN conference on Programming language design and imple-mentation (PLDI ’05), pp. 249–260, 2005.

Page 123: Language Support for Programming Interactions among ...prog.vub.ac.be/~cderoove/publications/master_thesis_wouter_amerijckx.pdfLanguage Support for Programming Interactions among Wireless

BIBLIOGRAPHY 111

[34] G. A. Agha, I. A. Mason, S. F. Smith, and C. L. Talcott, “A foundationfor actor computation,” Journal of Functional Programming, vol. 7, no. 1,pp. 1–72, 1997.

[35] A. Bakshi, V. K. Prasanna, J. Reich, and D. Larner, “The abstract taskgraph: a methodology for architecture-independent programming of net-worked sensor systems,” in Proceedings of the 2005 workshop on End-to-End, Sense-and-Respond systems, applications and services (EESR ’05),pp. 19–24, 2005.

[36] A. Pathak, L. Mottola, A. Bakshi, V. K. Prasanna, and G. P. Picco, “Ex-pressing sensor network interaction patterns using data-driven macropro-gramming,” in Proceedings of the 5th IEEE international conference onPervasive Computing and Communications Workshops (PERCOMW ’07),pp. 255–260, 2007.

[37] C. Forgy, “Rete: A fast algorithm for the many pattern / many objectpattern match problem,” Artificial Intelligence, vol. 19, pp. 17–37, 1982.

[38] K.-U. Schmidt, R. Stuhmer, and L. Stojanovic, “Blending complex eventprocessing with the rete algorithm,” in iCEP2008: 1st international work-shop on Complex Event Processing for the Future Internet colocated withthe Future Internet Symposium (FIS ’08), 2008.

[39] M. Perlin, “Scaffolding the rete network,” in Proceedings of the 2nd Inter-national IEEE Conference on Tools for Artificial Intelligence (ICTAI ’90),pp. 378–385, 1990.

[40] C. Scholliers and E. Philips, “Coordination in volatile networks,” Master’sthesis, Vrije Universiteit Brussel, 2007.