Context Management in a Pervasive System · noise. La tesi presente descrive le fasi del design di...

99
POLITECNICO DI MILANO Facoltà di Ingegneria dell’Informazione Corso di Laurea Magistrale in Ingegneria Informatica Context Management in a Pervasive System Relatore: Prof. Fabio A. Schreiber Tesi di Laurea di: SABATINO RACHELE Matr. 819191 Anno Accademico 2014 - 2015

Transcript of Context Management in a Pervasive System · noise. La tesi presente descrive le fasi del design di...

Page 1: Context Management in a Pervasive System · noise. La tesi presente descrive le fasi del design di caratteristiche context-aware e il loro sviluppo integrato ad un middleware pervasivo

POLITECNICO DI MILANO

Facoltà di Ingegneria dell’Informazione

Corso di Laurea Magistrale in Ingegneria Informatica

Context Management in

a Pervasive System

Relatore: Prof. Fabio A. Schreiber

Tesi di Laurea di:

SABATINO RACHELE

Matr. 819191

Anno Accademico 2014 - 2015

Page 2: Context Management in a Pervasive System · noise. La tesi presente descrive le fasi del design di caratteristiche context-aware e il loro sviluppo integrato ad un middleware pervasivo

Contents

Chapter 1 Introduction1.1 Pervasive computing . . . . . . . . . . . . . . . . . . . . . . . . 11.2 The notion of Context . . . . . . . . . . . . . . . . . . . . . . . 31.3 Thesis objectives and organisation . . . . . . . . . . . . . . . . . 4

Chapter 2 State of the Art2.1 Contextual Information . . . . . . . . . . . . . . . . . . . . . . . 7

2.1.1 Context model . . . . . . . . . . . . . . . . . . . . . . . 82.2 Short survey of Context-Aware Middleware . . . . . . . . . . . . 92.3 Examples of Context-Aware Frameworks . . . . . . . . . . . . . 132.4 The PerLa System . . . . . . . . . . . . . . . . . . . . . . . . . 15

2.4.1 FPC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162.4.2 Communication . . . . . . . . . . . . . . . . . . . . . . . 172.4.3 Script and Operations . . . . . . . . . . . . . . . . . . . 182.4.4 PerLa Language . . . . . . . . . . . . . . . . . . . . . . . 182.4.5 Low Level Queries . . . . . . . . . . . . . . . . . . . . . 192.4.6 Java object representation of the Query Language . . . . 22

Chapter 3 Context-Awareness at Design Time3.1 Context-aware system overview . . . . . . . . . . . . . . . . . . 253.2 Initial steps for a Context-Aware PerLa . . . . . . . . . . . . . . 263.3 Context Model . . . . . . . . . . . . . . . . . . . . . . . . . . . 26

3.3.1 The basic structure of the context model . . . . . . . . . 263.3.2 Example of a CDT . . . . . . . . . . . . . . . . . . . . . 27

3.4 Context Language . . . . . . . . . . . . . . . . . . . . . . . . . . 293.4.1 CDT Declaration . . . . . . . . . . . . . . . . . . . . . . 293.4.2 Context inference . . . . . . . . . . . . . . . . . . . . . . 323.4.3 Context creation . . . . . . . . . . . . . . . . . . . . . . 32

3.5 Partial components . . . . . . . . . . . . . . . . . . . . . . . . . 333.5.1 CDT Declaration example . . . . . . . . . . . . . . . . . 34

3.6 Final consideration . . . . . . . . . . . . . . . . . . . . . . . . . 37Chapter 4 Parser for Context Language

4.1 Utility classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40

ii

Page 3: Context Management in a Pervasive System · noise. La tesi presente descrive le fasi del design di caratteristiche context-aware e il loro sviluppo integrato ad un middleware pervasivo

CONTENTS

4.2 CDT Creation . . . . . . . . . . . . . . . . . . . . . . . . . . . . 424.2.1 Create Dimension clause . . . . . . . . . . . . . . . . . . 424.2.2 Create Attribute clause . . . . . . . . . . . . . . . . . . . 444.2.3 Create Concept clause . . . . . . . . . . . . . . . . . . . 45

4.3 Context Definition . . . . . . . . . . . . . . . . . . . . . . . . . 484.4 UML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49

Chapter 5 Context Awareness at Run Time5.1 Context Manager . . . . . . . . . . . . . . . . . . . . . . . . . . 53

5.1.1 The Composer Manager . . . . . . . . . . . . . . . . . . 545.1.2 Mapping raw data to contextual information . . . . . . . 56

5.2 Context Detector Component . . . . . . . . . . . . . . . . . . . 595.3 Context Executor . . . . . . . . . . . . . . . . . . . . . . . . . . 60

5.3.1 Context history . . . . . . . . . . . . . . . . . . . . . . . 615.3.2 Context distribution . . . . . . . . . . . . . . . . . . . . 62

5.4 Conflict management . . . . . . . . . . . . . . . . . . . . . . . . 655.4.1 Conflict Detection in PerLa . . . . . . . . . . . . . . . . 67

Chapter 6 Study case6.1 A ski resort application . . . . . . . . . . . . . . . . . . . . . . . 69

6.1.1 Description of the environment . . . . . . . . . . . . . . 706.2 Database . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 726.3 CDT schema . . . . . . . . . . . . . . . . . . . . . . . . . . . . 726.4 Netowork topology . . . . . . . . . . . . . . . . . . . . . . . . . 776.5 Context . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78

Chapter 7 Conclusions7.1 Final consideration . . . . . . . . . . . . . . . . . . . . . . . . . 817.2 Open points . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83

Chapter 8 Appendix8.1 XLM Device Description of a snow sensor . . . . . . . . . . . . 85

Bibliography

iii

Page 4: Context Management in a Pervasive System · noise. La tesi presente descrive le fasi del design di caratteristiche context-aware e il loro sviluppo integrato ad un middleware pervasivo

List of Figures

1.1 An example of a context-aware system . . . . . . . . . . . . . . 2

2.1 Layered conceptual architecture for context-aware systems . . . 92.2 Cassowary Deployment Architecture . . . . . . . . . . . . . . . 112.3 CASS architecture . . . . . . . . . . . . . . . . . . . . . . . . . 122.4 The Runtime Architecture of the JCAF Framework . . . . . . . 142.5 Sentient object model . . . . . . . . . . . . . . . . . . . . . . . . 152.6 PerLa achitecture . . . . . . . . . . . . . . . . . . . . . . . . . . 162.7 Execution of a user request in a FPC . . . . . . . . . . . . . . . 192.8 Query partial internal representation . . . . . . . . . . . . . . . 23

3.1 An example of CDT Schema . . . . . . . . . . . . . . . . . . . . 283.2 An example of useless context constraints . . . . . . . . . . . . . 283.3 Contextual block components . . . . . . . . . . . . . . . . . . . 333.4 Division of the enable component into enable partial components 34

4.1 Expression partial UML . . . . . . . . . . . . . . . . . . . . . . 414.2 ParserContext class . . . . . . . . . . . . . . . . . . . . . . . . . 424.3 Internal representation of the CDT . . . . . . . . . . . . . . . . 504.4 Internal representation of a Context . . . . . . . . . . . . . . . . 50

5.1 New context-aware PerLa . . . . . . . . . . . . . . . . . . . . . 515.2 Procedure flow of context-aware PerLa . . . . . . . . . . . . . . 525.3 Sequence diagram of an asynchronous query execution operation 585.4 Example of the cache containing the current state of the CDT . 595.5 Sequence diagram of the distribution of context events . . . . . 64

6.1 ER diagram for a ski resort . . . . . . . . . . . . . . . . . . . . 716.2 Example of a CDT for a ski resort . . . . . . . . . . . . . . . . . 736.3 Livigno ski resort map . . . . . . . . . . . . . . . . . . . . . . . 78

iv

Page 5: Context Management in a Pervasive System · noise. La tesi presente descrive le fasi del design di caratteristiche context-aware e il loro sviluppo integrato ad un middleware pervasivo

Listings

2.1 LLQ Selection Definition . . . . . . . . . . . . . . . . . . . . . . 202.2 Example of a Create PerLa Query . . . . . . . . . . . . . . . . . 222.3 Example of a Selection PerLa Query . . . . . . . . . . . . . . . 223.1 CDT declaration syntax . . . . . . . . . . . . . . . . . . . . . . 293.2 Example of use of clauses when/evaluated on . . . . . . . . . . . 303.3 Context creation syntax . . . . . . . . . . . . . . . . . . . . . . 323.4 CDT declaration of the wine production monitoring . . . . . . . 353.5 Concept Frost definition . . . . . . . . . . . . . . . . . . . . . . 363.6 Concept Overheat definition . . . . . . . . . . . . . . . . . . . . 363.7 Concept Growth definition . . . . . . . . . . . . . . . . . . . . . 363.8 Context Frost Alert definition . . . . . . . . . . . . . . . . . . . 373.9 Context Transport Monitoring definition . . . . . . . . . . . . . 374.1 Start of CDT grammar production . . . . . . . . . . . . . . . . 424.2 Creating a Dimension . . . . . . . . . . . . . . . . . . . . . . . . 444.3 Creating an Attribute . . . . . . . . . . . . . . . . . . . . . . . 454.4 Creating a Concept . . . . . . . . . . . . . . . . . . . . . . . . . 464.5 Context Production . . . . . . . . . . . . . . . . . . . . . . . . . 484.6 Active if Production . . . . . . . . . . . . . . . . . . . . . . . . 484.7 Simple Context Element Production . . . . . . . . . . . . . . . 494.8 Complex Contect Element Production . . . . . . . . . . . . . . 495.1 The ContextManager class . . . . . . . . . . . . . . . . . . . . . 535.2 The IComposerManager Interface . . . . . . . . . . . . . . . . . 555.3 The Query Executor class . . . . . . . . . . . . . . . . . . . . . 575.4 The StatementHandler class . . . . . . . . . . . . . . . . . . . . 575.5 The StatementTask interface . . . . . . . . . . . . . . . . . . . . 585.6 The ContextExecutor class . . . . . . . . . . . . . . . . . . . . . 615.7 The IConflictManager Interface . . . . . . . . . . . . . . . . . . 67

v

Page 6: Context Management in a Pervasive System · noise. La tesi presente descrive le fasi del design di caratteristiche context-aware e il loro sviluppo integrato ad un middleware pervasivo
Page 7: Context Management in a Pervasive System · noise. La tesi presente descrive le fasi del design di caratteristiche context-aware e il loro sviluppo integrato ad un middleware pervasivo

Sommario

Negli ultimi anni, il paradigma di ubiquitous computing ha mirato alla creazionedi ambienti intelligenti tramite l’uso di dispositivi embedded che forniscono con-nettivita e servizi in ogni momento nascondendo la loro presenza e migliorando inquesto modo l’esperienza dell’utente. Essere percepito come invisibile e lo scopoultimo di un sistema pervasivo che si adatta a nuove situazioni senza il bisogno diun diretto intervento dell’utente. Adattarsi a cambiamenti nell’ambiente richiedel’abilita di distinguere diverse situazioni o contesti. I sistemi context-awaremigliorano il comportamento di un’applicazione: raccolgono dati dall’ambiente,li interpretano riconoscendo il contesto in cui stanno operando e adattano ilsistema di conseguenza. Il comportamento context-aware puo influenzare sial’esecuzione di azioni specifiche, sia il filtraggio, tailoring, delle informazionisulla base delle preferenze dell’utente riducendo cosı il cosiddetto informationnoise. La tesi presente descrive le fasi del design di caratteristiche context-aware e il loro sviluppo integrato ad un middleware pervasivo chiamato PerLa.Originariamente concepito solo per la gestione e l’interrogazione di una rete disensori, PerLa e stato espanso con funzionalita per: 1) definire l’ambiente conuno modello adatto; 2) creare un contesto sulla base del modello definito; 3)acquisire dati da sensori e input esterni che definiscono uno specifico contesto;4) attivare o disattivare un contesto a run-time a seconda dei valori attuali dellevariabili di contesto; 5) eseguire le azioni di un contesto sul sistema.

vii

Page 8: Context Management in a Pervasive System · noise. La tesi presente descrive le fasi del design di caratteristiche context-aware e il loro sviluppo integrato ad un middleware pervasivo

Abstract

In recent years, ubiquitous computing aimed at creating intelligent environmentsby embedding devices that provide connectivity and services all the time hidingtheir presence, improving in this way the human experience. The ultimategoal of a pervasive system is to be perceived as invisible, adapting to newsituations without the direct intervention of the user. Adapting to changesin the environment requires the ability of distinguishing different situationsor contexts. Context-aware systems enhance the behaviour of an applicationby gathering data from the environment, interpreting them recognising thecontext in which the system operates and adapting the system accordingly. Thecontext-aware behaviour can affect both the execution of specific actions andthe tailoring of information on the base of the user’s preferences reducing theinformation noise. The present thesis describes the phases of design of context-aware features and their development to a pervasive middleware called PerLa.Originally conceived only for managing and querying a network of sensors,PerLa has been integrated with functionalities to: 1) define the environmentwith a suitable model; 2) create a context on the defined model; 3) acquire thesensor readings and external inputs which define a specific context; 4) activateor deactivate a context at run-time depending on the actual values of the contextvariables; 5) perform the context actions on the system.

viii

Page 9: Context Management in a Pervasive System · noise. La tesi presente descrive le fasi del design di caratteristiche context-aware e il loro sviluppo integrato ad un middleware pervasivo

Chapter 1

Introduction

1.1 Pervasive computing

The aim of developers in creating applications or systems, is the easiness of usefor the final user which depends on a number of factors like the intended user,his experience or the technical constraints; the set of these aspects is calledthe context of use. In earliest days of computing, the context in which systemswere used was strongly limited by the place in which computers were set, theydid not change easily location, hence, there was no need to adapt to differentenvironments. With the advent of mobile computers and ubiquitous computing,this limitation disappeared as users carried computers with them and used themin many different situations.

In the early 90s, starting with the initial effort of providing the same services tothe user independently of his environment, a new approach started to attract theattention of researchers. Bill Schilit [1] introduced the concept of context-awarecomputing as a software able to adapt itself according to the location of use,nearby people, devices as well as time. In short, a system that can examine, sensethe environment and react to changes detected in the environment. The conceptof context-awareness expanded and integrated another computing paradigm,presented a couple of years before, called ubiquitous computing.

Widely regarded as the father of ubiquitous computing, Mark Weiser, in his work“The Computer for the 21st Century” [2] envisaged a world where computerswould have gradually disappeared into the everyday life background until theywould have been indistinguishable from it. Weiser was aware that this visionwas, at that time, too far away from becoming reality as in order to achievesuch disappearance, technologies had to evolve and produce: cheap, low-power

1

Page 10: Context Management in a Pervasive System · noise. La tesi presente descrive le fasi del design di caratteristiche context-aware e il loro sviluppo integrato ad un middleware pervasivo

Chapter 1. Introduction

computers, communication networks and ad-hoc software systems.

Nowadays developments in technologies such as wireless communications andnetworking, mobile computing and handheld devices, embedded systems, wear-able computers, sensors, RFID tags and similar, have led to make real MarkWeiser’s vision. However, advanced hardware technologies are not sufficient bythemselves to fully disappear, technologies have to anticipate the user’s needfreeing him from a direct intervention and acting accordingly. This means tobe aware of the surroundings, to have a context-aware behaviour.

Ubiquitous computing, or pervasive computing has been one of the fastest-growing research areas. It aimed at creating intelligent environments by embed-ding devices which provide connectivity and services all the time, improving inthis way human experience and quality of life. In this environment, the worldaround us is interconnected as a pervasive network of intelligent devices thatcooperatively and autonomously collect, process and transport information, inorder to adapt to different situations. An example of a pervasive system is theWireless Sensors Networks (WSN), a network composed of spatially distributedsensors nodes. Each node is a low-power device that integrates processing,sensing and wireless communication abilities. Sensor nodes acquire informationfrom the surrounding environment, process locally the data, and/or send themto one or more collection base stations. They are useful for the monitoring ofphysical environment conditions like temperature, pressure, light or location.

Figure 1.1. An example of a context-aware system

2

Page 11: Context Management in a Pervasive System · noise. La tesi presente descrive le fasi del design di caratteristiche context-aware e il loro sviluppo integrato ad un middleware pervasivo

1.2. The notion of Context

1.2 The notion of Context

In order to consider context effectively, it is important to understand what itis and how it can be used. It can be difficult to give a precise definition; inthe years, many researchers have considered context differently according totheir field of research. In literature, the first attempt of definition was given byBill Schilit as the location of use, the collection of nearby people, hosts, andaccessible devices, as well as to changes over time [1]. A system with thesecapabilities can examine the computing environment and react to changes inthe environment. He developed one of the first pioneer context-aware systemscalled PARCTAB [3] where he tried to integrate the notion of context to mobilecomputers used into an office network with the goal of demonstrating thepotential for innovation in that area. The device registered the user’s id andrough location and on the base of this data, different information and controlchoices where available.

In [4] the author Dey complained about the lack of a clear definition with theresult that it was difficult to have a clear idea of what context was and howit could be effectively used as a source of information in a real operationalapplication. This was due to the fact that the majority of authors [5] definedcontext by examples or synonyms and, as consequence, the practical usefulnessof these definitions was limited. For this reason, Dey presented his definition:

”Context is any information that can be used to characterize the situation ofan entity. An entity can be a person, place or object that is considered relevantto the interaction between a user and an application, including the user andapplications themselves”.

Context enables to guide the user through the vast amount of informationthat surrounds him by helping him in discriminating what it is important fromwhat can be ignored. Since the amount of information can grow rapidly andgenerate confusion, information needs to be filtered adequately so that onlyrelevant information is presented to the user. In addition to prevent uselessinformation to be provided to the user, tailoring the data allows reducing thedevices’ computational effort and hardware physical constraints in dealing withmanageable amount of data. Probably, one of the most significant and widelyused context-aware service is Google search engine which returns query resultswith an order based on many factors like the user’s location, web history andnavigation, in a word, his context. Another system that can be considered ascontext-aware are the automatic lights in a building. The contextual parameterstaken into account are the current light conditions and if there is motion in thevicinity. The adaptation mechanism is fairly simple. If the situation detected is

3

Page 12: Context Management in a Pervasive System · noise. La tesi presente descrive le fasi del design di caratteristiche context-aware e il loro sviluppo integrato ad un middleware pervasivo

Chapter 1. Introduction

that it is dark and that there is someone moving, the light will be switched on.The light will then be on as long as the person moves, and after a period whereno motion is detected, the light will switch off again.

For a human being, context is often implicit (who I am talking to, where Iam, what I am talking about), but an application needs a conceptual modelto rely on and translate the information into a meaningful context on whichto act. A typical context-aware system acquires data gathered from the realworld through sensors, processes the data with some perception algorithm onthe base of the context model, recognizes in which context it runs and finally ittriggers specific actions.

1.3 Thesis objectives and organisation

Researchers have been investigating many issues of context-aware computing:sensing the environment, context modelling, representation, context inference,knowledge sharing and developing tools and architecture to choose the bestway to effectively acquire, represent, and make use of sensed data for providingcontext-aware services to applications. However, developing context-awaremiddleware is still a great challenge.

This thesis describes the design and implementation of components which providecontext-aware services to allow an existing middleware for pervasive systemscalled PerLa, to be context sensitive. PerLa is a project born at the Politecnicodi Milano in 2005 when two students worked on a common thesis about thedefinition of a language, called PerLa Language, for the interrogation of sensorsbelonging to a WSN. In the following years, other students collaborated in theimplementation of the software needed to manage a network of sensors and toquery it by exploiting the PerLa Language. As a result, today PerLa can be fullyconsidered as a language and infrastructure for data management in pervasivesystems, able to gather data sensed from various heterogeneous devices, toquery them and to easily add a new device to the sensor network. Nevertheless,there is still space for improvement with the addition of new features like energyreduction strategies or the expansion to support context-aware applications, thelast topic is the main topic of this thesis. The basic idea is to rely on the datasensed from the underlying sensor network already managed by the existingmiddleware and used this information to recognize a context and change thebehaviour of the devices accordingly.

4

Page 13: Context Management in a Pervasive System · noise. La tesi presente descrive le fasi del design di caratteristiche context-aware e il loro sviluppo integrato ad un middleware pervasivo

1.3. Thesis objectives and organisation

The rest of this thesis is organised as follows:

• Chapter 2 presents part of the literature concerning the concept of contextand some of the most recent and interesting context-aware systems. Then,a full overview of the architecture and main features of PerLa is describedwhich acts as the basis for a fuller understanding of the pervasive systemwhich will be the main actor during the rest of this work.

• Chapter 3 describes the formal context model and language used by PerLato define and store context data in a machine processable form.

• Chapter 4 and 5 focus on the components which are responsible forthe flow of operations required to manage the context-awareness fromthe building and storing of the context model to retrieve the relevantcontextual information which allows to distinguish the context in whichthe system is operating and finally to execute the actions defined in theactive context.

• Chapter 6 contains a simulated and simplified example of a scenariowhere the context-aware PerLa middleware can be deployed showing theadvantages and potential use of this system.

• Chapter 7 draws the conclusion and perspective of possible future works.

5

Page 14: Context Management in a Pervasive System · noise. La tesi presente descrive le fasi del design di caratteristiche context-aware e il loro sviluppo integrato ad un middleware pervasivo
Page 15: Context Management in a Pervasive System · noise. La tesi presente descrive le fasi del design di caratteristiche context-aware e il loro sviluppo integrato ad un middleware pervasivo

Chapter 2

State of the Art

2.1 Contextual Information

Context-awareness represents an important evolution of distributed computing.Awareness of the environment state helps applications to adapt their function-alities depending on context changes without the direct interaction with theuser. A system becomes aware of its surroundings when it receives some inputswhich make it possible to detect determined situations. It needs contextualinformation, that is any data gathered at a given point in time from sensors,applications or users, that enables the system to perceive a specific context.Information have many characteristics: it can be static or dynamic, about thepast or the present, inconsistent or incomplete due to a faulty transmission andhas many alternative representations. Typical questions that a developer mustconsider before starting to implement a context-aware system concern the choiceof the type and number of sensors needed, how often query or retrieve datafrom the several sources or how to represent different kinds of values trying tomake uniform the information in a common format. With regard to the methodof acquisition, as suggested by Chen in [6] there are three different approaches:

• Direct sensor access. The client software gathers the desired informationdirectly from sensors; this means that there is no additional layer forgathering and processing sensor data. Due to its tightly coupled nature,this approach is not suitable for distributed systems where there is theneed of a component capable of managing multiple concurrent sensoraccesses.

• Middleware infrastructure. The middleware-based approach introduces alayered architecture which hides the low-level sensing details and manages

7

Page 16: Context Management in a Pervasive System · noise. La tesi presente descrive le fasi del design di caratteristiche context-aware e il loro sviluppo integrato ad un middleware pervasivo

Chapter 2. State of the Art

the data retrieval, processes the data, recognize context changes andexecute the context behavior.

• Context server. The next logical step is to permit multiple clients access toremote data sources. This distributed approach extends the middleware-based architecture by introducing a remote component, called contextserver, that is responsible for providing an access point for sharing contextdata.

2.1.1 Context model

Context-aware applications adapt their behavior to changing context informa-tion gathered from a variety of sources that differ in the quality and type ofinformation they produce. As indicated in [7] there is usually a significant gapbetween sensor outputs and the type of information that is useful to applicationsand this gap may be bridged by adequate reasoning techniques and contextinformation processing and modelling. For example, a location sensor suppliesraw coordinates, whereas an application is interested in which building or rooma user is. A context model has the aim of representing in a compact, butexhaustive method, which environment characteristics, information or dataidentify and give a meaning to a specific context. The works presented in [8]and [9] give an overview on various common context models, in particular:

• Key-Value: use unstructured set of simple key value pairs to defineattributes and their values describing context information, for example[User = ’John Black’, Place = ’Office1’, Time = ’Y’ ]. Due to its simplicity,this model is often used.

• Markup: use a hierarchical data structure consisting of markup tags (likeXML tag) with attributes and content to create profiles. This approachextends the key-value model as it also contains the relationship betweenthe stored information, called context features.

• Graphical: use a graphical model which represents context’s elementsand their relationships; the standard is the Unified Modelling Language.

• Object-oriented: use various objects to represent different types (suchas temperature, location, etc.), and encapsulate the details of contextprocessing and representation. Access to the context and to the contextprocessing logic is provided by interfaces

• Ontologies: represent a description of the concepts and relationships.

8

Page 17: Context Management in a Pervasive System · noise. La tesi presente descrive le fasi del design di caratteristiche context-aware e il loro sviluppo integrato ad un middleware pervasivo

2.2. Short survey of Context-Aware Middleware

An ontology is the most complete model that guarantee a high degreeof expressiveness and semantic richness. The major drawback is thecomplexity of implementation and the heaviness of reasoning on theirfacts and entities.

2.2 Short survey of Context-Aware Middleware

During the development of context-aware systems, several challenging require-ments must be taken into consideration such as the location of sensors, thenumber of possible users, the type and limitations of used devices, the scalabilityof the system and data acquisition. In order to cope with these challengingrequirements, during the past years, many layered context-aware systems andframeworks have been developed, each using several solutions and tools toeffectively acquire, represent and reason on sensed and inferred data. Baldauf[10], after the analysis of various design approaches, concludes that, apart fromminor differences in functionalities, naming of the main components or the useof optional agents, it is possible to identify a common architecture structuredin five layers as represented in Figure 2.1:

Figure 2.1. Layered conceptual architecture for context-aware systems

• Sensors: It consists of every data sources which provide usable contextinformation. The term sensor does not refer only to sensing devices butdesignated any data source that is able to produce context information.They are usually categorized in physical sensors if they capture physicaldata, virtual when they provide data from software applications or logicalwhen data is retrieved from databases.

• Raw data retrieval : It is responsible for the retrieval of raw context databy means of appropriate drivers for sensors.

9

Page 18: Context Management in a Pervasive System · noise. La tesi presente descrive le fasi del design di caratteristiche context-aware e il loro sviluppo integrato ad un middleware pervasivo

Chapter 2. State of the Art

• Preprocessing : It deals with reasoning, aggregation and interpretation ofdata retrieved by sensors that are not appropriate to be directly used byapplication designers.

• Storage/Management : It stores and organizes the gathered data and offersthem to the client via a public interface. Usually, it is possible to querythe system either synchronously by sending a request of asynchronouslyby subscriptions.

• Application: It implements the actions on different events and contextchanges.

Based on these design principles, some of the most significant and recent contextaware middlewares and frameworks are presented, with a focus on how theyfollow the mentioned conceptual architecture. A very comprehensive analysis ofother projects active in this research field can be found in [11].

CassowaryCassowary is a middleware platform for smart buildings that relies on a Software-Defined Sensor Network (SDN) in order to coordinate and connect the smartdevices and sensors to a logically centralized controller and messaging broker[12]. The communication used to propagate the details sensed by the sensors ofthe heterogeneous devices depends on the message oriented middleware (MOM).It designs and builds a sensor network, connecting each of the devices in thesmart building.

The goal of Cassowary is to leverage the contextual information derived fromthe sensor readings to satisfy system requirements such as energy and carbonefficiency, user preferences and to give more control to user tenants. Configura-tion details such as profiles and policies are stored inside an in-memory datastore and they are parsed and managed by specific components.

Cassowary has been designed with a layered architecture consisting of twocore layers. The network layer, which consists of the SDN controller and datasensors and the appliance layer, which is responsible for the integration andexecution of the smart appliances. This means that the network layer groups theconceptual layers Sensors, Raw Data Retrieval and Storage, while the appliancelayer corresponds to the Application layer ( 2.2).

10

Page 19: Context Management in a Pervasive System · noise. La tesi presente descrive le fasi del design di caratteristiche context-aware e il loro sviluppo integrato ad un middleware pervasivo

2.2. Short survey of Context-Aware Middleware

Figure 2.2. Cassowary Deployment Architecture

SOCAMThe Service-Oriented Context-Aware Middleware project introduced in [13],is an architecture for building and rapid prototyping of context-aware mobileservices. It converts physical spaces into contexts using an ontology-based modelthat leverages Semantic Web technology and OWL. Architecturally, SOCAMconsists of the following components which clearly map to the conceptualarchitectural layers:

• Context providers abstract useful contexts from heterogeneous sourcesand convert them to OWL representations.

• The context interpreter provides logic reasoning services to process contextinformation.

• The context database stores context ontologies and past contexts.

• Context-aware applications use different levels of contexts and adapt theway they behave according to the current context.

• The service-locating service (SLS) provides a mechanism so that contextproviders and the context interpreter can advertise their presence andusers and applications can locate these services.

It is a centralized architecture, where the central server, called Context Inter-

11

Page 20: Context Management in a Pervasive System · noise. La tesi presente descrive le fasi del design di caratteristiche context-aware e il loro sviluppo integrato ad un middleware pervasivo

Chapter 2. State of the Art

preter, gathers context data through distributed context providers and offers itin mostly processed form to the clients, the communication between componentsis implemented using Java RMI.

SOCAM’s key feature is its ability to reason about various contexts and throughthe reasoning process, high-level contexts can be derived from low-level ones. Italso incorporates the notion of uncertain contexts : sensed or deduced contextinformation that is likely, but not definitive. This is realized by introducing aprobability measure to predicates that can be reasoned about with Bayesiannetworks.

CASSContext-Awareness Sub-Structure (CASS), presented in [14], is a centralizedserver-based middleware that supports context-aware applications on mobileand other small computers connecting over wireless networks. The middlewaresupports the use of large numbers of context inputs and provides for high-levelcontext abstractions while placing no additional processing or memory loadon constrained mobile platforms. A key feature of CASS is the separation ofcontext based inferences and behaviors from the application code.

Figure 2.3. CASS architecture

In Figure 2.3, the system architecture is presented. The middleware containsan Interpreter, a ContextRetriever, a Rule Engine and a SensorListener. TheSensorListener listens for updates from sensors, then the gathered informationis stored in the database by the SensorListener. The ContextRetriever isresponsible for retrieving stored context data. Both of these classes mayuse the services of an interpreter. The ChangeListener is a component withcommunication capabilities that allow a mobile computer to listen for notification

12

Page 21: Context Management in a Pervasive System · noise. La tesi presente descrive le fasi del design di caratteristiche context-aware e il loro sviluppo integrato ad un middleware pervasivo

2.3. Examples of Context-Aware Frameworks

of context change events. Mobile clients connect to the server over wirelessnetworks.

The use of the database makes it easier to handle large volume of data andit has also the key advantage to store not only context, application and userdata but also domain knowledge in the form of context awareness rules andbehaviors relevant to specific applications. An inference engine uses the rulescontained in the knowledge base to find a matching goal when a change incontext is detected.

CAMPSCAMPS [15] is an agent-based middleware that provides support for applicationsto make use of contextual information in a smart space environment. It consistsof individual, collaborating agents:

• Context Wrapper. It acquires various types of raw context data fromdifferent sources both physical and virtual, such as software agents.

• Context Provider. It abstracts and represents contextual informationusing ontologies.

• Inference Engine. It provides an inference mechanism to infer high-levelcontext from low-level data.

• Knowledge Base. It stores inference rules, observed facts and ontologiesfor context data management and maintenance.

• Query Filter. It provides query interface to upper applications to queryor subscribe the context-aware services using a formal query language.

As context model, it uses a combination of First Order Probabilistic Logicwith OWL ontologies with the aim to reason about imperfect and ambiguouscontextual information and to enable context knowledge sharing and reuse.

2.3 Examples of Context-Aware Frameworks

Together with middlewares which usually address a specific situation or environ-ment like smart buildings in Cassowary or mobile devices in CASS, frameworksfocus on providing a systematic approach and guidelines that ease the de-velopment for general context-aware applications. Following there are twowell-defined example of frameworks.

13

Page 22: Context Management in a Pervasive System · noise. La tesi presente descrive le fasi del design di caratteristiche context-aware e il loro sviluppo integrato ad un middleware pervasivo

Chapter 2. State of the Art

JCAFJCAF [16] is a Java-based, lightweight and robust framework which programmerscan extend in support of the creation of context-aware applications. JCAF isdivided into two parts: a Runtime Infrastructure and API.

The first part consists of a range of Context Services, long-lived processes analogto a J2EE Application Server, which are connected in a Peer-to-Peer setup.Running inside a context service, a small Java program is called Entity andit responds to changes in its context. An Entity with its Context informationis managed by the service’s Entity Container. The entity container handlessubscribers to context events and notifies relevant clients on changes to entities.The Entity Environment allows communication and access to shared resourcesamong the Entity components in a Context Service. Context Clients can accessEntities and their Context information in two ways: either requesting entitiesand their context data, or by subscribing as an Entity Listener, listening forchanges to specific entities.

Figure 2.4. The Runtime Architecture of the JCAF Framework

The JCAF API enables the programmer to create context-aware applicationsthat are deployable in the JCAF infrastructure. A Context Service enablesclients to access entities and to set, get, and subscribe to changes in contextinformation for entities. The basic modeling concepts in the JCAF API are a setof core interfaces such as Entity, ContextService, ContextClients and EntityEn-vironment, which developers of context-aware applications must implement.

Sentient object model FrameworkThis framework [17] eases the development of mobile context-aware applicationsby supporting the application developer in many important aspects such as

14

Page 23: Context Management in a Pervasive System · noise. La tesi presente descrive le fasi del design di caratteristiche context-aware e il loro sviluppo integrato ad un middleware pervasivo

2.4. The PerLa System

providing an abstraction for sensors and actuators, reasoning on contexts, event-based communication between components and an easy visual programmingtool for reducing the amount of code written by the developer.

The abstraction of the low-level hardware devices is implemented by the defini-tion of the sentient object model which is an entity with sensors and actuatorsas its interface, as shown in Figure 2.5. Once sensor inputs are received, theinternal control logic is evaluated, consisting of event filtering, sensor fusionand intelligent inference and actuators are activated if needed. The inferencemechanism relies on CLIPS (C Language Integrated Production System), aninference engine built into the language which, given a set of facts and rules, isable to decide which rule to fire in different contexts. Sensor fusion addressesthe problem of the uncertainty of sensor data and derives higher level contextinformation from multi-modal data sources by employing Bayesian networks.An application designer can use the provided programming model which allowsto easily specify sensors, actuators, sentient objects and inference rules.

Figure 2.5. Sentient object model

2.4 The PerLa System

As extensively presented in [18], the PerLa system is a middleware to configureand manage pervasive systems and wireless sensor networks. The developmentof Perla focused on the design and implementation of the following features:

• data-centric view managing the system as a database where all the datagenerated by the sensing network are accessible by means of SQL-likequery language, called PerLa language;

• homogeneous interface to heterogeneous devices realized my means of aFunctionality Proxy Component;

15

Page 24: Context Management in a Pervasive System · noise. La tesi presente descrive le fasi del design di caratteristiche context-aware e il loro sviluppo integrato ad un middleware pervasivo

Chapter 2. State of the Art

• minimal coding effort for new device addition thanks to a Plug & Playdevice addition mechanism. After the Perla system receives from a node anXML Device Descriptor (a document containing all the information neededto interact with the already existing sensing network), it autonomouslyassembles every software component needed to handle the new node.

Figure 2.6. PerLa achitecture

From an architectural point of view, PerLa is composed of different modulesthat interact, as it is shown in Figure 2.6, where components are divided intotwo macro-layers:

• Low level support that provides homogeneous API to manage and operateall the different devices that compose the pervasive system;

• High level support that implements data management and query executionservices needed to interface end-users and applications with the pervasivesystem.

2.4.1 FPC

The main software module of the low level support layer is the FunctionalityProxy Component (FPC). An FPC is a Java object that provides a functional

16

Page 25: Context Management in a Pervasive System · noise. La tesi presente descrive le fasi del design di caratteristiche context-aware e il loro sviluppo integrato ad un middleware pervasivo

2.4. The PerLa System

abstraction of a given device or a group of them. It is used by other PerLamiddleware components to interact with the sensing node itself. The PerLalanguage is completely oblivious and independent with respect to the hardwareand software of the nodes. This means that the language is not tied to anyparticular type of sensing devices and the types of nodes are not limited tophysical ones but also virtual ones like REST services.

The information generated by the sensing node are abstracted as FPC Attributes.They can be used to retrieve the node state (like battery status or memoryoccupation), to access sampled data (like temperature or pressure) or to changesome parameters on the device (sampling frequency, node parameters, etc.).Attributes can be classified in three categories: static, probing dynamic andnon probing dynamic. Static attributes represent constant values that describeimmutable characteristics of the sensing node. They are commonly used to defineproperties like device name or location of stationary nodes. Probing dynamicattributes require the interaction of the FPC with the device to produce thevalue; they can be real sensors (e.g., temperature, humidity) or a real actuator.When a non probing dynamic attribute is read, the FPC returns the value storedin its local cache without an actual reading on the physical device.

A hardware device can host an FPC only if:

• it runs a Java Virtual Machine (JVM)

• it is connected to the PerLa Middleware via TCP/IP

The addition of new sensing devices to an existing network is facilitated by aPlug & Play connection system, a runtime factory that generates all the softwarecomponents needed to query new sensor nodes. The information required toautomatically assemble a device driver are stored in a XML file created by thenode developer. This file, the Device Descriptor, contains the details all thenode’s characteristics in terms of data structures, protocols of communication,computational capabilities, and behavioral patterns. All running queries willautomatically make use of every new node added in the system.

2.4.2 Communication

The PerLa middleware deals with the problem of the network heterogeneity(different physical means and communication protocols) with components calledChannels. These software modules perform I/O operations and are employedto manage the communication between PerLa and the sensing nodes. EachChannel corresponds to the implementation of an existing communicationprotocol and it is bundled with a collection of IORequest objects to initiate

17

Page 26: Context Management in a Pervasive System · noise. La tesi presente descrive le fasi del design di caratteristiche context-aware e il loro sviluppo integrato ad un middleware pervasivo

Chapter 2. State of the Art

I/O tasks on the sensing nodes. For example, the HTTPChannel contains fourtypes of requests, one for each of the principal HTTP methods. To interpretbyte streams received from a communication channel, Mapper objects are usedfor the marshalling and unmarshalling.

2.4.3 Script and Operations

Scripts and Operations bind high-level data requests to processing tasksperformed on the remote device. The first objects are programs for interactingwith the sensing nodes and for mapping low-level data structures to Attributesgenerated by an FPC. Operations are entities that regroups one or moreScripts dedicated to a specific purpose. Every Operation is associated withthe set of Attributes that can extract or set; there are four types of operations:

• Get: retrieves a single sample from the remote device;

• Set: transmits data to the remote device;

• Periodic: periodically retrieves the collection of data samples generatedby a node;

• Async: handles the reception of asynchronous events emitted by thenode.

Figure 2.7 illustrates the execution flow generated when a user requests someAttributes to a FPC. The FPC selects an Operation which initializes theScripts, in order to configure the remote device and start the collection of data.The request is marshalled into a Message which travels on the Channel to thephysical sensor node. The data sample produced by the sensor travels backand it is then processed by a Script which is tasked with unmarshalling theinformation and create an output record.

2.4.4 PerLa Language

The other fundamental component is the PerLa Query language, (designed byMarco Fortunato and Marco Marelli in their master thesis [19]) a declarativeSQL-like language, to query the system. It has been designed in order to fullyexploit the capabilities typical of sensing networks. PerLa queries allow:

• to retrieve data from the pervasive system with Low Level Queries (LLQ);

• to define data manipulation operations on streams generated by a LLQor other High Level Queries (HLQ). The syntax and semantics of thesestatements are similar to standard SQL.

18

Page 27: Context Management in a Pervasive System · noise. La tesi presente descrive le fasi del design di caratteristiche context-aware e il loro sviluppo integrato ad un middleware pervasivo

2.4. The PerLa System

Figure 2.7. Execution of a user request in a FPC

• to send asynchronous behavior requests with Actuation Queries (AQ) forsetting parameters of the devices or for sending commands to actuators.

User queries are received by the Query Parser that parses them and sendsthem to the Query Executor component that uses the abstraction of the physicalnodes (FPCs) to access the Attributes.

2.4.5 Low Level Queries

Low Level Queries define the behavior of every single node or of a homogeneousgroup of nodes and specify the data selection criteria, the sampling frequencyand the computation to be performed on sampled data. When a LLQ is injectedinto the system, the set of FPCs possessing the requirements to execute it iscomputed and an instance of the query is deployed on each element of theset. Data produced are stored in a database with the possibility of furthermanipulation or sent to the user or to the component who requested it.

19

Page 28: Context Management in a Pervasive System · noise. La tesi presente descrive le fasi del design di caratteristiche context-aware e il loro sviluppo integrato ad un middleware pervasivo

Chapter 2. State of the Art

A LLQ can be:

• a creation statement that defines the name of the data structure to becreated and the list of fields (it is similar to the CREATE TABLE inSQL)

• an insertion statement that defines the destination data structure and thereal query to be done on the sources

• a general selection statement that expresses the query to be sent to thenodes

The selection statement has the role of specifying when data should be collectedfrom the logical object acting as a query source and how it is manipulated toproduce output records. The grammar for producing a selection statement isshown in the Listing 2.1. Notice that the square brackets are used for optionalclauses and the notation of a clause is <Name Clause>.

<Every Clause >

<Select Clause >

[<Group By Clause >]

[<Up To Clause >]

[<Having Clause >]

[<On Empty Selection Clause >]

<Sampling Clause >

[<Execute If Clause >]

[<Terminate After Clause >]

Listing 2.1: LLQ Selection Definition

A low level query can be decomposed in three main blocks:

• Data management section

• Execution conditions section

• Execution conditions section

The SELECT clause specifies which data (FPC’s Attributes) have to be col-lected from the sensing network and how they have to be aggregate to producesome records as result. Ideally, the selection should be executed on the localdevice buffer that is infinite, which it is simply impossible. To overcome thisproblem, in the SELECT clause it is required to specify the attribute on whichthe aggregation should be computed and the duration of a number of records

20

Page 29: Context Management in a Pervasive System · noise. La tesi presente descrive le fasi del design di caratteristiche context-aware e il loro sviluppo integrato ad un middleware pervasivo

2.4. The PerLa System

which represents the portion of the buffer used to calculate the aggregation.The UP TO clause allows retrieving more than one record from the local buffer,default is 1 record. The GROUP BY clause allows a grouping of the records inthe local buffer before the selection process, described above, is computed. TheHAVING clause allows a filtering operation on the records identified by the UPTO clause, before output records are produced. This last clause may producean empty result record so, the EMPTY SELECTION clause is useful to allowthe user to specify the behavior of the query when the selection process doesn’tproduce any output record.

The Sampling section specifies when the sensors must be sampled for the readingof the attributes specified with the SELECT clause. The obtained record isinserted into the node’s local buffer and it is transferred to the central serverwhen the EVERY clause is triggered. Two types of sampling are supported:

• event based that allows the acquisition of a data sample each time aspecific event is triggered

• time based that are employed to collect data at periodic intervals

The SAMPLING event based clause can be completed appending a WHEREclause, that allows the definition of a filtering condition. If specified, thiscondition is evaluated whenever a record is produced, before the insertion intothe local buffer. If the condition is not satisfied the record is discarded.

The Execution conditions section defines the rules to establish the set of logicalobjects that will participate to the execution of the query. The rules usuallyconsider which sensors the device possesses, so that the selection of a specificattribute, for example temperature, will be requested only to the FPCs that havea temperature sensor. The last clause is the TERMINATE AFTER one, thatcan be used to set the timeout after which the query will stop.

The selection statement may seem quite complex as it is composed of manyclauses. However, some of them are optional and most of the common queriesdo not require all the clauses. The simplest query, in fact, a user can writecontains only the EVERY, SELECT and the SAMPLING clauses.

The following query initiates a temperature sampling operation on all temper-ature sensors located in room number five. Data records are produced every1 minute and stored inside the device’s local buffer. The MAX aggregationexpression is evaluated on the temperature values collected in the previous 10minutes of sampling.

This query performs a 10 minutes monitoring of the tag with ID [tag]. At theend, it inserts a single record in an output stream to report how many times

21

Page 30: Context Management in a Pervasive System · noise. La tesi presente descrive le fasi del design di caratteristiche context-aware e il loro sviluppo integrato ad un middleware pervasivo

Chapter 2. State of the Art

CREATE OUTPUT STREAM Table (Temperature FLOAT) AS:

EVERY 10 MINUTES

SELECT MAX(temp , 10 MINUTES)

SAMPLING EVERY 1 MINUTE

EXECUTE IF EXISTS(temp) AND EXISTS(room) AND room = 5

Listing 2.2: Example of a Create PerLa Query

the tag was sensed by the reader with ID [reader]. The one shot behavior ismanaged by the TERMINATE clause that requires the execution of the selectionprocess only once.

CREATE OUTPUT STREAM Table (counter INTEGER) AS

EVERY 10 m

SELECT COUNT(*, 10 m) DEFAULT 0

ON EMPTY SELECTION INSERT DEFAULT

SAMPLING ON EVENT lastReaderChanged

WHERE lastReaderID = [reader]

EXECUTE IF ID = [tag]

TERMINATE AFTER 1 SELECTIONS

Listing 2.3: Example of a Selection PerLa Query

2.4.6 Java object representation of the Query Language

Starting from the grammar, a Java object structure of the query has beenimplemented. A complete description of the classes and methods is beyondthe scope of the present work, but a synthetic exposition is necessary to betterunderstand the entire PerLa System.

The QueryParser receives the textual query from the user, parses it, performssyntactic checks and some preliminary semantic ones and eventually generatesthe specified Java code. Since it is hard to monitor all the faults during the queryparsing, the QueryParser first generates a set of temporary objects. In thisway, it is possible to have a full view on the query and secondary inconsistencychecks are performed which result in the creation of the final and valid objects.

The resulting query is represented by a general interface Statement which isimplemented by the four type of available query: CreationStatement, Inser-tionStatement, SelectionStatement and SetStatement. Each Statement isa container for all the optional and mandatory clauses that appear in a query.The following UML diagram quickly shows the fields and main method of a

22

Page 31: Context Management in a Pervasive System · noise. La tesi presente descrive le fasi del design di caratteristiche context-aware e il loro sviluppo integrato ad un middleware pervasivo

2.4. The PerLa System

SelectionStatement. The object names immediately evoke the correspondingclauses that represent.

Figure 2.8. Query partial internal representation

23

Page 32: Context Management in a Pervasive System · noise. La tesi presente descrive le fasi del design di caratteristiche context-aware e il loro sviluppo integrato ad un middleware pervasivo
Page 33: Context Management in a Pervasive System · noise. La tesi presente descrive le fasi del design di caratteristiche context-aware e il loro sviluppo integrato ad un middleware pervasivo

Chapter 3

Context-Awareness at DesignTime

3.1 Context-aware system overview

A system becomes context-aware when it is able to recognize and distinguishamong contexts and act accordingly. Generally, the identification of contexts isdone in stages. At design time it is necessary:

• to analyse the environment in order to choose the characteristics rele-vant for the application and identify the possible situations (the feasiblecontexts) the system may incur in.

• to link the actions that will be executed and the data that may be re-quested once a context is recognized as active;

At run time the system must:

• sense the context with physical measurements from the environmentand virtual inputs sent from various software modules. For instance, atemperature sensor gives us a room’s temperature and a request to aREST service gives us the day’s weather.

• recognize the context transforming the values and data received in theprevious phase into contextual information. For example, the temperaturereading can be transformed into “Hot” or “Cold” which is the symbolicvalue associated with the temperature the sensor has sensed.

• establish whether the current combination of the contextual information

25

Page 34: Context Management in a Pervasive System · noise. La tesi presente descrive le fasi del design di caratteristiche context-aware e il loro sviluppo integrato ad un middleware pervasivo

Chapter 3. Context-Awareness at Design Time

corresponds to a defined context and, in that case, label the context asactive.

• execute the actions defined in the active context.

3.2 Initial steps for a Context-Aware PerLa

As the original PerLa was unable to deal with context, starting from the ideaof “pushing” context knowledge to the PerLa middleware, the authors in [20]presented an initial design of two features:

• an extension of the existing PerLa language syntax, called Context Lan-guage (CL), in order to declare the CDT context model (presented in thefollowing section), the contexts as well as the actions to be performedaccordingly;

• the Context Manager (CM), a component able to maintain and managethe declared CDT, detect active contexts and performs the desired actionsaccordingly;

From this initial design, a real implementation has been developed and will bepresented during the rest of this thesis.

3.3 Context Model

A well-designed context model plays an important, probably fundamental, role torepresent and access the context in any context-aware systems. In our approach,an original context model was used, called the CDT. Presented in the work“CARVE: Context-aware automatic view definition overrelational databases”[21], the CDT is a formal description of the environment characteristics whichextends the key-value context model.

3.3.1 The basic structure of the context model

As implied by the name, the CDT describes the environment in a structuredlabeled tree composed of two different types of nodes: dimension and concept.A dimension node expresses an environment characteristic and it has as chil-dren concept nodes which represent the set of possible values the dimensioncan assume. Both dimensions and concepts can be enriched using attributes.Graphically a dimension node is colored in black while a concept node in white.

The designer can increase the granularity of the scheme by expanding nodeswith the only constraints that every dimension can only have concept children

26

Page 35: Context Management in a Pervasive System · noise. La tesi presente descrive le fasi del design di caratteristiche context-aware e il loro sviluppo integrato ad un middleware pervasivo

3.3. Context Model

and vice-versa. This approach combines the simplicity of representing theenvironment with the sensibility of the designer who can add more levels inorder to explore some aspects of the CDT more in depth.

The constraint in the CDT definition is graphically visible as the node colorsalternate starting from the root and descending. Attributes are represented assquare nodes.

To denote that a dimension has assumed a certain value we use the notation

<Dimension = Value>

called a context element.

A context is formalized as the conjunction of one or more context elementsand it can graphically be seen as choosing subsets of the initial CDT. It isimportant to underline the fact that not all possible subsets are valid contexts,as a matter of fact it is not possible to use more than one concept children ofone dimension in the context definition. This logic constraint simply meansthat an environment feature can only assume one single value from the set ofits possible values.

Moreover, the designer can specify the context element combinations that arenot significant and which represent semantically meaningless context situationsor are irrelevant for the application. This constraint, called useless contextconstraint is represented by a line linking the concept nodes that cannot appearin the condition which defines a context.

According to the CDT authors, this context model is flexible and well supportsthe designer in the definition of the elements that affect data selection in differentsituations.

3.3.2 Example of a CDT

An example of usage will clarify the concepts previously presented, taken from[22], where it was adopted to model a wine monitoring scenario. With the datacollected from sensors is possible to control the factors involved in the delicateproduction process and prevent possible risks that endanger the quality of thefinal wine. The production can be divided in three main phases: the grape’sgrowth and maturation, the ageing of the wine and the transport to the finalusers. Each of these phases is influenced by external agents.

For example, in the vineyard, humidity and temperature values or parasitesattacks concur in the development of wine flavour. On the basis of these

27

Page 36: Context Management in a Pervasive System · noise. La tesi presente descrive le fasi del design di caratteristiche context-aware e il loro sviluppo integrato ad un middleware pervasivo

Chapter 3. Context-Awareness at Design Time

considerations, it is easy to identify the main environment characteristics relevantfor the situation: Phase, Risk and Role dimension. The Phase reflects theseparate stages of the wine production process (Growth, Ageing and Transport)while Role expresses which actors are involved (Farmer, Driver or Oenologist).The Risk dimension models a feasible threat to which the wine may be exposed:Overheat from overexposure to sunlight or a Disease from bacterias. The Diseasecan be further analyzed considering its Type or the Affected hectares.

The resulting CDT is shown in the Figure 3.1.

Figure 3.1. An example of CDT Schema

Knowing that the Driver is never involved during the Growth Phase, the combi-nation of these elements is meaningless and pointless for a context condition.For this reason, the designer can graphically express this useless constraintby drawing a line between the concept nodes that cannot appear in the samecontext definition, as shown in Figure 3.2.

Figure 3.2. An example of useless context constraints

Among all possible contexts, we can consider Frost Alert and the Transport -Monitoring ones that are particularly important for the wine monitoring example.

28

Page 37: Context Management in a Pervasive System · noise. La tesi presente descrive le fasi del design di caratteristiche context-aware e il loro sviluppo integrato ad un middleware pervasivo

3.4. Context Language

The first context is used in the first phase of the production process: temperatureand humidity are critical attributes that must be kept under constant controlby the farmer. The second context is relevant for the transport phase. Thebottled wine must not be kept under direct sunlight for more than a certainamount of time in order to avoid overheat and a consequent alteration of thewine flavour. Formally:

Frost Alert = (Role = Farmer) ∧(Phase = Growth) ∧

(Risk = Frost)

Transport Monitoring = (Role = Driver) ∧(Phase = Transport) ∧

(Risk = Overheat)

3.4 Context Language

The syntax of the Context Language has been divided into two parts:

• CDT Declaration for the definition of the CDT,

• Context Creation for the creation of a context.

3.4.1 CDT Declaration

With this part of the language, the designer defines the CDT, by listing allthe dimensions of interest for the application together with the values they canassume. The syntax, slightly different from the original version, is shown in theListing 3.1.

CREATE DIMENSION <Dimension_Name >

[CHILD OF <Parent_Node >]

[CREATE ATTRIBUTE $<Attribute_Name >

[EVALUATED ON "<Perla_Query >" | AS <Function > ] |

CREATE CONCEPT <Concept_Name > [WHEN <Condition >]

[EVALUATED ON "<Perla_Query >"]

[WITH ENABLE COMPONENT: "<Perla_Query >"]

[WITH DISABLE COMPONENT: "<Perla_Query >"]

[WITH REFRESH COMPONENT: "<Perla_Query >"]

[CREATE ATTRIBUTE $<Attribute_Name >

EVALUATED ON "<Perla_Query >" | AS <Function >]* *

Listing 3.1: CDT declaration syntax

29

Page 38: Context Management in a Pervasive System · noise. La tesi presente descrive le fasi del design di caratteristiche context-aware e il loro sviluppo integrato ad un middleware pervasivo

Chapter 3. Context-Awareness at Design Time

The intuitive syntax eases the CDT definition by means of creation clauses forthe dimension and its concepts. The CREATE DIMENSION clause is used toadd a new dimension identified by a unique symbolic name and by a conceptfather node. As the CHILD OF clause is optional, if no father node is specified,the dimension is a direct child of the tree root. A dimension can have a singleattribute or one or more concept children.

The CREATE ATTRIBUTE clause adds an attribute to a dimension or aconcept. An attribute is a parameter whose value can be evaluated at run timeor retrieved as a static system value. In the first case, the designer specifies withthe EVALUATED ON clause the query that the system will inject at run timeto estimate the attribute numeric value. It is worth mentioning that from theCDT parser point of view, the Query is treated as a constant string that willbe parsed by the Query Language Parser. In the second case, the non terminal<Function>has been introduced to allow the user to call an external functionfrom the language. A function can have an arbitrary number of parameters andthe designer is tasked with the definition of the set of external functions andtheir implementations.

The CREATE CONCEPT clause creates a concept object identified by asymbolic name. Because the concept represents a value a dimension can assumedepending on the occurrence of a condition, such condition is expressed in termsof numeric observables with the WHEN clause. These numeric observables mustmap to existing sensor features, the Attributes, of the FPC’s or to existingmethods. The EVALUATED ON clause allows to specify with a query how thecondition must be evaluated and to limit the number of nodes involved in theQuery execution to the devices with special features.

The designer should always make use of the EVALUATED ON clause as itis useful in two important aspects. On one hand it allows saving energy andcomputational power of the sensing nodes as the condition is evaluated onlyon the specified nodes. On the other hand, it allows the user to inject anaggregation query that considers not just the single value of a node, useless ina distributed environment, but a combined significant value.An example should clarify these advantages:

CREATE DIMENSION Temperature

CREATE CONCEPT Hot WHEN temperature > 35

EVALUATED ON "SELECT MAX(Temperature) EXECUTE IF EXISTS(

temperature)"

Listing 3.2: Example of use of clauses when/evaluated on

30

Page 39: Context Management in a Pervasive System · noise. La tesi presente descrive le fasi del design di caratteristiche context-aware e il loro sviluppo integrato ad un middleware pervasivo

3.4. Context Language

The designer creates a dimension Temperature and the concept Hot with thecondition that the temperature must be greater than 35 degrees. By specifyingthe clause evaluated on, the designer tells the system that the condition mustbe evaluated only on devices that have the temperature sensor. Moreover, forthe designer is enough that a single device senses a temperature over 35 degreesto make the dimension Temperature assumes the value Hot.

Since to explicitly define all EVALUATED ON clauses for the concepts isdemanding for a designer, the system provides a default one. The condition isevaluated on all network devices possessing the sensor for the desired Attribute

and it will compute the average of the sensed samples (in this case the averagetemperature). This design choice has been made because it makes sense that thedesigner is generally interested in average values, like the average temperaturein a room, and he has the task of specifying detailed clauses only in specialscenarios. The only constraint is that the clause must contain only a SelectStatement from the PerLa Query Language as the other statements (Create,Set and Insertion) are not evaluable conditions.

The role of the clauses WITH ENABLE, WITH DISABLE and REFRESHCOMPONENT will be explained in the next section.

Finally, a concept can have one or more attributes created with the same logicof a dimension attribute.

During the parsing of a user CDT declaration, the following semantic controlsare performed:

• two dimensions cannot have the same symbolic name;

• two concepts children of the same dimension cannot have the same sym-bolic name;

• attributes of concepts of the same dimension cannot have the same sym-bolic name;

• existence check of the declared function calls;

• a dimension chooses only existing concept nodes as the “parent node”;

• parsing and validation of queries expressed with the EVALUATION ON,WITH ENABLE, DISABLE and REFRESH COMPONENT clauses.

31

Page 40: Context Management in a Pervasive System · noise. La tesi presente descrive le fasi del design di caratteristiche context-aware e il loro sviluppo integrato ad un middleware pervasivo

Chapter 3. Context-Awareness at Design Time

3.4.2 Context inference

The most delicate phase in the CDT definition is the association to a WHENclause to each concept. Practically, the clause expresses the inference processneeded to translate raw data coming from the sensor network to the symbolicconcept value.

As said in the previous chapter, raw data gathered from context inputs arerarely directly useful for an application mainly for two reasons. On one handthe system must account for uncertain data, especially when context data areproduced by sensors or acquired from external sources that can be intermittentlyconnected to the network. Therefore processing of raw data should discard asingle reading coming from a single sensor and instead considering aggregatedata coming from a set of sources, possibly applying techniques such as noisereduction or mean calculation in order to produce higher quality data.

Data collected must then be extracted, catalogued into conceptual information.In the CDT model, this transformation is possible with the use of the WHENcondition and the associated EVALUATED ON clause. Used in combination,they are an effective way of combining the symbolic high level concept valuewith the physical computation of low level data. The conversion is performedby means of a suitable query PerLa.

3.4.3 Context creation

With the syntax in the Listing 3.3, the designer can define as many contexts asdesired. He only needs to choose a suitable name and declare the ACTIVE IFcondition in terms of a conjunction of dimensions belonging to subtrees of thepreviously declared CDT.

In particular, a condition can use pairs

• <Dimension = Value>

• Dimension.Attribute OP expression where “OP” indicates an operationaloperator.

CREATE CONTEXT <Context_Name >

ACTIVE IF <Dimension > = <Value >

[AND <Dimension > = <Value >]*

Listing 3.3: Context creation syntax

32

Page 41: Context Management in a Pervasive System · noise. La tesi presente descrive le fasi del design di caratteristiche context-aware e il loro sviluppo integrato ad un middleware pervasivo

3.5. Partial components

During the parsing of the creation of a context, some logical controls areperformed:

• a context must have a unique name;

• every dimension, concept and attribute used in the ACTIVE IF conditionmust refer to an existing object in the CDT;

• the ACTIVE IF condition must be well defined this means that it doesnot contain the useless contexts constraints neither brother concept nodes.

3.5 Partial components

In the early stages of the context creation syntax design, the language wasvirtually divided into four block components: activation, enable, disable andrefresh.

Figure 3.3. Contextual block components

The activation component corresponded to the still existing ACTIVE IF clause.The other components allowed the designer to express which actions, expressedin terms of PerLa queries, the middleware had to perform when the contextwas active, when it stopped to be active and how frequently the system had tocheck the ACTIVE IF condition.

So, it was up to the designer to explicitly list the actions and the refresh periodwith dedicated clauses for each context. However, it soon became evident thatthis approach had scalability limits due to the possible high number of contexts.

In particular, the total number of contexts grows exponentially with the numberof nodes, and, even for middle-sized CDTs, the task of declaring all the con-texts using the aforementioned syntax would become rapidly unfeasible for thedesigner. As a result, a new strategy has been adopted: instead of consideringthe activation, deactivation and refresh blocks as monolithic block for eachcontext, they can be divided into smaller blocks called partials. This separation

33

Page 42: Context Management in a Pervasive System · noise. La tesi presente descrive le fasi del design di caratteristiche context-aware e il loro sviluppo integrato ad un middleware pervasivo

Chapter 3. Context-Awareness at Design Time

is possible thanks to the precise syntax of the PerLa Language which allowsdeconstructing a complex query into smaller queries, as shown in Figure 3.4.

Figure 3.4. Division of the enable component into enable partial components

Even if the division is very significant for ENABLE and DISABLE components,also the REFRESH component can be associated with its own partial refreshcomponent, although formed only of the REFRESH clause.

Having introduced the concept of partials, it is now possible to give an expla-nation of the role of the WITH ENABLE COMPONENT, WITH DISABLECOMPONENT and WITH REFRESH COMPONENT clauses, which was post-poned from the previous section. The intent of these clauses is to give thedesigner the chance of associating smaller PerLa Queries for each concept thatwill be automatically composed and assembled by the system. These clausesare optional because it is not necessary that every context element shouldbe associated with each partial component. In case of absence, the missingcomponents are considered as formed by empty clauses.

How the system performs the composition of the context blocks will be explainedin Chapter 5.

3.5.1 CDT Declaration example

Referring to the CDT shown in Figure 3.4, a possible grammar definition ispresented focusing first on the listing of all dimensions and relative concepts andattributes. As the reader can see all concepts and attributes are associated witha suitable expression that associate their symbolic name to numeric observablesthat can be measured from the environment or retrieved from other sources.

34

Page 43: Context Management in a Pervasive System · noise. La tesi presente descrive le fasi del design di caratteristiche context-aware e il loro sviluppo integrato ad un middleware pervasivo

3.5. Partial components

CREATE DIMENSION Role

CREATE CONCEPT Farmer

WHEN getUserRole () = ’farmer ’

CREATE CONCEPT Oenologist

WHEN getUserRole () = ’oenologist ’

CREATE CONCEPT Driver

WHEN getUserRole () = ’driver ’

EXCLUDES Phase.Growth /* Useless context constraint */

CREATE DIMENSION Risk

CREATE CONCEPT Disease

WHEN getInterestTopic () = ’disease ’

CREATE CONCEPT Overheat

WHEN temperature > 30 AND brightness > 0.80

CREATE CONCEPT Frost

WHEN temperature < 5 AND humidity > 0.75

CREATE DIMENSION Type

CHILD OF Disease

CREATE ATTRIBUTE $id AS getIdDisease ()

CREATE DIMENSION Affected_hectares

CHILD OF Disease

CREATE ATTRIBUTE $square_meters AS getSquareMeters ()

CREATE DIMENSION Phase

CREATE CONCEPT Growth

WHEN getPhase () = ’growth ’

EXCLUDES Role.Driver /* Useless context constraint */

CREATE CONCEPT Ageing

WHEN getPhase () = ’ageing ’

CREATE CONCEPT Transport

WHEN getPhase () = ’transport ’

Listing 3.4: CDT declaration of the wine production monitoring

Following, some fragments that integrate the CDT definition are listed for thesake of completeness.

The frost phenomenon is known to show itself when the temperature is near 0oCand the amount of water vapour in the air is significantly high, so the dimensionRisk assumes the value Frost whenever the temperature decreases below 5oCand the humidity in the air is over 75%. This query evaluates the average valueof temperature and humidity of the last 10 minutes samples in order to removeunwanted noise. If the frost condition becomes true in an active context, theQuery PerLa defined with the ENABLE clause increases the sampling rate.

35

Page 44: Context Management in a Pervasive System · noise. La tesi presente descrive le fasi del design di caratteristiche context-aware e il loro sviluppo integrato ad un middleware pervasivo

Chapter 3. Context-Awareness at Design Time

CREATE CONCEPT Frost

WHEN temperature < 5 AND humidity > 0.75

EVALUATED ON ’EVERY ONE SELECT AVG(humidity :10m),

AVG(temperature: 10m) SAMPLING EVERY 1 m EXECUTE

IF EXISTS (humidity) OR EXISTS(temperature)’

WITH ENABLE COMPONENT: ’EVERY ONE SELECT MAX(humidity ,5m),

MAX(temperature ,5m) SAMPLING EVERY 1 m EXECUTE IF

EXISTS (humidity) OR EXISTS(temperature)’

WITH REFRESH COMPONENT: 15 m

Listing 3.5: Concept Frost definition

The overheat risk may appear when the wine is exposed for a long time underthe sunlight so that the temperature increases to more than 30oC. In this event,it is best to raise a warning signal by setting an overheat alarm to true. Whenthe risk is no longer present, the alarm can be turned off. The REFRESH clausestates how often the context condition definition that includes the Overheatconcept must be evaluated.

CREATE CONCEPT Overheat

WHEN temperature > 30 AND brightness > 0.80

EVALUATED ON ’EVERY ONE SELECT AVG(temperature :10m),

AVG(brightness: 10m) SAMPLING EVERY 1 m EXECUTE IF EXISTS

(temperature) OR EXISTS(brightness)’

WITH ENABLE COMPONENT: ’SET overheat_alarm = true’

WITH DISABLE COMPONENT: ’SET overheat_alarm = false’

WITH REFRESH COMPONENT: 15 m

Listing 3.6: Concept Overheat definition

CREATE CONCEPT Growth

WHEN humidity > 5 AND temperature > 0.75

EVALUATED ON ’EVERY ONE SELECT AVG(humidity :10m), AVG(

temperature: 10m) SAMPLING EVERY 1 m EXECUTE IF EXISTS

(humidity) AND EXISTS(temperature)’

WITH ENABLE COMPONENT: ’EVERY ONE SELECT MAX(humidity , 5m

), MAX(temperature , 5m) SAMPLING EVERY 1 m EXECUTE IF

EXISTS (humidity) AND EXISTS(temperature)’

WITH REFRESH COMPONENT: 15 m

Listing 3.7: Concept Growth definition

36

Page 45: Context Management in a Pervasive System · noise. La tesi presente descrive le fasi del design di caratteristiche context-aware e il loro sviluppo integrato ad un middleware pervasivo

3.6. Final consideration

During the Growth Phase, the wine process monitoring requires to collecttemperature and humidity from all the nodes located in the vineyard storingtheir values in a suitable table (Listing 3.7).

The context listed in section 3.3.2 is translated with the formal syntax.

CREATE Frost_Alert

ACTIVE IF Role = Farmer AND Phase = Growth AND Risk =

Frost

Listing 3.8: Context Frost Alert definition

CREATE CONTEXT Transport_Monitoring

ACTIVE IF Role = Driver AND Phase = Transport AND Risk =

Overheat

Listing 3.9: Context Transport Monitoring definition

3.6 Final consideration

In this chapter the necessary steps to add context-awareness to a system atdesign time have been illustrated. Since an application needs more meaningfuland higher level information rather than raw data gathered directly from sensors,it is advisable to create a context model. The context model should represent:the relevant characteristics of the environment, how the combination of thesecharacteristics maps to a defined context and specific behavior to raise whena context is detected as active. The context model chosen for PerLa is theCDT, a powerful yet simple tool that allows representing the main features ofthe environment playing with the adding of new sub-dimensions and concepts.Although this flexibility allows exploring more in detail some aspects, it maylead to a very high number of contexts which are not actually used or significant.Even if the use of constraints reduces the number of admissible contexts, stillthe cardinality of the valid contexts with respect to the most used ones is alimitation. The only solution is to rely on the designer’s expertise in graspinga deep understanding of the environment so that he can balance between theright level of detail and the right number of dimensions most appropriate tothe several application cases.

37

Page 46: Context Management in a Pervasive System · noise. La tesi presente descrive le fasi del design di caratteristiche context-aware e il loro sviluppo integrato ad un middleware pervasivo
Page 47: Context Management in a Pervasive System · noise. La tesi presente descrive le fasi del design di caratteristiche context-aware e il loro sviluppo integrato ad un middleware pervasivo

Chapter 4

Parser for Context Language

In the next sections, the grammar productions for the Context Language (CL)are illustrated, giving an insight on the implementation choices and showingfragments of UML corresponding to the Java object involved. As a broadoverview of the scope and meaning of the language has been the object of theprevious chapter, we will focus on the most significant aspects and quickly goover the negligible ones.

The CDT Declaration Parser and Context Creation Parser receive and parsethe Context Language inputs according to the defined grammar and performthe following tasks:

• syntactic validation

• semantic error checking

• generation of the corresponding Java objects representing the CDT andthe Context

The parsers are based on JavaCC (Java Compiler) [23], a lexical analyzer andparser generator. It takes as input an LL(k) grammar specification in a JJfile and, if there are no errors, it generates Java classes able to recognize andvalidate instances of the specified language. To define a language in a .jj file,the designer needs to define:

• “white space” that are characters as spaces or tabs that are ignored duringthe parsing;

• tokens, the smallest unit of parsed string that will have meaning to theparsing program,

39

Page 48: Context Management in a Pervasive System · noise. La tesi presente descrive le fasi del design di caratteristiche context-aware e il loro sviluppo integrato ad un middleware pervasivo

Chapter 4. Parser for Context Language

• syntax parsing rules, also called the production rule expressed in terms ofthe tokens;

• the behavior that will happen at each stage of parsing.

In a standard parser, grammar productions are translated as methods that arecalled according to the flow of the parsing procedure. Syntactic errors triggeran exception and the parser stops. Additional features (like semantic validation)must be manually coded inside the grammar file using Java syntax. WhenJavaCC is invoked to generate the parser, these blocks of code are taken as theyare and inserted in the parser class.

There are, however, two drawbacks in this system:

• the .jj file contains both the grammar specification and the Java codeneeded for the additional functionalities and controls of the parser;

• JavaCC plugin for Eclipse IDE does not provide any form of Java errorchecking;

Debugging is, therefore, more difficult and time-consuming, since the parser hasto be recompiled whenever the Java code included in the grammar changes. Topreserve the grammar understandability and to take advantage of Eclipse de-bugging, all the additional features of semantic error checkings are implementedoutside the grammar. Only the code needed to interface with the externalclasses is left in the .jj file. Before creating a Java object, a check is performedto assert that the result is semantic error free. The parser execution does notstop when an error is noticed, so all the faults found are shown to the user atthe end of the parsing.

4.1 Utility classes

ExpressionSome clauses of the language represent some kind of condition. From thelanguage point of view, a condition is an expression, which is a syntacticconstruction that has a value, formed by combining operators with variables,constants and values returned from functions. A general expression is evaluatedas a Boolean.

An expression is modelled as a structured tree where a leaf node contains theoperands (constants, aggregate values or methods) while intermediate nodesrepresent the operations to apply on the operands such as algebraic or logicfunctions. The construction of the tree is performed during the parsing of the

40

Page 49: Context Management in a Pervasive System · noise. La tesi presente descrive le fasi del design di caratteristiche context-aware e il loro sviluppo integrato ad un middleware pervasivo

4.1. Utility classes

expression strictly following the precedence and associativity rules to determinethe order in which operators are applied. The abstract class Expression

represents a general condition and it will be used whenever a class has acondition field.

The following UML diagram shows a partial view of the classes that implementan expression, notice that not all the classes are reported. Starting from theabstract class Expression, the concrete classes extend it and they are, forexample: Constant, Aggregate, Comparison or AttributeReference whichrefers to a FPC’s attribute.

Figure 4.1. Expression partial UML

Error trackingDuring the parsing of the language, several semantic checks have been imple-mented. This extra control is necessary because queries with wrong semanticsare accepted by the parser that only performs syntactic controls. Without thistype of screening, the parser would accept CDT or context definition containingduplicate dimension names or a dimension that declare as father a never createdconcept node.

The goal of implementing the semantic checking brought to the use of theclass ParserContext that stores the semantic errors possibly found during theparsing. Its instance is passed as a parameter during the invocation of the staticmethod for the creation of objects when there is the risk that the user mayinput invalid language clauses. In this way, if one or more inconsistencies areobserved, the addError method stores them inside the ParserContext.

41

Page 50: Context Management in a Pervasive System · noise. La tesi presente descrive le fasi del design di caratteristiche context-aware e il loro sviluppo integrato ad un middleware pervasivo

Chapter 4. Parser for Context Language

Figure 4.2. ParserContext class

At the end of parsing, in case the list of errors is not empty, an Exception israised and the entire error description is shown to give the user the chance ofnoticing and correcting his mistake.

4.2 CDT Creation

The following grammar production returns the CDT object. Since there is asingle CDT for an application, the Java Singleton pattern is a perfect fit becauseit ensures that only one instance of the class is created. The pattern employs atechnique known as lazy instantiation to create the singleton, as a result theinstance is not created until the getCDT() method is called for the first time.The CDT contains a list of Dimension which are set when the parser reachesthe end of the text input.

/* Production for a CDT object */

CDT CDT(ParserContext ctx):

CDT cdt = CDT.getCDT ();

List <Dimension > dimensions=new ArrayList <>();

dimensions = CreateDimensions(ctx)

cdt.setDimensions(dimensions);

return cdt;

Listing 4.1: Start of CDT grammar production

4.2.1 Create Dimension clause

A Dimension has a name, a concept father node and a list of Concept childrennodes or an attribute. To impose the exclusivity between concept children andattribute, inside the grammar production there is the alternative choice closed

42

Page 51: Context Management in a Pervasive System · noise. La tesi presente descrive le fasi del design di caratteristiche context-aware e il loro sviluppo integrato ad un middleware pervasivo

4.2. CDT Creation

between square brackets. A simple semantic check is added directly inside thejavacc file as it is immediate to assert that dimension names must be unique.

The optional CHILD OF clause assigns a father to a Dimension by stating aconcept name, but this may lead to ambiguity since there is no constraint thatall concepts belonging to any dimensions must have distinct names. For example,in case there are two concepts with the same name “XX” and a dimension isassigned as a child of “XX”, it would be impossible for the system to establishwhich is the “right” father concept. This means that the simple concept nameis not always sufficient, so, in these cases, the solution is to input the conceptname as dimensionName.conceptName. If the CHILD OF clause is not used bythe user, the default value set as father is the Root node.

List <Dimension > CreateDimensions(ParserContext ctx) :

List <Dimension > dims = new ArrayList <ension >();

Dimension d;

Set <String > names = new TreeSet <String >();

<KEYWORD CREATE >

d = CreateDimension(ctx)

names.add(d.getName ());

dims.add(d);

(

<KEYWORD CREATE >

d = CreateDimension(ctx)

String n = d.getName ();

if (names.contains(n)) /* Duplicate name control */

ctx.addError (" Duplicate name");

else

names.add(n);

dims.add(d);

)*

<EOF >

return dims;

43

Page 52: Context Management in a Pervasive System · noise. La tesi presente descrive le fasi del design di caratteristiche context-aware e il loro sviluppo integrato ad un middleware pervasivo

Chapter 4. Parser for Context Language

Dimension CreateDimension(ParserContext ctx):

String name;

String father = "ROOT";

CreateAttr att = null;

List <Concept > concepts = new ArrayList <>();

<KEYWORD DIMENSION >

name = Identifier ()

[ father = ChildOf(ctx) ]

( LOOKAHEAD (2)

att = CreateAttribute(ctx , father)

return new Dimension(name , father , att);

|

LOOKAHEAD (2)

concepts = CreateConcepts(ctx , atts)

return new Dimension(name , father , concepts);

)

Listing 4.2: Creating a Dimension

4.2.2 Create Attribute clause

A CreateAttribute object is identified by a symbolic name with the prefix $and by a retrieval policy. In order to distinguish among the different modalitiesthat can be employed to obtain its run time value, the EvaluatedOn interfacehas been introduced.

At present there are two evaluation modalities implemented by the class QueryE-valuatedOn that stores the PerLa query needed to retrieve the attribute atrun time, and by the class FunctionEvaluatedOn that stores the function callsdeclared in the CDT definition. The Utility class acts as a bridge from thesymbolic function definition to its real implementation done by the designer.The method retrieveValueOfFunction() takes as arguments the functionname and the optional parameters and returns the actual value. The use ofthe EvaluatedOn interface leaves open the possibility of adding new ways ofretrieving an attribute value, for example reading a configuration propertyprovided by an external file or by accessing a database table.

A CreateAttribute object is created by a static method because before instan-tiating an object of the class, the EVALUATED ON string must be validatedaccording to the chosen retrieval method. A PerLa query must be validated by

44

Page 53: Context Management in a Pervasive System · noise. La tesi presente descrive le fasi del design di caratteristiche context-aware e il loro sviluppo integrato ad un middleware pervasivo

4.2. CDT Creation

the Query Parser while the external function must exist. If one of this stepfails, an error is recorded inside the ParserContext instance.

CreateAttr CreateAttribute(ParserContext ctx):

String id;

String evalOn;

<KEYWORD CREATE > <KEYWORD ATTRIBUTE > <KEYWORD DOLLAR >

id = Identifier ()

( <KEYWORD EVALUATED > <KEYWORD ON>

evalOn = ConstantString ()

return CreateAttr.createWithQuery(id, evalOn , ctx);

|

<KEYWORD AS >

evaluatedOn = Method ()

return CreateAttr.createWithMethod(id, evalOn , ctx)

)

Listing 4.3: Creating an Attribute

4.2.3 Create Concept clause

The Concept class has several fields, many optional. The simpler Concept

object contains a name and a WhenCondition field representing the physicalevaluation condition.

A WhenCondition regroups the WHEN clause modelled as an Expression

object and the EVALUATED ON clause which contains a suitable query. Theuser writes the query enclosed in quotes so that the CDT Parser treats it as aconstant string and the query text is afterwards validated by the Query Parser

invoked inside the static creation method of the WhenCondition itself. Again,a semantic control is performed outside the parser scope during the creation ofa Java object which, if successful, terminates with the creation of a Statement

object.

The variable whenAttr stores the attribute names used in the WHEN conditionwhich are necessary to create the default EVALUATED ON clause. Therelated query demands to the FPC possessing the sensors matching the declaredattributes, the 10 minute periodical sampling of the attributes’ average. Thedefault clause is not initialized if the WHEN condition does not contain anysensor attributes but only values retrieved by external function calls.

45

Page 54: Context Management in a Pervasive System · noise. La tesi presente descrive le fasi del design di caratteristiche context-aware e il loro sviluppo integrato ad un middleware pervasivo

Chapter 4. Parser for Context Language

The enable and disable clauses are modelled by the PartialComponent classwhich stores the corresponding query PerLa while Refresh contains the tem-poral interval bound to the evaluation of the context condition. Since theseclauses are optional, they are initialized to void objects, respectively Partial-

Component.EMPTY and Refresh.NEVER and only set if the user declares themas part of the Concept definition.

As for the WhenCondition object creation, the successful PartialComponentcreation depends on the validation result produced by the Query Parser at theend of query parsing. In addition to the parser’s validation, the PartialCompo-

nent disable can only contain a Set Statement.

To conclude, the Multimap variable constraints contains the useless contextconstraints expressed with the clause EXCLUDES. The advantage of using aMultimap object instead of a classic Map object is the feature of associating alist of values to a single key map. The key is a dimension name, while a valueis a concept name.

Concept CreateConcept(ParserContext ctx):

String name;

String whenEvaluated = null;

WhenCondition cond = WhenCondition.EMPTY;

ExpressionAST when = ConstantAST.TRUE;

List <CreateAttr > subAtts = Collections.emptyList ();

Set <String > ids = new TreeSet <String >();

PartialComponent enable = PartialComponent.EMPTY;

PartialComponent disable = PartialComponent.EMPTY;

Refresh refresh = Refresh.NEVER;

Map <String , DataType > whenAttr = new HashMap <>();

Multimap <String , String > constraints;

<KEYWORD CREATE > <KEYWORD CONCEPT >

name = Identifier ()

( <KEYWORD WHEN >

when = Expression(ExpressionType.SIMPLE , ctx , whenAttr)

[

<KEYWORD EVALUATED > <KEYWORD ON >

whenEvaluated = ConstantString ()

]

cond = WhenCondition.create(whenAttr , when ,

whenEvaluated , ctx);

46

Page 55: Context Management in a Pervasive System · noise. La tesi presente descrive le fasi del design di caratteristiche context-aware e il loro sviluppo integrato ad un middleware pervasivo

4.2. CDT Creation

)?

[

constraints = Constraints(ctx)

]

[ LOOKAHEAD (2)

enable = WithEnable(ctx , name)

]

[ LOOKAHEAD (2)

disable = WithDisable(ctx , name)

]

[ LOOKAHEAD (2)

refresh = WithRefresh(ctx)

]

[ LOOKAHEAD (2)

subAtts = AddConceptAttributes(ctx , atts , name)

]

return new Concept(name , cond , ...);

Listing 4.4: Creating a Concept

47

Page 56: Context Management in a Pervasive System · noise. La tesi presente descrive le fasi del design di caratteristiche context-aware e il loro sviluppo integrato ad un middleware pervasivo

Chapter 4. Parser for Context Language

4.3 Context Definition

A Context object contains a list of ContextElement objects. A context elementcan be a ContextElementSimple if it represents a <Dimension = Value> pairor a ContextElementAtt if it models a Dimension.Attribute OP expression.

Context CreateContext(ParserContext ctx):

String name;

List <ContextElement > elements = new ArrayList <>();

<KEYWORD CREATE >

<KEYWORD CONTEXT >

name = Identifier ()

elements = ActiveIfClause(ctx)

return new Context(name , elements);

Listing 4.5: Context Production

Context CreateContext(ParserContext ctx):

List <ContextElement > ActiveIfClause(ParserContext ctx) :

List <ContextElement > elements = new ArrayList <>();

ContextElement c;

<KEYWORD ACTIVE > <KEYWORD IF>

(

LOOKAHEAD (2)

c = CreateContextElement(ctx)

|

LOOKAHEAD (2)

c = CreateContextElemAtt(ctx)

)

elements.add(c);

)* <EOF >

return elements;

Listing 4.6: Active if Production

48

Page 57: Context Management in a Pervasive System · noise. La tesi presente descrive le fasi del design di caratteristiche context-aware e il loro sviluppo integrato ad un middleware pervasivo

4.4. UML

Context CreateContext(ParserContext ctx):

ContextElement CreateContextElement(ParserContext ctx):

String dimension;

String concept;

dimension = Identifier ()

<OPERATOR EQUAL >

concept = Identifier ()

return ContextElemSimple.create(dimension , concept , ctx

);

Listing 4.7: Simple Context Element Production

Context CreateContext(ParserContext ctx):

ContextElement CreateContextElemAtt(ParserContext ctx) :

String dimension;

String attribute;

ExpressionAST e;

dimension = Identifier ()

<KEYWORD DOT >

attribute = getToken (1).image;

e = Expression(ExpressionType.SIMPLE , ctx)

return ContextElemAtt.create(dimension , attribute , e,

ctx);

Listing 4.8: Complex Contect Element Production

4.4 UML

Figure 4.3 and 4.4 report a UML class diagram of the internal representationof the CDT and of the Context that is built by the parser. Interface classes arecolored in orange while standard classes are in blue. Traditional get, set andutility methods are omitted from the schema to preserve better readability.

49

Page 58: Context Management in a Pervasive System · noise. La tesi presente descrive le fasi del design di caratteristiche context-aware e il loro sviluppo integrato ad un middleware pervasivo

Chapter 4. Parser for Context Language

Figure 4.3. Internal representation of the CDT

Figure 4.4. Internal representation of a Context

50

Page 59: Context Management in a Pervasive System · noise. La tesi presente descrive le fasi del design di caratteristiche context-aware e il loro sviluppo integrato ad un middleware pervasivo

Chapter 5

Context Awareness at Run Time

To manage context-awareness at run-time a Context Management layer hasbeen added to the existing PerLa middleware.

Figure 5.1. New context-aware PerLa

The Context Management layer is composed of different helper modules withwell-defined functions that respect the basic principle of context-aware systemswhich imposes to separate the context sensing from its usage. The sensingphase relies on the underlying sensor network already managed by the existingmiddleware. The classes that belong to the context management layer are:

51

Page 60: Context Management in a Pervasive System · noise. La tesi presente descrive le fasi del design di caratteristiche context-aware e il loro sviluppo integrato ad un middleware pervasivo

Chapter 5. Context Awareness at Run Time

• Context Manager : is the core of the system, it stores the CDT andcontexts’ representation and through the query execution layer, queriesthe sensor networks to retrieve the data needed for context detectionchanges;

• Context Detector : elaborates the gathered context data, checks periodi-cally if a context is active or inactive on the base of the context validationcondition and sets the internal state of the context accordingly

• Context Executor : listens for notification of context state change andexecutes its behavior actions, for example by automatically injectingspecific queries into the system.

As the reader may have noticed, this architecture is similar to the projects’architecture described in Chapter 2.

Figure 5.2. Procedure flow of context-aware PerLa

52

Page 61: Context Management in a Pervasive System · noise. La tesi presente descrive le fasi del design di caratteristiche context-aware e il loro sviluppo integrato ad un middleware pervasivo

5.1. Context Manager

Figure 5.2 outlines the basic principles of the context management layer addedto the PerLa System. Sensors provide data events and information in the realworld which are processed and classified into context. Based on the observedcontext, actions of the system will be triggered.

Moreover, since it can be interesting for the designer to keep track of the historyof context change, the system uses a database for persistent data storage. Thedatabase is server-based and, therefore, it is not constrained by storage spaceor performance limitations.

5.1 Context Manager

The ContextManager is the central component that orchestrates the manage-ment flow of the context layer. Listing 5.1 shows its the main methods whosepurpose is explored in the rest of the following sections.

1 public class ContextManager

2 public void createCDT(String text) throws

ParseException;

3

4 public void createContext(String context) throws

ParseException;

5

6 public void startDetectingContext(String contextName);

7

8 public void removeContext(String context) throws

ParseException;

9

10 public void populateCDT ();

11

Listing 5.1: The ContextManager class

The flow starts at design time when the user designs the application CDT andthe relevant contexts. The designer calls the createCDT() method passingas argument the textual CDT (expressed with the Context Language), thenan instance of CDTreeParser validates the inputs and, if correct, the internalrepresentation of the CDT is created. The same goes for createContext()

method which creates a Context object. At this point, a Context is definedonly by its name and activation condition, it is devoid of enable, disable andrefresh blocks that correspond to the actions to perform when the context

53

Page 62: Context Management in a Pervasive System · noise. La tesi presente descrive le fasi del design di caratteristiche context-aware e il loro sviluppo integrato ad un middleware pervasivo

Chapter 5. Context Awareness at Run Time

becomes active, inactive and the frequency period to check the activationcondition.

5.1.1 The Composer Manager

The automatic composition of the contextual blocks of a context could becarried out both at design and at run time. At design time, the designer has toassociate the proper partial components with every context element and thecontextual block of a context is assembled before it is put into an operationalstate. In the run-time approach, the association phase is the same, but, in thiscase, the composition is carried out at run-time only when its relative contextis recognized as active by the middleware.

The advantages and disadvantages of the composition in these two scenarios arediscussed in [22], which reaches the conclusion that there is not a best practice,but it depends on different factors. On one hand, the approach at design-timeallows the designer to change the composed blocks in case the requirementsask for particular attention. On the other hand, the frequent composition atrun-time of several context elements, maybe involving complex partials, couldpotentially slow down the whole system performance.

Another important remark that has been underestimated before, is the incon-sistency problem related to a growing number of context elements. The wholecontextual block composition relies on the ability of the designer to choosesuitable partial components for every context element and, in a sense, to foreseewhat will happen when the automatic composition will take place. As a matterof fact, it is quite hard, if not impossible, to image how the different fragmentsmay combine with each other in the contextual block of every context. Even ifthe new strategy of the partial component composition was derived to relievethe designer from the task of defining the contextual block for each context, thedanger of producing inconsistencies during the automatic composition is veryhigh and it increases with the number of context elements. For this reason, thedesign-time policy is the only choice that prevents the risk of runtime exceptionsby enabling the designer to manually correct validation errors produced duringthe composition.

The IComposerManager is the component responsible for the design-time asso-ciation of the PartialComponent enable, disable and refresh.

As shown in Listing 5.2, the composeBlock method is invoked whenever anew Context is created and it implements the chosen algorithm for the blockcomposition. The first step of the composition procedure is the retrieval of all

54

Page 63: Context Management in a Pervasive System · noise. La tesi presente descrive le fasi del design di caratteristiche context-aware e il loro sviluppo integrato ad un middleware pervasivo

5.1. Context Manager

1 public interface IComposerManager

2 public void composeBlock(Context context);

3

4 public void addPossibleContext(Context context);

5

6 public Context getPossibleContext(String contextName);

7

8 public void removePossibleContext(Context toDetect);

9

10 public List <Context > getPossibleContexts ();

11

Listing 5.2: The IComposerManager Interface

the relative context elements used in the ACTIVE IF context clause. Whenall these inputs have been retrieved, as a first step empty enable, disable andrefresh blocks are created. In the refresh block, the most frequent time valueamong the ones contained in the refresh partials is set.

Care must be taken in assembling the enable and disable blocks as it is notenough to simply append all the relative partials in a block. SetStatement,CreationStatement, InsertionStatement objects are simply attached to theblock as they don’t interfere with one other. Instead, for SelectionStatementobjects, there could be many situations of conflicts.

Keeping in mind the syntax and Java representation of the Selection Statement,we now list some design choices in trying to assemble singular select statementsin the same enable or disable block:

• the Every clause contains the lowest time period;

• the fields of the Select and GroupBy clauses are simply concatenated;

• the Expression where, having become conjunctions of the singular state-ments;

• final ExecutionConditions clause contains the union of the rules neededto select the proper execution devices;

• the events specified in the SamplingEvent clauses are appended one afteranother;

• for the time based clauses SamplingIfEvery, the lowest sampling valueis selected;

55

Page 64: Context Management in a Pervasive System · noise. La tesi presente descrive le fasi del design di caratteristiche context-aware e il loro sviluppo integrato ad un middleware pervasivo

Chapter 5. Context Awareness at Run Time

• the final terminate clause is the highest time value.

At the end of the procedure, the QueryParser verifies the syntactic and semanticvalidation of the composed blocks. If correct, the possible Context object isstored in a list, at this moment the system has not started yet its detection.The choice to not automatically inject the created context into the detectionflow allows the user to change the composed block if special care is needed.

Conversely, in case some inconsistencies are detected, the Context is consideredas an invalid one, so that the designer can retrieve it, look at the error descriptiongenerated during the parser validation and correct the errors manually.

5.1.2 Mapping raw data to contextual information

With the invocation of the ContextManager.populateCDT(), the context man-agement flow continues at run time, the sensor data acquisition phase begins.As we said before, the QueryExecutor is responsible for the query execution bygathering samples from the FPC, but how a user or another system componentinteract with the QueryExecutor?

The PerLa System is an asynchronous, event-driven architecture which fostersa direct exchange of information between data producers and data consumerswhere information is explicitly handed over to the intended recipients. Thismeans that every asynchronous method call is identified by the following char-acteristics:

• Does not block: calls to an asynchronous method never block; control ofthe execution flow is immediately returned to the caller, and the requestedcomputation is executed asynchronously;

• Returns a Task object: asynchronous method calls do not return theimmediate result of a computation. Instead, they return a Task, an objectthat can be used to stop the ongoing operation or to query its currentstate of progress;

• Defers the delivery of results: the result of an asynchronous method isnotified through a Handler function, which is invoked as soon as thecomputation terminates.

Interaction with the QueryExecutor follows the same principle and it is achievedby means of the execute() method.

As can be seen in Listing 5.3, execute() requires two parameters: a query anda StatementHandler callback object. The former is the query that can be in

56

Page 65: Context Management in a Pervasive System · noise. La tesi presente descrive le fasi del design di caratteristiche context-aware e il loro sviluppo integrato ad un middleware pervasivo

5.1. Context Manager

1 public final class Executor

2 public StatementTask execute(Statement s,

StatementHandler h) throws QueryException;

3

4 public StatementTask execute(String query ,

StatementHandler h) throws QueryException;

Listing 5.3: The Query Executor class

textual form or directly as a Statement object which is the result of the queryparsing. The latter allows the caller to be asynchronously notified of the queryexecution procedure. Invocations of execute() are non-blocking; control flowis immediately returned to the caller, thus allowing other computations to beperformed while the requested query execution is being processed.

1 public interface StatementHandler

2 void data(Statement query , Record record);

3

4 void error(E source , Throwable cause);

5

Listing 5.4: The StatementHandler class

The StatementHandler interface is composed of two methods, namely data()

and error(), which are invoked during the processing of the query. An invoca-tion of the data() method is always associated with the successful execution ofa query. As shown in Listing 5.4, this method includes a Record object, thatcontains all the samples gathered from the network devices. A Record containsthe list of Attribute to sample with the corresponding values. An invocationof the error() method indicates that the query execution was aborted beforecompletion. In this case, the cause of failure is notified through the causeparameter.

Ongoing query sampling operations can be monitored or cancelled by means ofthe StatementTask object acquired upon invocation of the execute() method.Listing 5.5 shows all methods of the StatementTask interface; method namesare self-explanatory, it is easy to deduce their purpose just by analyzing theirsignature.

Figure 5.3 shows the sequence diagram of the interaction between objects duringthe request of execution of a query.

57

Page 66: Context Management in a Pervasive System · noise. La tesi presente descrive le fasi del design di caratteristiche context-aware e il loro sviluppo integrato ad un middleware pervasivo

Chapter 5. Context Awareness at Run Time

1 public interface StatementTask

2 void stop();

3

4 boolean isRunning ();

5

Listing 5.5: The StatementTask interface

Figure 5.3. Sequence diagram of an asynchronous query execution operation

The raw data acquisition procedure first retrieves all the Concept from theCDT with the corresponding WhenCondition. For each Concept and CreateAt-

tribute, the query contained in the EvaluatedOn is passed as parameter tothe QueryExecution.execute() method together with a specific Statemen-

tHandler object.

In order to have a real time representation of the values assumed by the dimen-sions and relative attributes of the CDT, a ConcurrentHashMap, called cache,is used. It contains as keys all the distinct Dimension and CreateAttribute

names and as values, respectively, the set of current Concepts or of the numericvalues, Figure 5.4.

As soon as the QueryExecution receives the record sampled from the FPCs,it invokes the StatementHandler.data() method; the Record object passed

58

Page 67: Context Management in a Pervasive System · noise. La tesi presente descrive le fasi del design di caratteristiche context-aware e il loro sviluppo integrato ad un middleware pervasivo

5.2. Context Detector Component

Figure 5.4. Example of the cache containing the current state of the CDT

as parameter of the method is used to verify the WhenCondition of a Concept.If the condition is verified, the Concept is associated to the correspondingDimension in the cache. In case of a CreateAttribute, the attribute valuecontained in the Record is directly saved inside the hash map.

5.2 Context Detector Component

As the cache contains the current environment state given by the current valuesassociated to the dimensions belonging to the CDT, the system can start todetect the user-defined contexts.

Upon the invocation of the ContextManager.startDetectingContext method,a Context has to be considered by the application, recognizing whether it isactive or not. Its activation condition must be periodically checked against thereal time environment situation. The component responsible during this phaseis the ContextDetector.

A ContextDetector object is associated to every context the system has todetect. It contains a thread dedicated to verify the context activation conditionperiodically with respect to the time interval specified in the Context’s Refreshobject. When the time interval is triggered, the ContextElement objects con-

59

Page 68: Context Management in a Pervasive System · noise. La tesi presente descrive le fasi del design di caratteristiche context-aware e il loro sviluppo integrato ad un middleware pervasivo

Chapter 5. Context Awareness at Run Time

tained in the activation condition are checked against the ContextManager’scache. For each Dimension or CreateAttribute contained in the ContextEle-

ment, its current values are retrieved by the cache and it is compared withthe expected values. If all current values match with the expected values, theContextDetector sets the Context’s state variable as active. In the oppositecase, the Context’s state remains inactive.

5.3 Context Executor

The ContextExecutor component joins the procedure flow when a Context

changes its state. The relationship between those objects is implementedfollowing a Java behavioral design pattern called Observer Pattern. Thispattern is useful when an object, called Observer, is interested in the stateof another object, called Subject and wants to get notified whenever there isany change. In the present case the ContextExecutor is concerned about theContext and it subscribes to receive notification upon the invocation of theContextManager.startDetectingContext method.

It is worth noting that the Observer Pattern’s definition states ([24]): ”It definesa one-to-many dependency between objects so that when one object changes state,all its dependents are notified and updated automatically”. This means that ina future expansion of the system, any software components or external usercan subscribe, if interested, to a particular Context and automatically receiveinformation about its state change.

Listing 5.6 contains the ContextExecutor’s methods that groups all the func-tionalities needed to handle the actions triggered by a context change. Themethods allow to execute a Context which has become active or to stop itsexecution when it is no longer active.

When the ContextExecutor receives the notification about the Context’s statechange, it distinguishes among the active case or the inactive case. In the firstscenario, it first controls that the context is not in conflict with previouslyactivated contexts (see section 5.4). If not, it proceeds at applying the enableactions. The procedure retrieves the queries contained in the enable block andinvokes the QueryExecutor.execute() method. The StatementTask obtainedas the result object of the method invocation is stored in a suitable map thatkeeps track of the queries in execution associated with an active context. Ifa context has become inactive, the ContextExecutor has to first stop theexecution of the context’s active queries on the sensor network. The previouslysaved StatementTask objects show their purpose, the invocation of the stop()

method terminates the execution of the associated query. Afterwards, the

60

Page 69: Context Management in a Pervasive System · noise. La tesi presente descrive le fasi del design di caratteristiche context-aware e il loro sviluppo integrato ad un middleware pervasivo

5.3. Context Executor

1 public class ContextExecutor implements Observer

2 public void addContextToExecute(Context c);

3

4 public void removeContextToExecute(Context c);

5

6 public void addActiveContext(Context c);

7

8 public void removeActiveContext(Context c);

9

10 public void update(Observable o, Object arg);

11

Listing 5.6: The ContextExecutor class

procedure continues with the injection in the system of the disable context’squeries.

A question that arises from observing the loop of context change and actionsto be executed is: ”What happens if the context changes its state from activeto inactive during the execution of a context’s action itself?”. A similar issuehas been the object of discussion in [25] where the authors argue about theunpredictability of continuous queries that run for long periods of time. Theirefforts concentrated on the introduction of a framework able to express lifecycleoperations on the basis of input-output mappings and basic control elementssuch as start or stop of queries. The approach tried to guarantee some basiccorrectness criteria: avoid losing output elements caused by the sudden stop ofa query, guaranteeing that the old query will eventually terminate and freeingup its occupied resources while the new query starts progressing. With regardsto PerLa, an action of a context (called for example ”Context1”) is a query tothe sensing network sent to the QueryExecutor that is executed by means of adedicated thread. When the ContextExecutor gets notified that the Context1is no longer active, it retrieves the StatementTask associated to the Context1’sactive queries and calls the relative stop() methods. Even if an action sent toan actuator to set a parameter is not complete because it is stopped, this is notan issue because the queries of the disable should be defined in order to restorethe environment state present before Context1 was activated.

5.3.1 Context history

A requirement linked to the need of an evolving system is the desire to maintainhistorical information. Sensors or information inputs maintain little, if any,

61

Page 70: Context Management in a Pervasive System · noise. La tesi presente descrive le fasi del design di caratteristiche context-aware e il loro sviluppo integrato ad un middleware pervasivo

Chapter 5. Context Awareness at Run Time

historical information. A component that acquires context information shouldmaintain a history of all the context it obtains. Context history can be used toestablish trends and predict future context values. Without context storage, thistype of analysis could not be performed. Ideally, the architecture should supportstorage at the finest possible level of detail in order to meet any application’srequests for historical information. For the moment, every time a contextchange happens, a timestamp is recorded inside a dedicated external database.A possible analysis based on the collected timestamp computes the frequencyrate of a specific context change, which is the context more rarely detected orwhich is the most stable and common.

5.3.2 Context distribution

The context behavior can be expressed in terms of direct and indirect actions.The first type of actions indicates operations that act directly on the system bysetting parameters on actuators (turn on or turn off a light). The second typedeals with signaling asynchronous events to external connected applications.This type of commands is used to enhance the ability of PerLa to react to contextchanges; at an higher level, it is also related to improve data management. Datatailoring aims at effectively and efficiently gathering and synthesizing datacoming from a variety of heterogeneous sources, reducing at the same timeinformation noise. Data tailoring is needed because of two main reasons: thefirst is to filter the amount of information adequately, in order for the usernot to be confused by too much noisy information but to focus on currentlyuseful information (often called views) ; the second is for reducing the devices’computational effort and hardware constraints in dealing with manageableamount of data. The PerLa middleware adopts data tailoring by injectingspecific contextualized queries with changeable policies towards the differentdata sources. For example, in case of contexts that signal a possible risk,queries with an increased sampling rate are injected whereas the sampling rateis decreased when the system detects a calm, “normal” context.

Up to this point, we have considered only actions useful from the PerLa middle-ware point of view which reacts to context changes with commands to actuatorsand modified current queries with contextualized ones. We have followed thecontext-aware middleware-based approach with the introduction of a layeredarchitecture which manages the context lifecycle: from the raw data acquisitionhiding the low-level sensing details, processing of the data, recognition of contextchanges and execution of the context behavior. The extension of this approachis the ContextServer architecture which supplies information about the currentcontexts to remote users and external applications. The ContextManager can

62

Page 71: Context Management in a Pervasive System · noise. La tesi presente descrive le fasi del design di caratteristiche context-aware e il loro sviluppo integrato ad un middleware pervasivo

5.3. Context Executor

be seen as a part of the ContextServer, in fact, it has the role of managing thecontext lifecycle internally to PerLa. The missing step is the dissemination ofcontext data to all interested applications.

This further improvement and integration at the moment is being developedin another project, starting with the idea of modeling a context change orspecific actions as events. Present to an external user, useful portion of datacan be considered as the sending of an event which serialize and marshal thedata into a concrete message. An EventManager interface provides methodsfor managing the different kinds of events related to a context. Context datadistribution adopts as communication pattern, the publish/subscribe mechanism.Applications interested in certain context information can subscribe to themiddleware and be notified when updates of the context information occur.

In order to show the interactions between the different components that areresponsible for the context lifecycle and its distribution, we have drawn anactivity diagram, Figure 5.5. The diagram is not complete as it regroups smallercomponents into macro components, but still it gives a clear picture of thescenario.

Suppose that a user has, on its personal device, an application that wants toretrieve context information from PerLa. The application communicates witha Web service that exposes methods to connect with the PerLa System. Thecredential and user settings are retrieved and managed by the Utility class,so that the PerLa System gets notified that a new user is connected. Once theuser’s application has been recognized, it connects to the Publisher througha call to the Subscriber in order to receive the events fired by PerLa. Whenthe ContextManager detects that a context has changed its status, it retrievesthe needed information (stored in the database or about the connected users)and generates the events. The EventManager is notified, creates the suitablemessage, the topic, and sends it to the subscribers.

63

Page 72: Context Management in a Pervasive System · noise. La tesi presente descrive le fasi del design di caratteristiche context-aware e il loro sviluppo integrato ad un middleware pervasivo

Chapter 5. Context Awareness at Run Time

Figure

5.5.

Seq

uen

ced

iagr

amof

the

dis

trib

uti

onof

conte

xt

even

ts

64

Page 73: Context Management in a Pervasive System · noise. La tesi presente descrive le fasi del design di caratteristiche context-aware e il loro sviluppo integrato ad un middleware pervasivo

5.4. Conflict management

5.4 Conflict management

Context-aware systems in mobile and pervasive environments face many con-flicting situations while collecting sensor data, processing sensor data or adaptto the evolving environment. Conflicts can be classified into two categoriesaccording their source:

• Data conflict. It is present whenever an input source reports an informationthat is is clashing with the corresponding information provided by anotherinput channel. Which data the system should trust?

• Action conflict. What to do when two concurrent contexts performincompatible actions?

Context conflict is a key problem since it often occurs in context-aware systemwhen multiple users share the same context at the same time or when multiplecontexts can be active at the same time. Context conflict not only causesconfusion in applications, but also slows down the efficiency of context-awaresystems. For the rest of this section, we will discuss conflicts between contextsthat would perform opposite actions.

A wide review of this topic has been presented in [26], which lists a generaldefinition of conflicts and possible policies to handle them. Formally, given twogeneric contexts C1 and C2, they are in conflict if the following conditions aretrue at the same instant:

• C1 and C2 are distinct contexts;

• C1 and C2 are both active;

• C1 and C2 impose actions to be executed on the same resource.

Suppose we are in a building where the office labelled as ”Office1” has an airconditioner. A very basic CDT contains a dimension Location with the attributeID and a dimension Risk with two concepts Overheat and Overload. We definetwo contexts:

CREATE C1

ACTIVE IF Location.ID = ’Office1 ’ AND Risk = Overheat

ENABLE SET Air_Conditioner = ON

The first context defines the action of turning on the air conditioner when atemperature above a fixed threshold is sensed; while the second one definesthe action of turning off the air conditioner when the power consumption goes

65

Page 74: Context Management in a Pervasive System · noise. La tesi presente descrive le fasi del design di caratteristiche context-aware e il loro sviluppo integrato ad un middleware pervasivo

Chapter 5. Context Awareness at Run Time

CREATE C2

ACTIVE IF Location.ID = ’Office1 ’ AND Risk = Overheat

ENABLE SET Air_Conditioner = OFF

above a determined value of electric power. It is possible that these contextscould become active at the same time creating a context conflict since theydefine an opposite action on the same resource.

Facing a conflict, the system must be able to detect its presence and decidewhich context has priority and should execute the action on the shared resource.A conflict resolution policy has to be defined during the system implementationchoosing from techniques which impose several priority criteria. To cite someexamples:

• Absolute Priority with a Total Ordering. As the name suggests, a totalordering is established among the contexts which operate on the sameresource. Clearly, the winner in a conflict is the context with higherpriority.

• Absolute Priority with Partitioned Ordering. Contexts which operate onthe same resource are split into two sets: on the first one the designerestablishes a total order, the second set contains contexts with the samepriority level. In case a conflict happens between contexts in the latterset, the winner is chosen randomly.

• Relative Priority. The designer decides the conflict winner with respectto a single combination of contexts.

• Minimum Duration Priority. The winner is chosen based on the actionwhich lasts for less time.

• Maximum Duration Priority. The context with the action which haslasted for more time, wins.

The best solution would be the first one, the Absolute Priority with a TotalOrdering because it establishes a winner for every combination of conflictcontexts. The main drawback falls on the designer who has to declare the totalordering for each set of contexts that can be in conflict over a resource. Thegravity of this charge increases with the number of contexts.

66

Page 75: Context Management in a Pervasive System · noise. La tesi presente descrive le fasi del design di caratteristiche context-aware e il loro sviluppo integrato ad un middleware pervasivo

5.4. Conflict management

5.4.1 Conflict Detection in PerLa

The Conflict Detection procedure is performed before the ContextExecutor

component executes the actions of an active context. As the available actionscan only be expressed in terms of queries, the only contexts which can conflictare those that specify actions on the same resource by means of actuationqueries.

The IConflictDetector interface, Listing 5.7 contains two methods useful fordeciding if a context is in conflict with another. The implementation of thesemethods enforces the chosen resolution conflict policy.

1 public interface IConflictDetector

2 boolean isInConflict(Context context , List <Context >

activeContexts);

3

4 boolean isInConflict(Context a, Context b);

5

Listing 5.7: The IConflictManager Interface

In order to apply a policy based on an ordering, it would be required to integratethe Context Language with a clause expressing the context priority or by usingsome external configuration files. At the moment, it was chosen to apply thefollowing policy: when a context is set as active by the ContextDetector,before the ContextExecutor starts executing the newly activated context, theContextDetector.isInConflict method is invoked. For each contexts alreadyactive, it is checked whether the new context is in conflict. In case, the contextis not in conflict with any of the concurrent contexts its actions are executed.If in conflict, on the contrary, the new context’s actions are executed and theother context is deactivated.

Referring to the previous scenario about the dispute involving the air conditioner,the winner context would be probably the second one, as the overloaded riskhappens after the context in which the air conditioner has been operating forcooling down the office temperature.

67

Page 76: Context Management in a Pervasive System · noise. La tesi presente descrive le fasi del design di caratteristiche context-aware e il loro sviluppo integrato ad un middleware pervasivo
Page 77: Context Management in a Pervasive System · noise. La tesi presente descrive le fasi del design di caratteristiche context-aware e il loro sviluppo integrato ad un middleware pervasivo

Chapter 6

Study case

6.1 A ski resort application

In order to show a complete use of the usefulness of the context-aware PerLaSystem, in the following, a case of a possible application is presented. In thisexample a pervasive system is employed to monitor all the potential risk andsituations that may occur inside a ski resort.

Recently, technology companies have developed wearable devices that promiseto provide a better user experience to skiers. Wearable technology is stronglyrelated to ubiquitous computing and is constantly on the rise. Sensors, embeddedin small objects that every person can wear like watches or wristbands, keeptrack of many aspects: from the user’s position to his heart rate. Just to makesome examples of ski wearable gear:

• Carv. Reading from the creator’s website [27], it is “your digital ski coach”.It measures motions and pressure distribution, it connects wirelessly to asmartphone to give feedback to improve the user’s skiing with techniqueanalysis.

• Oakley Airwave Googles. They are integrated with a display which showsin real time speed, time, location, distance, altitude or airtime, [28]. Thespecial sunglasses also allow to load resort maps and use special functionsto find friends on the snow tracks.

• POC Receptor Bug. It is a ski helmet [29], that in addition to protect fromfalls, has incorporated headphones built that allow the user to answercalls, switch tunes and adjust volume without using the smartphone.

These wearable devices address only the user’s ski experience or performance.

69

Page 78: Context Management in a Pervasive System · noise. La tesi presente descrive le fasi del design di caratteristiche context-aware e il loro sviluppo integrato ad un middleware pervasivo

Chapter 6. Study case

The intent of our study case is to monitor the whole ski resort focusing ondetecting and preventing potential dangers. We will follow the canonical phaseof the design and implementation of a context-aware application. First, to let thereader familiarize with the background, a general overview of the environmentis presented. Once there is a clear understanding of the resources and servicesinvolved, the CDT model and contexts are defined.

6.1.1 Description of the environment

The chosen environment to simulate and monitor is the ski resort at the villageof Livigno. Livigno is one of the most complete ski resorts in Lombardia fromboth the point of view of the ski area and for what concerns the hospitality andservices. Due to the harsh climate, the snow remains until late in the season,soft and powdery; then, if the natural one is missing, the number of cannonsfor artificial snow are ready to prepare a solid ground on the slopes.

In Livigno people can ski from late November to early May; the ski resort ownsseveral infrastructures:

• 115 kilometers of snow tracks of various levels

• 11 ski lifts

• 13 chairlifts

• 6 gondolas

In our simulated scenario, on the snow runs, a smart sensor network is usedfor monitoring several environment properties such as snow composition inmountain slopes or the weather; data, suitably aggregated, can be used fornumerous purposes. This sensor network will be comprised of devices havingthe ability to communicate, compute and sense the environment temperature,light intensity, pressure, and other snow properties.

In a real scenario, many types of snow sensors are available in the market,able to detect falling or blowing snow at very low temperatures. For example,the CIT-1 snow sensor is a reliable and sensible sensor with automatic snowmelting control while the 260-700 Ultrasonic Snow Depth one is an inexpensivesolution for remotely measuring snow depth or water levels. The latter sensorworks by measuring the time required for an ultrasonic pulse to travel to andfrom a target surface and a temperature probe provides an air temperaturemeasurement for properly compensating the distance measured.

70

Page 79: Context Management in a Pervasive System · noise. La tesi presente descrive le fasi del design di caratteristiche context-aware e il loro sviluppo integrato ad un middleware pervasivo

6.1. A ski resort application

Figure

6.1.

ER

dia

gram

for

ask

ire

sort

71

Page 80: Context Management in a Pervasive System · noise. La tesi presente descrive le fasi del design di caratteristiche context-aware e il loro sviluppo integrato ad un middleware pervasivo

Chapter 6. Study case

6.2 Database

The domain data of a ski resort covers a very large set of concepts, whichcan be conceptually modelled by means an Entity-Relationship (ER) diagram.Figure 6.1 shows an initial ER which represents a small part of the wholeapplication domain. At the centre of the diagram there is the entity SKIRESORT around which many entities revolve: SKILIFT, SLOPE, PEOPLE andSNOW GROOMER. Each entity is identified by an ID and a list of attributes.The main components of a ski resort are the slopes, characterized by length anddifficulty level; the last one is symbolized by a color: blue for the easiest one,red for tracks of medium difficulty and finally the black ones.

A ski lift is a transport means that carries skiers up the side of a slope, it canbe of three types: a gondola which is a closed cabin driven by motors, a chairlift or a T-bar to which skiers hang on while they are dragged up the ski run.

A snow groomer is a mean such as a tractor or snowcat used to maintain cleanski slopes by moving, flattening or compacting the snow on them. Finally, manypeople pass by a ski resort. From the simple customer to the employee whichoperates the entire structure. Ski instructors direct ski courses with a variablenumber of lessons and participants and employees control the snow groomersand ski lifts. The Emergency staff takes action whenever a risk situation occurswhich require quick intervention.

6.3 CDT schema

Figure 6.2 shows an example CDT describing the environment to monitor. Theprevious ER is the initial diagram which the designer can analyse, extractingthe relevant dimensions and concepts inherent to a suitable CDT. It is worthunderlining the fact that not all data belonging to the ER should appear asCDT nodes. The ER diagram is a data model used for describing informationaspects of an application and their relationships in an abstract way and thefinal model is implemented in a database. Instead, the CDT is the modelwhich describes the environment in which an application acts, that capturesthe ambient characteristics which are meaningful for identify and distinguishcontexts.

The main dimensions of the CDT are: Role, SnowCondition, Wind, Visibility,WeatherCondition, Season, Place and Risk. The dimension Role correspondsto the entity People of the ER diagram and it can be used to specify whichactions a user is entitled to do. Its concept nodes are Customer, a SnowGroomDriver a Lift Staff, a Ski Instructor or a member of the Rescue Squad with the

72

Page 81: Context Management in a Pervasive System · noise. La tesi presente descrive le fasi del design di caratteristiche context-aware e il loro sviluppo integrato ad un middleware pervasivo

6.3. CDT schema

Figure 6.2. Example of a CDT for a ski resort

addition of the Base Station.

Skiing hides potential risks, some serious, other less problematic. The leastgrave Risk is when a particular ski lift is overcrowded because it is a convenientposition and, as a result, a long queue appears. The most dangerous one is anavalanche, which comes unexpectedly and every year claims victims.

The dimensions Wind, Weather and Visibility identify different independentparameters of the weather condition. A user is also interested in the Snow (Icy,Slushy and Soft) as it can be annoying for an inexperienced skier to ski on aslope covered with not optimal snow. Note how these dimensions have not acorresponding ER entity because they are real situations that may happen andnot system data which are recorded into a database.

Another dimension which is not present in the ER is the Season, as a ski resortis often opened not only in winter and the season influences many aspects ofthe environment, first of all, the weather and the snow conditions.

To conclude, the dimension Place represents a different part of the ski resort.In a context, we are interested if the user is skiing following a Slope, if he isbeing transported by a Skilift or warms inside a refuge or if he is working atthe Rescue Centre.

Before listing the Context Language code to define the CDT in PerLa, it isnecessary to select which sensors the ski resort system should possess to fullyexploit context-aware capabilities, in particular:

73

Page 82: Context Management in a Pervasive System · noise. La tesi presente descrive le fasi del design di caratteristiche context-aware e il loro sviluppo integrato ad un middleware pervasivo

Chapter 6. Study case

• a weather station equipped with sensors to detect rainfall and snowprecipitations, measured usually in inches or millimetres, and sensors tomeasure atmospheric visibility;

• scattered on the snow tracks, sensors able to detect different snow prop-erties such as snow depth, snow density or snow water equivalent. Snowdensity can be measured as mass per volume (kg/m3) or as a ratio withrespect to the density of water. So, if the density of water of 1000 1000(kg/m3), snow which is 100 (kg/m3) is specified as 100/1000, or 10 percent(of the density of water).

• before a ski lift, there are sensors able to estimate the length of a queueof people waiting to access the lift. An existing sensor of this type iscalled the “People Counter”, a 3D sensor based on the optical time offlight principle. A source emits modulated near-infrared light; the phasedifference between the light emitted by the source and the light reflectedby the object in the field of view is measured to create a real-time imageof the area. Installed at multiple locations over a queue, it accuratelyprocesses its length and duration.

In addition to these physical sensors placed in various strategic points of theski resort, some information must be retrieved from external sources. In thissimulated environment, for example, to know if a ski instructor is holding alesson, we refer to the external database that keeps track of the lesson schedules.

To complete the environment description, we list the resources used to performthe context actions:

• in strategical location speakers are placed

• along the sky tracks lights are placed

The most critical phase of the CDT design is linking physical or measurableenvironment aspects to the symbolic Concepts. Monitoring the snow conditionsin order to prevent major risks is a daunting task which requires a deepknowledge of the properties of snow and of the devices which provide algorithmsand functionalities that detect them. Clearly, this is a superficial example;we will just limit to present a simplified version, trying to be as realistic aspossible. Respecting some logical considerations and assumptions, we illustratehow the WhenCondition of the CDT’s Concepts have been defined. A finalremark concerns the measuring system of the sensors. According to the chosensensor for measuring a physical parameter, its output is expressed with a specificmeasure unit.

The dimension Snow Condition can assume four values: Icy, Slushy, Soft or

74

Page 83: Context Management in a Pervasive System · noise. La tesi presente descrive le fasi del design di caratteristiche context-aware e il loro sviluppo integrato ad un middleware pervasivo

6.3. CDT schema

Low. The last value refers to the situation when there is little snow depositedon the slopes. If it has been cold and has not snowed for a while, snow on thetracks will start to get icy because skiers keep going over the same layer ofsnow compacting it more and more until it becomes very solid. Contrarily, if ithas snowed recently, snow is relatively soft. Snow becomes slushy when it issaturated with water, typically when it is too warm during the day and the snowstarts to melt. According to [30], new snowfall has density between 7% and 12%but can increase depending on wind exposure. Higher density (heavier) snowresults from warmer temperatures and/or winds while lower density (lightersnow) usually results from colder air with less wind. The density will increaseover time due to snow settlement. Old snow may reach 40% to 50% densityand the highest density of ice known is fully mature glacier ice. On the base onthese estimations, we define:

CREATE CONCEPT Icy WHEN temperature: < -5

AND snow_density > 0.30

EVALUATED ON ’EVERY 30 m SELECT temperature, snow_density

SAMPLING EVERY 10 m

EXECUTE IF EXISTS (temperature) OR EXISTS (snow_density)’

CREATE CONCEPT Soft WHEN temperature BETWEEN -5 AND 6

AND snow_density < 0.12

EVALUATED ON ’EVERY 30 m SELECT temperature, snow_density

SAMPLING EVERY 10 m

EXECUTE IF EXISTS (temperature) OR EXISTS (snow_density)’

CREATE CONCEPT Slushy WHEN temperature > 8

AND snow_density BETWEEN 0.12 AND 0.29

EVALUATED ON ’EVERY 3 0m SELECT temperature, snow_density

SAMPLING EVERY 10 m

EXECUTE IF EXISTS (temperature) OR EXISTS (snow_density)’

CREATE CONCEPT LOW WHEN snow_depth < 10 cm

EVALUATED ON ’EVERY ONE SELECT snow_depth

SAMPLING EVERY 1 d EXECUTE IF EXISTS (snow_depth)’

The main relevant weather condition can be derived from an intelligent use ofthe available sensors. A light precipitation is not an issue and can be overlooked.In order to reduce the energy consumption of the sensors since the rain, snowor fog are not phenomena which have to be constantly sampled, the conditionalsampling is exploited. In case the sensor does not detect the weather conditionor it is not influential (e.g a light rain or snow), the sampling rate is kept

75

Page 84: Context Management in a Pervasive System · noise. La tesi presente descrive le fasi del design di caratteristiche context-aware e il loro sviluppo integrato ad un middleware pervasivo

Chapter 6. Study case

every 30 minutes and it increases when the sensor observes the phenomenon.Sensors detecting the presence of fog uses different techniques by determiningthe amount of light scattered by particles or the number of water particles.

CREATE CONCEPT Rain WHEN rainfall_level > 5ml

EVALUATED ON ’EVERY 30 m SELECT rainfall_level

SAMPLING IF (rainfall_level < 2 ml) EVERY 30 m

ELSE every 10 m

REFRESH EVERY 30 m EXECUTE IF EXISTS(rainfall_level)’

CREATE CONCEPT Snow WHEN snowfall_level > 5 ml

EVALUATED ON ’EVERY 30 m SELECT snowfall_level

SAMPLING IF (snowfall_level < 2 ml) EVERY 30 m

ELSE every 10 m

REFRESH EVERY 30 m EXECUTE IF EXISTS(snowfall_level)’

CREATE CONCEPT Fog WHEN fog > 0.5

EVALUATED ON ’EVERY 30 m SELECT fog

SAMPLING IF (fog > 20 meters) EVERY 30 m ELSE every 10 m

REFRESH EVERY 30 m EXECUTE IF EXISTS(fog)’.

The risk of Avalanche is very complicated to postulate since it depends onmany factors such as the snow water equivalent, the snow liquid water content,strong wind blowing on slopes covered with extra snow and many other factors.In our simplified simulation, when a certain number of sensors change theirposition because they are swept away by the snow movement, the Avalanche riskoccurs. We consider only the sensors which are placed at dangerous slopes wherethe possibility of an avalanche is high. Again we use the sampling conditionincreasing the sampling rate during the day when skiers may be in danger andreducing it during the night when no one can be hit. The function isDay() is anotation to quickly state that the system returns a time between 8 am and 8pm, while isNight() returns true during the evening hours. The other functionisInZone() is a simple notation to express whether a sensor belongs to a certainzone.

CREATE CONCEPT AVALANCHE WHEN numberMovedSensor > 10

EVALUATED ON ’EVERY ONE coordinateX > threadshold1

AND coordinateY > threadshold2 SAMPLING IF isDay() EVERY 1 m

ELSE EVERY 1h REFRESH EVERY 6h EXECUTE IF isInZone(coordinateX,

coordinateY)’

To determine the values of the dimension Place, it is reasonable to supposethat a sensor is attached to a stationary node and it has a static attribute

76

Page 85: Context Management in a Pervasive System · noise. La tesi presente descrive le fasi del design di caratteristiche context-aware e il loro sviluppo integrato ad un middleware pervasivo

6.4. Netowork topology

which specifies its location. The retrieval can be done both from a system staticmethod or querying the device with a very low sampling rate.

CREATE CONCEPT SLOPE WHEN position = ’slope’

EVALUATED ON ’EVERY ONE SELECT position SAMPLING EVERY 1d EXECUTE IF

EXISTS (position)’

CREATE CONCEPT Skilift WHEN position = ’skilift’

EVALUATED ON ’EVERY ONE SELECT position SAMPLING EVERY 1d EXECUTE IF

EXISTS (position)’.

The remaining CDT’s concepts are of immediate understanding as they don’tneed further analysis. Notice how ad-hoc functions have been used such asgetIdRole() or getMonth() to obtain contextual information that are not directlyretrievable from the sensor network.

6.4 Netowork topology

Probably, the most complicated part in the design of a wireless sensor network isthe topology. One of the main issues for a deployment of sensor nodes is energyconsumption, so it is important to decide which sensors should be connected tothe electric power or have their own energy supply through batteries. The mapof the resort (Figure 6.3) underlines the slopes as brown lines while the ski liftsare represented with red-dotted lines. The network topology is made up of asink, base stations and sensors. The sink is the core of the network, the centralserver with a running PerLa system. A base station is an intermediate nodewith a certain power and computational capabilities connected to a sink. Itreceives sensor data and transmits them the sink. Finally, sensor nodes acquireinformation from the surrounding environment, process locally the data andsend them to one or more base stations whose position must be chosen carefullytrying to optimize the communication.

Referring to the map, we imagine placing the base stations at the start andarrival point of the chair lifts. In these points weather sensors should be deployed,connecting them directly to the electrical network enables to have more powerfuldevices and reduce the cost of deployment and maintenance. The other sensorsare disseminated in the whole ski resort and rely on internal batteries or solarpanels. The PerLa system connects to the FPCs through base stations sendingqueries to them based on the data it needs. The base stations have the role toforward the queries to the connected sensors and to other base stations. Themost straightforward approach between PerLa and the base stations is to usea direct GSM connection. If this option is not available due to the limitednetwork availability, a radio connection can be established or multiple signal

77

Page 86: Context Management in a Pervasive System · noise. La tesi presente descrive le fasi del design di caratteristiche context-aware e il loro sviluppo integrato ad un middleware pervasivo

Chapter 6. Study case

Figure 6.3. Livigno ski resort map

repeaters can be installed in strategical points, for example on the chair lift’spuncheon in order to extend the signal range.

6.5 Context

Once defined the CDT, we now proceed to define some contexts that areparticularly relevant to the scenario. To privilege brevity and compactness, theactions are illustrated directly with the context definition, although the actionsof a context should be defined as partial components of the concepts used inthe context activation condition and automatically composed.

Winter MonitoringWinter is the most problematic season when there is a constant flow of customersand weather conditions are more unpredictable. For this reason, it is wise tomonitor more frequently the snow conditions.

CREATE CONTEXT WinterMonitoring

ACTIVE IF Season = Winter AND Role = BaseStation

ON ENABLE: EVERY 1h SELECT temperature, snow_density, rainfall_level,

snow_depth, visibility, wind_strength SAMPLING EVERY 10 m

EXECUTE IF EXISTS (temperature) OR EXISTS (snow_density)

78

Page 87: Context Management in a Pervasive System · noise. La tesi presente descrive le fasi del design di caratteristiche context-aware e il loro sviluppo integrato ad un middleware pervasivo

6.5. Context

OR EXISTS (rainfall_level) OR EXISTS (snow_depth)

OR EXISTS (visibility) OR EXISTS (wind_strength)

REFRESH EVERY 30 d

Not wanting to be repetitive, during spring and autumn similar contexts haveto be monitored changing the frequency rate accordingly. In spring temperaturemust be taken under stricter control increasing its sample rate, while it is lesslikely for snow precipitation to occur. In autumn, rainfall may happen morefrequently thus increasing the rainfall sample rate is helpful.

Icy PistesIcy pistes can be problematic as skiers have little control on maintaining balanceand a steady speed. The Listing contains the context used to monitor icy pistesrecording which tracks are iced. This information could then be displayed onmonitors of the ski resort giving advice about which tracks should be avoided ifthe skier is not talented or confident enough

CREATE CONTEXT IcyPistes

ACTIVE IF Place = Slope AND SnowCondition = Icy AND Role = Customer

ON ENABLE: EVERY 30 m SELECT temperature, snow_density

SAMPLING EVERY 10 m

EXECUTE IF EXISTS (temperature) OR EXISTS (snow_density)

REFRESH EVERY 1 h

Slushy PistesThe opposite situation that icy tracks are slushy tracks. When the snow keepsmelting and refreezing, snowflake structure is lost and what is left is many littlelumps of ice. Slushy snow is heavy and skiers can not slide so easily. Theseconditions are more common during the spring season. As for icy runs, a contextis defined to monitor which snow runs are slushy and can be an issue for skiers.

CREATE CONTEXT SlushyPistes

ACTIVE IF Place = Slope AND SnowCondition = Slushy

AND Role = Customer

ON ENABLE: EVERY 30 m SELECT temperature, snow_density

SAMPLING EVERY 10 m

EXECUTE IF EXISTS (temperature) OR EXISTS (snow_density)

REFRESH EVERY 1 h

79

Page 88: Context Management in a Pervasive System · noise. La tesi presente descrive le fasi del design di caratteristiche context-aware e il loro sviluppo integrato ad un middleware pervasivo

Chapter 6. Study case

Little VisibilityThe following context monitors a situation with little visibility, dangerous for askier who can easily lose sense of direction or not see obstacles. Little visibilitycan derive from a whiteout effect or when there is heavy snowfall. To improvevisibility additional light signals are turned on near the edges of the slopes tobetter guide skiers.

CREATE CONTEXT LittleVisibility

ACTIVE IF Place = Slope AND Visibility = Limited

AND Role = BaseStation

ON ENABLE: EVERY 30 m SELECT visibility

SAMPLING EVERY 10 m EXECUTE IF EXISTS (visibility)

SET lights = ’on’

ON DISABLE SET lights = ’off’

REFRESH EVERY 30 m

Blizzard MonitoringA blizzard is the most dangerous condition on the mountain. It is when thereis a strong wind and it is snowing heavily. Designing a specific context enablesto detect the beginning of a blizzard and warn in time skiers advising them tobe careful and maybe go back to a refuge.

CREATE CONTEXT LittleVisibility

ACTIVE IF WeatherCondition = Snow AND Wind = Strong

AND Role = BaseStation

ON ENABLE: EVERY 10 m SELECT wind_strength SAMPLING EVERY 1 m

EXECUTE IF EXISTS (wind_strength)

SET alarm = ’on’

ON DISABLE SET alarm = ’off’

REFRESH EVERY 30 m

80

Page 89: Context Management in a Pervasive System · noise. La tesi presente descrive le fasi del design di caratteristiche context-aware e il loro sviluppo integrato ad un middleware pervasivo

Chapter 7

Conclusions

7.1 Final consideration

In this work, we presented the components used to add a context man-agementlayer to the PerLa System. The components provide a general and robustsupporting infrastructure through which the notion of context can be integratedwith the existing PerLa functionalities giving a primordial intelligence. Eachof the created new components is responsible for a distinct phase during theexecution flow of a typical context-aware system. The main goal of the extendedmiddleware is to be of help in monitoring applications that use dynamic andpervasive data for specific purposes. This lead to the following key designprinciples:

- Easy abstract model. The most critical development point is at design time,when the designer must carefully consider and analyse the environmentto select which characteristics are relevant for the application. The typeof context information that is relevant to model and handle varies acrossapplications. The designer must have the right expertise to capturesignificant aspects discarding pointless ones keeping in mind that as thefreedom of design is increased, at the same time the system becomesmore complex and more difficult to implement. The environment is thencategorized as a list of possible situations, contexts which are representedby a model. In the years, many context models have been proposed, fromthe simple ones like the key-value model to the most complex ones likeontologies. In PerLa, the Context Definition Tree model (CDT) has beenchosen and implemented because it is flexible, easy to use and at the sametime, it gives the designer a considerable expressive power.

81

Page 90: Context Management in a Pervasive System · noise. La tesi presente descrive le fasi del design di caratteristiche context-aware e il loro sviluppo integrato ad un middleware pervasivo

Chapter 7. Conclusions

- Support for generic inputs. The designer has to decide which sensorinputs to expect in a certain context. He has to find parameters thatdefine a context and find means to measure those parameters. The PerLamiddleware has the advantage of supporting the use of a wide variety ofsensors to acquire contextual information. Important sensors used areGPS (for location and speed), light and vision (to detect objects and activ-ities), microphones (for information about noise, activities, and talking),accelerometers and gyroscopes (for movement, device orientation, andvibration), magnetic field sensors (as a compass to determine orientation),proximity and touch sensing (to detect explicit and implicit user interac-tion), sensors for temperature and humidity (to assess the environment),and air pressure/barometric pressure. There are also sensors to detect thephysiological context of the user (e.g. galvanic skin response, EEG, andECG). Typically, such measurements can be used to determine reactionssuch as surprise or fear (lie detectors are based on similar mechanisms).In principle, one can use all types of sensors available on the market tofeed the system with context information.

- Separation of context inference from application code. Context inferenceis the process of interpreting and deducing high level context informationfrom raw data retrieved from sensors or external sources. In PerLa, theinference process is performed during the mapping of the raw data to theCDT’s variables. The choice of letting the designer specify the mappingtogether with the context definition, allows the to separate the contextinference from the application code in a manner that opens the way to aneasy user’s configuration.

- Code tailoring. A large number of possible contexts, due to a rich CDTmodel, asks the designer to write a large number of actions, queries to beexecuted when a context is discovered as active or inactive which is aninefficient time-consuming task and error prone. The solution, called codetailoring, relies on a compositional strategy applied at design time: thedesigner must associate the CDT context elements with fragments of thefinal contextual blocks. Afterwards, an automatic composition process isperformed that produces the complete contextual block. This strategyhas the advantage of relieving the designer from a tedious task and at thesame time it gives him the control to change the final contextual blocks ifneeded.

82

Page 91: Context Management in a Pervasive System · noise. La tesi presente descrive le fasi del design di caratteristiche context-aware e il loro sviluppo integrato ad un middleware pervasivo

7.2. Open points

7.2 Open points

Besides the contribution of this work to add context-awareness to PerLa, somefunctionalities and issues can be explored. In this thesis, the problems arisingfrom conflicts between concurrent contexts and the possible decisional strategieshave been discussed. The chosen strategy gives priority to the most recentlyactivated context whenever a conflict may appear. This approach was chosenmainly because the other proposed strategies require changing the ContextLanguage with specific clauses to associate a priority value to each contextcreating a partial or total ordering among contexts. Although this approachis time-consuming for the designer which has to decide the winner context forevery situation in which a conflict may arise, it has the advantage of setting adefinite criteria and respect user’s preference.

Context information can originate from a wide variety of sources, leading toheterogeneity in terms of quality and persistence. Context inputs can roughlybe categorized in sensed, static or user-supplied information. Data producedby sensing nodes is usually highly dynamic and prone to noise and sensingerrors, while user-supplied information is initially reliable, but easily becomesout of date; as consequence we have to deal with the problem of imperfectcontext information. Some context modelling solutions address part of thisproblem by allowing context information to be associated with quality metadata,such as origin, accuracy, certainty and freshness estimates [31]. However, thisapproach does not address the entire problem. For instance, it does not providea solution for representing or reasoning about ambiguity or unknowns. Thesetypes of imperfection are common when sensors or other providers of contextinformation report conflicting values or fail to report values at all. In fact, theother type of conflict which we have been neglected up to this point is the dataconflict. In other words, an input channel reports information that is clashingwith the corresponding information provided by another input channel. Suchsituations are not as exceptional as they may seem. On the contrary, dealingwith inconsistencies means adjusting the level of trust associated with each inputchannel. In PerLa, sensor raw data are previously aggregated thus significantlyreducing noise and inconsistencies between sources. Still, the problem is presentas a source could produce a completely senseless sample that compromises thefinal aggregated result in case the aggregation is evaluated on few samples. Inshort, data conflicts is more damaging when there are few data sources with theconsequence that even if the final data is aggregated, the result can be ruined.A possible solution can be to add a level of trust to data sources which are morevulnerable to faults and devise algorithms or strategies to deal with conflictinginputs which privilege more reliable sources.

83

Page 92: Context Management in a Pervasive System · noise. La tesi presente descrive le fasi del design di caratteristiche context-aware e il loro sviluppo integrato ad un middleware pervasivo
Page 93: Context Management in a Pervasive System · noise. La tesi presente descrive le fasi del design di caratteristiche context-aware e il loro sviluppo integrato ad un middleware pervasivo

Chapter 8

Appendix

8.1 XLM Device Description of a snow sensor

The Device Descriptor portrayed in this example is employed to create aSimulator FPC which represents a possible snow sensor used within the ski resortenvironment. The Simulator FPC is a useful tool that helps to test the PerLaMiddleware when no physical sensor nodes are available. This device exposes sixattributes with different data types and access permissions. Four attributes areread-only floats representing the temperature in Celsius degree, the humidityexpressed as a ratio of the vapour pressure in the air to its saturation, the depthof the deposited snow and the value of the snow density. The attribute positionis defined a static since it is reasonable to assume that this type of sensors areplaced in a fixed location and they will not be moved. For example, this sensoris located at the slope called ”slope1”. The last attribute is a write-only integerthat will be used to set the sampling period.

This FPC contains one Channel of type SimulatorChannel which generates newdata samples without requiring a connection to a real sensing device. In thisexample, the SimulatorChannel is configured with data generation routines,named measures, that automatically creates new data samples spanning from aminimum to a maximum for each attribute. The <request> section containsthe object to drive the data generators available in this FPC. Messages containthe data fields that the system receives after submitting a specific request tothe FPC. These two messages will be used to collect the samples and to set thedesired sampling period in the SimulatorChannel respectively. As can be seenfrom the ¡operation¿ section of this descriptor, the simulator device exposes aperiodic sampling operation named all-periodic. The start Script initializes theSimulatorChannel according to the sampling rate specified by the user, which

85

Page 94: Context Management in a Pervasive System · noise. La tesi presente descrive le fasi del design di caratteristiche context-aware e il loro sviluppo integrato ad un middleware pervasivo

Chapter 8. Appendix

is retrieved with a $arg[’period’] expression. New output records are createdby the on Script upon arrival of a message declared in the <message> section.The generation of new data samples can be stopped by setting the samplingfrequency to zero.

<?xml version="1.0" encoding="UTF -8"?>

<device type="Weather simulator"

xmlns="http :// perla.dei.org/device"

xmlns:i="http :// perla.dei.org/device/instructions"

xmlns:sim="http :// perla.dei.org/channel/simulator">

<attributes >

<attribute id="temperature" type="float"

permission="read -only"/>

<attribute id="humidity" type="float"

permission="read -only"/>

<attribute id="snow_depth" type="float"

permission="read -only"/>

<attribute id="snow_density" type="float"

permission="read -only"/>

<attribute id="position" type="string"

access="static" value="pista1"/>

<attribute id="period" type="integer"

permission="write -only"/>

</attributes >

<channels >

<sim:channel id="simulator">

<sim:generator id="measures">

<sim:field name="temperature" qualifier="dynamic"

type="float" min=" -30" max="30"/>

<sim:field name="humidity" qualifier="dynamic"

type="float" min="10" max="90"/>

<sim:field name="snow_depth" qualifier="dynamic"

type="float" min="0" max="300"/>

<sim:field name="snow_density" qualifier="dynamic"

type="float" min="50" max="900"/>

</sim:generator >

<sim:generator id="snow_condition">

<sim:field name="snow_depth" qualifier="dynamic"

type="float" min="0" max="300"/>

<sim:field name="snow_density" qualifier="dynamic"

type="float" min="50" max="900"/>

</sim:generator >

86

Page 95: Context Management in a Pervasive System · noise. La tesi presente descrive le fasi del design di caratteristiche context-aware e il loro sviluppo integrato ad un middleware pervasivo

8.1. XLM Device Description of a snow sensor

<sim:generator id="enviroment_condition">

<sim:field name="temperature" qualifier="dynamic"

type="float" min=" -20" max="20"/>

<sim:field name="humidity" qualifier="dynamic"

type="float" min="10" max="90"/>

</sim:generator >

</sim:channel >

</channels >

<messages >

<sim:message id="measures -msg">

<sim:field name="temperature" type="float"/>

<sim:field name="humidity" type="float"/>

<sim:field name="snow_depth" type="float"/>

<sim:field name="snow_density" type="float"/>

<sim:field name="position" type="string"/>

</sim:message >

<sim:message id="position -msg">

<sim:field name="position" type="string"/>

</sim:message >

<sim:message id="snow_condition -msg">

<sim:field name="snow_depth" type="float"/>

<sim:field name="snow_density" type="float"/>

</sim:message >

<sim:message id="environmental_condition -msg">

<sim:field name="temperature" type="float"/>

<sim:field name="humidity" type="float"/>

</sim:message >

<sim:message id="sampling -period">

<sim:field name="period" type="integer"/>

</sim:message >

</messages >

<requests >

<sim:request id="measures -request"

generator="measures"/>

<sim:request id="snow_condition -request"

generator="snow_condition"/>

<sim:request id="environment -request" generator="

enviroment_condition"/>

</requests >

<operations >

87

Page 96: Context Management in a Pervasive System · noise. La tesi presente descrive le fasi del design di caratteristiche context-aware e il loro sviluppo integrato ad un middleware pervasivo

Chapter 8. Appendix

<periodic id="all -periodic">

<start >

<i:var name="period" type="sampling -period"/>

<i:set variable="period" field="period"

value="$param[’period ’]"/>

<i:submit request="measures -request"

channel="simulator">

<i:param name="period" variable="period"/>

</i:submit >

</start >

<stop >

<i:var name="period" type="sampling -period"/>

<i:set variable="period" field="period" value="0"/>

<i:submit request="measures -request"

channel="simulator">

<i:param name="period" variable="period"/> </i:submit >

</stop >

<on message="measures -msg" variable="result">

<i:put expression="$result.temperature"

attribute="temperature" />

<i:put expression="$result.humidity"

attribute="humidity" />

<i:put expression="$result.snow_depth"

attribute="snow_depth" />

<i:put expression="$result.snow_density"

attribute="snow_density" />

<i:put expression="$result.position"

attribute="position" /> <i:emit />

</on >

<on message="environmental_condition -msg"

variable="result">

<i:put expression="$result.temperature"

attribute="temperature" />

<i:put expression="$result.humidity"

attribute="humidity" /> <i:emit />

</on >

<on message="snow_condition -msg" variable="result">

<i:put expression="$result.snow_depth"

attribute="snow_depth" />

<i:put expression="$result.snow_density" attribute="

snow_density" />

<i:emit />

</on > </periodic > </operations > </device >

88

Page 97: Context Management in a Pervasive System · noise. La tesi presente descrive le fasi del design di caratteristiche context-aware e il loro sviluppo integrato ad un middleware pervasivo

Bibliography

[1] Bill N. Schilit, Norman Adams, and Roy Want. “Context-Aware Comput-ing Applications”. In: In proceedings of the workshop on mobile computingsystems and applications. IEEE Computer Society, 1994, pp. 85–90.

[2] Mark Weiser. “The Computer for the 21st Century”. In: SIGMOBILEMob. Comput. Commun. Rev. 3 (1999). issn: 1559-1662. url: http:

//doi.acm.org/10.1145/329124.329126.[3] Roy Want et al. “An overview of the PARCTAB ubiquitous computing

experiment.” In: IEEE Personal Commun. 2.6 (1995), pp. 28–43.[4] A. Dey. “Understanding and using context”. In: Personal Ubiquitous

Comput. 5 (2001), pp. 4–7.[5] N. S. Ryan, J. Pascoe, and D. R. Morse. “Enhanced Reality Fieldwork: the

Context-aware Archaeological Assistant”. In: Computer Applications inArchaeology 1997. Ed. by V. Gaffney, M. van Leusen, and S. Exxon. BritishArchaeological Reports. Oxford: Tempus Reparatum, 1998, pp. 182–196.url: http://www.cs.kent.ac.uk/pubs/1998/616.

[6] Harry Chen. “An Intelligent Broker Architecture for Pervasive Context-Aware Systems”. PhD thesis. University of Maryland, Baltimore County,2004.

[7] Karen Henricksen, Jadwiga Indulska, and Andry Rakotonirainy. “ModelingContext Information in Pervasive Computing Systems”. In: Pervasive ’02(2002), pp. 167–180. url: http://dl.acm.org/citation.cfm?id=646867.706693.

[8] Thomas Strang and Claudia Linnhoff-Popien. “A Context Modeling Sur-vey”. In: Workshop on Advanced Context Modelling, Reasoning and Man-agement, UbiComp 2004 - The Sixth International Conference on Ubiqui-tous Computing, Nottingham/England. 2004.

[9] Cristiana Bolchini et al. “A Data-oriented Survey of Context Models”. In:SIGMOD Rec. 36.4 (Dec. 2007), pp. 19–26. issn: 0163-5808.

[10] Matthias Baldauf, Schahram Dustdar, and Florian Rosenberg. “A Surveyon Contex Aware Systems”. In: Int. J. Ad Hoc Ubiquitous Comput. 2.4

89

Page 98: Context Management in a Pervasive System · noise. La tesi presente descrive le fasi del design di caratteristiche context-aware e il loro sviluppo integrato ad un middleware pervasivo

BIBLIOGRAPHY

(June 2007), pp. 263–277. issn: 1743-8225. url: http://dx.doi.org/10.1504/IJAHUC.2007.014070.

[11] Jong-yi Hong, Eui-ho Suh, and Sung-Jin Kim. “Context-aware Systems: Aliterature review and classification”. In: Expert Syst. Appl. 36 (2009). issn:0957-4174. url: http://dx.doi.org/10.1016/j.eswa.2008.10.071.

[12] Pradeeban Kathiravelu, Leila Sharifi, and Luıs Veiga. “Cassowary: Middle-ware Platform for Context-Aware Smart Buildings with Software-DefinedSensor Networks”. In: ACM, 2015, pp. 1–6. isbn: 978-1-4503-3731-1. url:http://doi.acm.org/10.1145/2836127.2836132.

[13] Tao Gu, Hung Keng Pung, and Da Qing Zhang. “Toward an OSGi-Based Infrastructure for Context-Aware Applications”. In: IEEE PervasiveComputing (Oct. 2004), pp. 66–74. url: http://dx.doi.org/10.1109/MPRV.2004.19.

[14] Patrick Fahy and Siobhan Clarke. “CASS – a middleware for mobilecontext-aware applications”. In: Workshop on Context Awareness, Mo-biSys. 2004.

[15] Weijun Qin, Yue Suo, and Yuanchun Shi. “CAMPS: A Middleware forProviding Context-aware Services for Smart Space”. In: Proceedings ofthe First International Conference on Advances in Grid and PervasiveComputing. Springer-Verlag, 2006. url: http://dx.doi.org/10.1007/11745693_63.

[16] Jakob E. Bardram. “The Java Context Awareness Framework (JCAF) –a Service Infrastructure and Programming Framework for Context-awareApplications”. In: Proceedings of the Third International Conference onPervasive Computing. PERVASIVE’05. Springer-Verlag, 2005. url: http://dx.doi.org/10.1007/11428572_7.

[17] Adrian Fitzpatrick et al. “Towards a Sentient Object Model”. In: In work-shop of enginerring context-aware object oriented systems and evironments.2002.

[18] F. A. Schreiber et al. “Perla: A language and middleware architecture fordata management and integration in pervasive information systems”. In:IEEE Transactions on Software Engineering 99 (2011).

[19] Marco Fortunato and Marco Marelli. “Design of a declarative languagefor pervasive systems”. Master Thesis. Politecnico di Milano, 2007.

[20] F. A. Schreiber et al. “Pushing context-awareness down to the core: moreflexibility for the Perla language”. In: Electronic Proc. 6th PersDB (2012),pp. 1–6.

[21] Cristiana Bolchini, Elisa Quintarelli, and Letizia Tanca. “CARVE: Context-aware Automatic View Definition over Relational Databases”. In: Inf.Syst. 38.1 (Mar. 2013), pp. 45–67. issn: 0306-4379.

90

Page 99: Context Management in a Pervasive System · noise. La tesi presente descrive le fasi del design di caratteristiche context-aware e il loro sviluppo integrato ad un middleware pervasivo

BIBLIOGRAPHY

[22] F. Schreiber et al. “Towards autonomic context-aware pervasive systems:the PerLa context language”. In: Electronic Proc. 6th NetDB (2011),pp. 1–7.

[23] JavaCC reference. url: \urlhttps://javacc.dev.java.net/.[24] E. Gamma et al. Design Patterns Elements of Reusable Object-Oriented

Software. Ed. by Addison-Wesley. 1995.[25] K. Sheykh-Esmaili et al. “Changing Flights in Mid-air: A Model for

Safely Modifying Continuous Queries”. In: ACM SIGMOD InternationalConference on Management of Data (SIGMOD’11). Athens, Greece, 2011.

[26] G. Pirotta, G. Pisati, and D. Pozzi. “Resolution of Context Conflicts inPervasive Systems”. Master Thesis. Politecnico di Milano, 2011.

[27] Carv project. url: \urlhttps://www.kickstarter.com/projects/333155164/carv- the- worlds- first- wearable- that- helps- you-

ski.[28] Snow Googles Airwave. url: \urlhttp://www.oakley.com/en/mens/

goggles/snow-goggles/airwave/product/WGOO7049i.[29] Poc Sports. url: \urlhttp://www.pocsports.com/en/product/1213/

receptor-bug.[30] Avalanche center. url: \urlhttp://www.avalanche-center.org/

Education/glossary/.[31] Hui Lei et al. “The Design and Applications of a Context Service”. In:

SIGMOBILE Mob. Comput. Commun. Rev. 6.4 (Oct. 2002), pp. 45–55.issn: 1559-1662.

91