programming mobile context-aware applications with totam

17
The Journal of Systems and Software 92 (2014) 3–19 Contents lists available at ScienceDirect The Journal of Systems and Software j ourna l ho mepage: www.elsevier.com/locate/jss Programming mobile context-aware applications with TOTAM Elisa Gonzalez Boix , Christophe Scholliers, Wolfgang De Meuter, Theo D’Hondt Software Languages Lab, Vrije Universiteit Brussel, Pleinlaan 2, 1050 Brussel, Belgium a r t i c l e i n f o Article history: Received 4 October 2012 Received in revised form 14 June 2013 Accepted 13 July 2013 Available online 1 August 2013 Keywords: Tuple spaces Programming abstractions Context-awareness a b s t r a c t In tuple space approaches to context-aware mobile systems, the notion of context is defined by the presence or absence of certain tuples in the tuple space. Existing approaches define such presence either by collocation of devices holding the tuples or by replication of tuples across all devices. We show that both approaches can lead to an erroneous perception of context. Collocation ties the perception of context to network connectivity which does not always yield the expected result. Tuple replication can cause that a certain context is perceived even if the device has left the context a long time ago. We propose a tuple space approach in which tuples themselves carry a predicate that determines whether they are in the right context or not. We present a practical API for our approach and show its use by means of the implementation of various mobile applications. Benchmarks show that our approach can lead to a significant increase in performance compared to other approaches. © 2013 Elsevier Inc. All rights reserved. 1. Introduction A growing body of research in pervasive computing deals with coordination in mobile ad hoc networks. Such networks are com- posed of mobile devices which spontaneously interact with other devices within communication range as they move about. This network topology is often used to convey context information to collocated devices (Murphy et al., 2001; Mascolo et al., 2002; Davies et al., 1998; Julien and Roman, 2004; Mamei and Zambonelli, 2004). Moreover, such context information can be used to opti- mize application behaviour given the scare resources of mobile devices (Mascolo et al., 2002). In this paper, we focus on distributed programming abstractions to ease the development of context- aware applications deployed in a mobile environment. Developing these applications is complicated because of two discriminating properties inherent to mobile ad hoc networks (Van Cutsem et al., 2007): nodes in the network only have intermittent connectivity (due to the limited communication range of wire- less technology combined with the mobility of the devices) and applications need to discover and collaborate without relying on a centralized coordination facility. Decoupled coordination models such as tuple spaces provide an appropriate paradigm for dealing with those properties (Mascolo et al., 2002). Several adaptations of tuple spaces have been specially developed for the mobile environ- ment (including LIME (Murphy et al., 2001), L2imbo (Davies et al., 1998), EgoSpaces (Julien and Roman, 2004), and TOTA (Mamei and Zambonelli, 2004)). In those systems, processes communicate by Corresponding author. Tel.: +32 2 629 3956; fax: +32 2 629 3525. E-mail address: [email protected] (E. Gonzalez Boix). reading from and writing tuples to collocated devices in the envi- ronment. Context information in such systems is thus represented by the ability to read certain tuples from the environment. In this paper we argue that this representation is inappropriate and can even lead to an erroneous perception of context. The main reason for this is that the ability to read a tuple from the environment does not give any guarantees that the context information carried by the tuple is appropriate for the reader. This forces programmers to manually verify that a tuple is valid for the application’s context situation after the tuple is read. To support the development of mobile context-aware appli- cations, we propose a novel tuple space approach called TOTAM (“Tuples On The Ambient”) which decouples the concept of tuple perception from tuple reception. A TOTAM tuple can contain an associated predicated called a context rule that describes the run- time conditions under which it is visible to applications. Only when a tuple’s context rule can be satisfied by the context of the receiving application, the tuple can be perceived by the application. Applica- tions can also be notified when the tuple can no longer be perceived. The core contribution of this work lies in proposing a tuple space model designed for a mobile environment which introduces a gen- eral programming concept under the form of a context rule to support development of mobile context-aware applications. Our contribution is validated by (1) a prototype implementation, (2) demonstrating the applicability of our model by using it in non- trivial context-aware mobile applications, (3) using our prototype implementation for teaching students, (4) providing an operational semantics for our model, (5) benchmarking our prototype imple- mentation. TOTAM has been employed in a realistic experiment with the Brussels public transport company. In addition, students have used 0164-1212/$ see front matter © 2013 Elsevier Inc. All rights reserved. http://dx.doi.org/10.1016/j.jss.2013.07.031

Upload: theo

Post on 27-Jan-2017

215 views

Category:

Documents


1 download

TRANSCRIPT

  • P

    ES

    a

    ARRAA

    KTPC

    1

    cpdntD2mdpa

    dCclaaswtm1Z

    0h

    The Journal of Systems and Software 92 (2014) 319

    Contents lists available at ScienceDirect

    The Journal of Systems and Software

    j ourna l ho mepage: www.elsev ier .com/ locate / j ss

    rogramming mobile context-aware applications with TOTAM

    lisa Gonzalez Boix , Christophe Scholliers, Wolfgang De Meuter, Theo DHondtoftware Languages Lab, Vrije Universiteit Brussel, Pleinlaan 2, 1050 Brussel, Belgium

    r t i c l e i n f o

    rticle history:eceived 4 October 2012eceived in revised form 14 June 2013ccepted 13 July 2013vailable online 1 August 2013

    a b s t r a c t

    In tuple space approaches to context-aware mobile systems, the notion of context is defined by thepresence or absence of certain tuples in the tuple space. Existing approaches define such presence eitherby collocation of devices holding the tuples or by replication of tuples across all devices. We show thatboth approaches can lead to an erroneous perception of context. Collocation ties the perception of contexteywords:uple spacesrogramming abstractionsontext-awareness

    to network connectivity which does not always yield the expected result. Tuple replication can causethat a certain context is perceived even if the device has left the context a long time ago. We proposea tuple space approach in which tuples themselves carry a predicate that determines whether they arein the right context or not. We present a practical API for our approach and show its use by means ofthe implementation of various mobile applications. Benchmarks show that our approach can lead to asignificant increase in performance compared to other approaches.. Introduction

    A growing body of research in pervasive computing deals withoordination in mobile ad hoc networks. Such networks are com-osed of mobile devices which spontaneously interact with otherevices within communication range as they move about. Thisetwork topology is often used to convey context informationo collocated devices (Murphy et al., 2001; Mascolo et al., 2002;avies et al., 1998; Julien and Roman, 2004; Mamei and Zambonelli,004). Moreover, such context information can be used to opti-ize application behaviour given the scare resources of mobileevices (Mascolo et al., 2002). In this paper, we focus on distributedrogramming abstractions to ease the development of context-ware applications deployed in a mobile environment.Developing these applications is complicated because of two

    iscriminating properties inherent to mobile ad hoc networks (Vanutsem et al., 2007): nodes in the network only have intermittentonnectivity (due to the limited communication range of wire-ess technology combined with the mobility of the devices) andpplications need to discover and collaborate without relying on

    centralized coordination facility. Decoupled coordination modelsuch as tuple spaces provide an appropriate paradigm for dealingith those properties (Mascolo et al., 2002). Several adaptations of

    uple spaces have been specially developed for the mobile environ-

    ent (including LIME (Murphy et al., 2001), L2imbo (Davies et al.,998), EgoSpaces (Julien and Roman, 2004), and TOTA (Mamei andambonelli, 2004)). In those systems, processes communicate by

    Corresponding author. Tel.: +32 2 629 3956; fax: +32 2 629 3525.E-mail address: [email protected] (E. Gonzalez Boix).

    164-1212/$ see front matter 2013 Elsevier Inc. All rights reserved.ttp://dx.doi.org/10.1016/j.jss.2013.07.031 2013 Elsevier Inc. All rights reserved.

    reading from and writing tuples to collocated devices in the envi-ronment. Context information in such systems is thus representedby the ability to read certain tuples from the environment. In thispaper we argue that this representation is inappropriate and caneven lead to an erroneous perception of context. The main reasonfor this is that the ability to read a tuple from the environmentdoes not give any guarantees that the context information carriedby the tuple is appropriate for the reader. This forces programmersto manually verify that a tuple is valid for the applications contextsituation after the tuple is read.

    To support the development of mobile context-aware appli-cations, we propose a novel tuple space approach called TOTAM(Tuples On The Ambient) which decouples the concept of tupleperception from tuple reception. A TOTAM tuple can contain anassociated predicated called a context rule that describes the run-time conditions under which it is visible to applications. Only whena tuples context rule can be satisfied by the context of the receivingapplication, the tuple can be perceived by the application. Applica-tions can also be notified when the tuple can no longer be perceived.The core contribution of this work lies in proposing a tuple spacemodel designed for a mobile environment which introduces a gen-eral programming concept under the form of a context rule tosupport development of mobile context-aware applications. Ourcontribution is validated by (1) a prototype implementation, (2)demonstrating the applicability of our model by using it in non-trivial context-aware mobile applications, (3) using our prototypeimplementation for teaching students, (4) providing an operational

    semantics for our model, (5) benchmarking our prototype imple-mentation.

    TOTAM has been employed in a realistic experiment with theBrussels public transport company. In addition, students have used

    dx.doi.org/10.1016/j.jss.2013.07.031http://www.sciencedirect.com/science/journal/01641212http://www.elsevier.com/locate/jsshttp://crossmark.crossref.org/dialog/?doi=10.1016/j.jss.2013.07.031&domain=pdfmailto:[email protected]/10.1016/j.jss.2013.07.031

  • 4 E. Gonzalez Boix et al. / The Journal of Sys

    Legend

    Context Provider

    Perceives Correct Context

    Perceives Wrong Context

    Target Context

    Network Connectivity

    World

    RR

    omtmhtraIaec

    2

    Lsemsotoatao

    iibciiEtiloiu

    btaiatnt

    Fig. 1. Context perception in existing tuple space approaches.

    ur tuple space based approach for the development of variousobile peer-to-peer applications. These experiences have led us

    o significantly improve previous iterations of our tuple spaceodel (Scholliers et al., 2010) in two fundamental ways. First, weave developed a leasing model which allows the underlying sys-em to reclaim tuples in the face of partial failures. Second, we haveevisited the propagation mechanism included in TOTAM whichllows developers to scope the distribution of tuples in the network.n this paper, we report on the various extensions that we havepplied over our original tuple space abstractions and how thesextensions ease the development of mobile context-aware appli-ations.

    . Motivation

    Tuple spaces were first introduced in the coordination languageinda (Gelernter, 1985). Recently they have shown to provide auitable coordination model for the mobile environment (Mascolot al., 2002). In the tuple space model, processes communicate byeans of a globally shared virtual data structure (called a tuplepace) by reading and writing tuples. A tuple is an ordered groupf values (called the tuple content) and has an identifier (called theype name). Processes can post and read tuples using three basicperations: out to insert a tuple into the tuple space, in to remove

    tuple from the tuple space and rd to check if a tuple is present inhe tuple space (without removing it). Tuples are anonymous andre extracted from the tuple space by means of pattern matchingn the tuple content.In order to describe the main motivation behind TOTAM, we

    ntroduce a simple yet representative scenario and show the lim-tations of existing tuple space approaches. Consider a companyuilding where each room is equipped with devices that act asontext providers of different kinds of information. For example,nformation to help visitors to orient themselves in the build-ng or information about the meeting schedule in a certain room.mployees and visitors are equipped with mobile devices whichhey use to plan meetings or to find their way through the build-ng. Since each room is equipped with a context provider, a userocated in one room will receive context information from a rangef context providers. Only part of this context information whichs broadcasted in the ambient is valid for the current context of theser.Fig. 1 illustrates the scenario where represents the company

    uilding, a meeting room in the building, and the communica-ion range of a device located in the meeting room. The star denotes

    tuple space (acting as the context provider) which injects tuplesnto the ambient, i.e., all devices (depicted as dots) . Those tuples

    re aimed to be perceived by devices in the meeting room, i.e., inhe target area . This device injects a tuple in the ambient to sig-al receivers that they are currently in the meeting room. Notehat location is just one example of context, could involve moretems and Software 92 (2014) 319

    complex constraints, e.g. being located in the meeting room whilethere is a meeting.

    We now give an overview of how context is perceived in thetwo most prominent tuple space models. A first group of tuple spacemodels, follows a federated tuple space model (Murphy et al., 2001)in which the visibility of the tuples (and thus context perception)directly depends on collocation of devices holding these tuples. Inthis model, the perceived context of a device is equivalent to beingin range of . The context delivery solely based on makes twogroups of devices to perceive wrong context information (depictedas black dots). The first group consists of devices contained in theset \ . In our example, these are all devices within communica-tion range of the context provider but outside the meeting room.These devices will perceive to be in the meeting room while they areactually not. The second group consists of devices contained in theset \ . In our example, these are all devices out of communicationrange of the context provider (possibly due to an intermittent dis-connection) but in the meeting room. These devices will perceivenot to be in the meeting room while they actually are.

    Other tuple space systems have adopted a replication modelwhere tuples are replicated amongst collocated devices in orderto increase data availability in the face of intermittent connectiv-ity (Mamei and Zambonelli, 2004; Murphy and Picco, 2006). Inreplication-based models, devices in \ will not perceive wrongcontext information. However, in these systems tuple perception isequivalent to have been once within reach of , possibly in the past.This means that devices which have been connected to the contextprovider once () and are currently in \ (depicted as black dotswith a R) will perceive to be in the meeting room even though theyare no longer there.

    2.1. Summary

    Using current tuple space approaches the context perception iscorrect in certain cases (the white dots) but, in many cases it iswrong (black dots). There are three main reasons for these erro-neous context perceptions. First, there is a connectivity-contextmismatch making context sharing based solely on connectivityunsuitable for the development of context-aware applicationsdeployed in a mobile setting. Second, the observed context isaffected by intermittent connectivity: temporal disconnectionswith the context provider result in an erroneous context per-ception. Third, when using replication-based models to deal withintermittent connectivity, a permanent disconnection leads devicesto perceive a certain context forever. In order to solve these issues,programmers are forced to manually verify that every tuple (andthus context information) is valid for the application context. Moreconcretely, programmers have to manually determine tuple per-ception at the application level after a tuple is read from the tuplespace. Manually determining the applications context and adaptaccordingly leads to context-related conditionals (if statements)being scattered all over the program (Costanza and Hirschfeld,2005), hindering modularity. Additionally, the content of the tupleshave to be polluted with meta data in order to infer tuple perceptionat application level, decreasing reusability of tuples. For example,a Room tuple indicating that a person is currently located in themeeting room should also contain the location information. Finally,programmers need to write application level code that deals withcontext-awareness in order to compensate for the lack of expres-siveness of underlying model.

    As the complexity of context-aware applications increases,manually computing tuple perception can no longer be solved

    using ad hoc solutions. Instead, the coordination model shouldbe augmented with abstractions for context-awareness that allowdevelopers to describe tuple perception in the coordination modelitself. In this work, we introduce TOTAM, a novel approach that

  • E. Gonzalez Boix et al. / The Journal of Systems and Software 92 (2014) 319 5

    VM VM

    tuple

    Applications

    Applications

    Tuple Space System

    Tuple Space Rule Engine Tuple Space System

    Tuple Space

    Rule Engine

    Tuple Space System

    Tuple Space

    Rule Engine

    M tup

    kaar

    3

    mfiTirTZdro

    ttiosfcssipttdpMai

    PtstpocT

    diTT

    flow of

    Fig. 2. The TOTA

    eeps the simplicity of the tuple space model where interactionsnd context information are defined by means of tuples, whilellowing tuples themselves to determine the context in which aeceiving application should be in order to perceive a tuple.

    . The TOTAM approach

    TOTAM is a novel tuple space-based programming model forobile context-aware applications. It adopts concepts from both

    ederated and replication-based tuple spaces, and extends themn order to overcome the aforementioned tuple perception issues.he TOTAM system introduces the notion of a context rule prescrib-ng when a tuple should be perceived by the application, and aule engine to infer when a tuple is perceivable and when it is not.OTAM has a scoping mechanism (inspired by TOTA (Mamei andambonelli, 2004)) and a leasing model that allows developers toeal with the hardware characteristics of a mobile setting. In theemainder of this section, we describe the most important featuresf our model.The core model. The model underlying TOTAM tuples extends

    he notion of a traditional tuple space with machinery to controlhe scope and visibility of tuples. Fig. 2 depicts our model. A devicen the network corresponds to a virtual machine (VM) carrying oner more TOTAM tuple spaces. Each virtual machine forms a TOTAMystem. TOTAM systems are interconnected by means of a MANET,orming a TOTAM network. The composition of a TOTAM networkhanges according to the network topology. A TOTAM system con-ists of a tuple space, and a rule engine which infers when a tuplehould be perceived by applications. The tuple space serves as thenterface between applications and the TOTAM system. It only sup-orts non-blocking Linda-like operations to insert, read and removeuples. The main reason for the strict non-blocking operations ishat it significantly reduces the impact of volatile connections on aistributed application. As an alternative to blocking operations, werovide the notion of a reaction to a tuple (similar to LIME reactions;urphy et al., 2001): applications can register an observer that issynchronously notified when a tuple matching a given templates read or removed from the tuple space.

    The tuple space of a TOTAM system contains two types of tuples.ublic tuples denote tuples that are shared with remote TOTAM sys-ems, and private tuples denote tuples that remain local to the tuplepace in which they were inserted and thus will not be transmit-ed to other TOTAM systems. Applications can insert private andublic tuples in the tuple space by means of the out and injectperation, respectively. As in LIME, applications can access tuplesoming from the network without knowing the different collocatedOTAM systems explicitly.Distribution of tuples in the network. When two TOTAM systemsiscover each other in the network, the public tuples containedn their tuple spaces are cloned and transmitted to the collocatedOTAM system according to a propagation protocol (reminiscent ofOTA propagation rules; Mamei and Zambonelli, 2004). However,s in the model

    le space model.

    in contrast to TOTA, TOTAM triggers the propagation protocol beforea tuple is being physically transmitted to a new TOTAM system, andafter it is received by the new TOTAM system. Thus, the tuple itselfcontains all the information needed to dynamically adjust its scopein the TOTAM network while being propagated. In addition, sucha scoping mechanism avoids unnecessary exchange of tuples andenhances privacy because the protocol can enforce that a tuple isnot transmitted to a TOTAM system which is not in its scope. Thisdiffers from techniques in which the tuple space itself is scopedand tuples have to be inserted in a certain scope which can not bechanged after the facts. To be able to compute the scope of a tuple,each tuple space has a tuple space descriptor. This descriptor con-tains semantic information that is used by the tuples at sendingtime in order to decide whether a certain TOTAM system is in theirscope. Descriptors are exchanged between two TOTAM systemswhen they meet for the first time or whenever a system decidesto change its description.

    Coordination. Our model combines replication of tuples forread operations (to support time-decoupled communication) whileguaranteeing atomicity for removal operations (to support syn-chronization). In order for a remove operation to succeed, thesystem which created and injected the tuple in the network (calledthe originator system) needs to be connected. The underlying modeldoes not remove tuples unless the originator system has acknowl-edged the operation. As such, a remove operation in our approachis executed atomically as defined in Linda (Gelernter, 1985): if twoprocesses perform a remove operation for a tuple, only one removesthe tuple. When an originator is asked to remove one of its (stored)tuples by another system, it removes the tuple and injects an anti-tuple for the removed tuple in the network. By means of antituples,TOTAM systems can unsend tuples injected to the network. Forevery tuple there is (conceptually) a unique antituple with the sameformat and content, but with a different sign. All tuples injected byan application have positive sign while their antituples have a neg-ative sign. Whenever a tuple and its antituple are stored in the sametuple space, they annihilate one another, i.e., they both get removedfrom the tuple space.

    Supporting context-awareness. TOTAM tuples can carry a con-text rule that describes the runtime conditions under which thetuple is visible to an application, facilitating the development ofcontext-aware applications deployed in a mobile environment.More precisely, a context rule is conceived as a set of conditionsdefined in terms of the presence of other tuples in the receivingtuple space. Such context rule is defined by the creator of the tupleand gets transmitted together with the tuple when the tuple isinjected in the network. Defining context rules in terms of tuplesallows the application to abstract away from the underlying hard-ware while keeping the simplicity of the tuple space model (both

    interactions and context information are defined using tuples).

    When a tuple is inserted at a certain TOTAM system, the tupleis first handed over to the rule engine which installs the neces-sary machinery to evaluate the tuples context rule. When the rule

  • 6 E. Gonzalez Boix et al. / The Journal of Systems and Software 92 (2014) 319

    Perceivable CR Deactivation

    in [template]

    [!context rule] / OC Listeners

    Non-perceivableCR Activation

    Non-perceivableCR Retracted

    Non-perceivable CR Deactivation

    [context rule]

    rd [template]out [!context rule]

    [!context rule] / OC Listeners

    etfiit

    rcptsblte

    abpUTacsi

    tttpic(l

    tisotce

    alrga

    t

    Fig. 3. Lifespan of a context-aware tuple.

    ngine infers that the conditions on a context rule are satisfied,he tuples context rule is triggered and the rule is said to be satis-ed. Only when the context rule of a tuple is satisfied, is the tuplenserted in the tuple space of the TOTAM system. At that moment,he applications are able to read the tuple.

    The rule engine plays a central role in our model as it takes care ofeflecting the changes to the receivers context so that applicationsannot perceive those tuples whose context rule is not satisfied. Inarticular, it observes the insertion and removal of the tuples inhe tuple space to infer which context rules are satisfied, and sub-equently control which tuples present in the tuple space shoulde actually accessible by applications. As a result, programmers noonger need to infer the presence or absence of tuples manually ashe rule engine takes care of it in an efficient way, making the codeasier to understand and maintain.The lifespan of a context-aware tuple. Context rules introduce

    new dimension to the lifespan of a tuple. Not only can a tuplee inserted or removed from the tuple space, it can now also beerceivable or non-perceivable for the application. Fig. 3 shows aML-state diagram for the lifespan of a context-aware tuple, i.e., aOTAM tuple carrying a context rule. When an application inserts

    tuple in a TOTAM system,1 the tuple is non-perceivable and itsontext rule is asserted by the rule engine. The rule engine thentarts listening for the activation of that context rule (CR activationn the figure).

    A tuple will become perceivable depending on whether or nothe context rule is satisfied. If the context rule is satisfied, theuple is perceivable and it is subject to tuple space operations (andhus becomes accessible to the application). If the tuple is non-erceivable, the tuple is not subject to tuple space operations butts context rule remains in the rule engine. Every time a tuplesontext rule is not satisfied, the out-of-context listeners of a tupleOC listeners in the figure) are triggered. Applications can installisteners to be notified when a tuple moves out of context.

    Upon performing an in operation, the tuple is removed fromhe tuple space but its context is not modified. As such, the tuples considered not to be perceivable (as it is no longer in the tuplepace) and its context rule remains in the rule engine. Once outf the tuple space, the rule engine listens for the deactivation ofhe context rule. Once the context rule is no longer satisfied, theontext rule is retracted from the rule engine, and the tuple will beventually garbage collected.A best effort leasing model. In order to support resource man-

    gement in the face of permanent disconnections, we integrate aeasing model into public tuples. Designing a leasing model for a

    eplication-based model, however, is challenging because tupleset replicated through a highly dynamic network topology. As such,t the moment a tuple needs to be removed it might not be possible

    1 To keep the figure concise out denotes the insertion of a private or a publicuple.Fig. 4. The CAP theorem.

    to reach all systems where it was replicated to. The root problem isthat a fundamental trade-off needs to be made between consistencyand availability of data. Such a trade-off was first remarked in thedomain of web services as Brewers conjecture and later, formal-ized and proven as the CAP theorem in (Gilbert and Lynch, 2002).The theorem, depicted in Fig. 4, states that it is impossible to simul-taneously provide consistency, availability and partition tolerance;only two can be guaranteed at the same time. Since MANET appli-cations must almost always be partition-tolerant because failuresare inherent to the network topology, a choice needs to be madebetween providing consistency or availability. Relaxing consistencyallows the system to remain highly available in the face of partialfailures, while emphasizing consistency implies that the systemmay not be available under certain conditions. Since not havingaccess to services can be considered the rule in a mobile setting,trading off consistency provides a scalable solution. Not only pro-viding consistency usually introduces communication overhead, itmay be also difficult (if not impossible) to achieve without mak-ing assumptions about the mobility of devices (Murphy and Picco,2006).

    In TOTAM, we have introduced a leasing model which does notguarantee strong consistency, but only guarantees best effort. Theunderlying system tries hard to remove all replicas of a tuple, butdoes not give guarantees when this will happen. It is importantto notice that the system does guarantee that the tuple is onlyremoved once. All tuples are injected in the network with an asso-ciated lease denoting the total lifespan of a tuple. It is determinedby the application that creates and injects the tuple to the network.Programmers can specify the lease time interval by means of ded-icated support (explained later). A lease is encoded as part of thepropagation protocol, and as such, it is transmitted together withthe tuple when it gets replicated and transmitted to another TOTAMsystem. When the lease term has elapsed, independently of thestate in which a tuple is, the tuple becomes candidate for garbagecollection in the TOTAM system. This means that the tuples con-text rule is retracted from the rule engine, and the tuple is removedfrom the tuple space if necessary.

    The transitions for leasing have been omitted from Fig. 3 to keepit clear and concise. The lease of a tuple adds a transition from anystate to the state representing that a tuple is non-perceivable andits context rule is retracted. When a public tuple gets removed asa result of an in operation, the underlying system sends an antitu-ple to those systems that have previously received a replica of theremoved tuple. If a TOTAM system cannot be reached, the removalof the tuple is delayed until its lease expires in the disconnectedTOTAM system, or until it is in range with one of the TOTAM systemscarrying its antituple.

    4. Operational semanticsBefore describing TOTAMs programming API, we formalize ourtuple space model by means of a calculus with operational seman-tics based on prior work in coordination (Viroli and Casadei, 2009;Viroli and Omicini, 2006). The syntax of our model is defined by the

  • E. Gonzalez Boix et al. / The Journal of Sys

    Table 1TOTAM tuples: grammar.

    k : : =+ | | Tuple typesc ::= kx,t r TupleS : : = | c, S Tuple setP : : = | A . P ProcessC : : = | ( S x | C) | (P | C) Configuration

    gacwfia

    ii

    Tbioo

    frtmmeis

    ttu

    axcittstssWttuit

    s(o(pttt

    start playing a game. After the game, they get the wild idea to orga-A : : = out(x, , r, t)| inject(x, , r, t) | rd(x, ) | in(x, ) |outC(x, ) | whenRead(x, , Pa , Pd) . P | whenIn(x, , Pa , Pd) . P Actions

    rammar shown in Table 1. k identifies the type of the tuple: + for public tuple, for a private tuple and for an antituple. A tuple

    is specified as a first order term . kx,tr indicates that the tupleith content , type k and time interval of its lease t, originates

    rom a tuple space with identifier x and is only perceivable whents context rule r is satisfied. The context rule is considered optionalnd the notation kx,t should be read as

    kx,t1, i.e., the context rule

    s always true. The antituple of a tuple kx,t is denoted by x,t0, i.e.,

    ts context rule is always false.A process P consists of a sequence of tuple space operations A.

    uples are stored in S which is defined as a set of tuples composedy the operator (,). A tuple space with content S and identifier xs denoted by S x. A system configuration C is modeled as a setf processes P and collocated tuple spaces S x composed by theperator |. An application consists of all P C.Next to the grammar, we assume the existence of a matching

    unction (, ) that takes a template and a tuple content , andeturns . is a substitution map of variable identifiers from theemplate to the actual values from . A concrete value in thisap can be accessed by z that returns the actual value for z. Theatched tuple can be accessed by . We also assume the exist-nce of a function time which returns a numeric comparable valuendicating the current time. r(S) indicates that the context rule r isatisfied in the tuple set S.

    The semantics of the our tuple space model is defined by the

    ransition rules shown in Table 2. Every transition CC indicates

    hat a configuration C can be transformed into a configuration C

    nder the condition .The (OUT) rule states that when a process performs an out oper-

    tion over a local tuple space x, the tuple is immediately inserted in as a private tuple with context rule r and timeout t. The processontinuation P is executed immediately. When a tuple is insertedn the tuple space x with an inject operation as specified by (INJ),he tuple is inserted in x as a public tuple and is replicated to otheruple spaces as specified by (RPL). This rule states that when a tuplepace y moves in communication range of a tuple space x, all tupleskx,t which are not private and are not already in y will be replicatedo y. The (RD) rule states that to read a template from a tuplepace x, x has to contain a matching ky,t and the context rule of isatisfied in S. (RD) blocks if one of these conditions is not satisfied.hen (RD) does apply, the continuation P is invoked with substi-

    ution map . Note that we do not disallow x to be equal to y inhis rule. The (KILL) rule specifies that when both a tuple and itsnique antituple are stored in the same tuple space, is removedmmediately. The (TIM) rule specifies that when the timeout of auple elapses, its antituple is inserted in the tuple space.

    The in operation is guaranteed to be atomically executed. In theemantics, it has been split into a local rule (INL) and a remote ruleINR). (INL) works similarly to (RD), but it removes the tuple kx,triginated by the local tuple space x and inserts its antituple x,t .INR) states that when the in operation is matched with a tupleublished by another tuple space y, y must be one of the collocated

    uple spaces (i.e., be in the configuration). Analogously to (INL), theuple is removed and its antituple is inserted. The (OC) rule stateshat to move out of context a tuple from a local tuple space x, xtems and Software 92 (2014) 319 7

    has to contain (possibly its antituple) and its context rule is notsatisfied. The WR rule states that a whenRead operation performedon the local tuple space x with template and processes Pa and Pd,is immediately translated into a new parallel process and the con-tinuation P will be executed. The newly spawned parallel process isspecified in terms of performing a rd operation followed by an outCoperation. A rd operation blocks until there is a tuple matching inthe local tuple space. The continuation Pa is then executed to sub-sequently perform an outC which blocks until the tuple is no longerperceivable. Finally, the continuation Pd is invoked whereafter theprocess dies. The WI is specified analogously but as it models awhenIn operation, it performs a in operation rather than a rd one.The wheneverRead and wheneverIn operations have been omittedas they are trivial recursive extensions of whenRead and whenIn,respectively.

    Note that (KILL) does not remove antituples. This has been omit-ted to keep the semantics simple and concise. By means of (RPL),the antituple of a tuple is only replicated to those systems thatreceived . In our concrete implementation if a system cannot bereached, the removal of the antituple is delayed until the timeout ofits tuple elapses (which inserts an antituple as specified by (TIM)).An antituple can only be removed once there are no processes in theconfiguration which registered an outC operation on the originaltuple.

    5. Programming in TOTAM

    In this section, we describe TOTAM from a programmersperspective. We have implemented TOTAM as a middleware inAmbientTalk, a distributed object-oriented programming languagespecifically designed for mobile ad hoc networks (Van Cutsem et al.,2007). Table A.4 in Appendix A summarizes TOTAMs programmingAPI which we further detail in this section. We introduce the nec-essary syntax and features of the AmbientTalk language along withour explanation. We illustrate the set of operations provided byTOTAM by means of a concrete application called Guanotes that weuse as running example throughout this section.

    5.1. Running example: the Guanotes application

    Guanotes is one of the default applications of Urbiflock (GonzalezBoix et al., 2011): a framework implemented in AmbientTalk forscripting social applications running on Android phones interac-ting via mobile ad hoc networks. It allows end-users to interact withtheir social networks (organized in flocks) by means of messages. Aflock typically denotes a group of nearby users that match a numberof user-defined criteria. Messages in Guanotes are called guanotes.A guanote can be sent to the users belonging to a flock which arecurrently in in their direct neighbourhood, or to all (reachable)users belonging to the target flock regardless of whether they arecurrently connected in the Urbiflock platform.

    To exemplify the kinds of interactions using Guanotes, considerthe following scenario: Alice and Bob are in the cafeteria of theuniversity sports complex when they decide it would be nice toplay some badminton. Since reserving the badminton field is ratherexpensive, Bob decides to invite some extra players by taking hismobile phone and using Guanotes to send a message to the couplescurrently in the neighborhood who like to play badminton. Luck-ily, Carol and Denis who also wanted to play badminton see theinvitation. They reply to Bobs message whereafter they meet andnize a badminton competition for next week. Again Bob takes hismobile phone and decides to send an invitation to all couples at theuniversity who like badminton.

  • 8 E. Gonzalez Boix et al. / The Journal of Systems and Software 92 (2014) 319

    Table 2Operational semantics.

    out(x, , r, t) . P| S x|C t=time()+t P|

    x,t r, Sx |C (OUT)inject(x, , r, t) . P| S x|C t

    =time()+t P|+x,t r, Sx |C (INJ)

    kx,t r, Sx |Sy|C /S(k /= )

    (x /= y)kx,t r, Sx |kx,t r, Sy |C (RPL)

    rd(x, ).P|ky,t r, Sx |C(,)=(k /= )

    r(S)P|ky,t r, Sx |C (RD)

    y,t 0, ky,t r, Sx |C(k /= ) y,t 0, Sx |C (KILL)

    ky,t r, Sx |Cttime()(k /= ) y,t 0, Sx |C (TIM)

    in(x, ).P|kx,t r, Sx |C(,)=r(S)

    (k /= )P|x,t 0, Sx |C (INL)

    in(x, ).P|+y,t r, Sx |+y,t r, Sy|C(,)=r(S)

    (x /= y)P|Sx |y,t 0, Sy|C (INR)

    outC(x, ).P|ky,t r, Sx |C!r(S) P|ky,t r, Sx |C (OC)

    whenRead(x, , Pa , Pd) . P| S x|C 1 rd(x, ) . Pa . outC(x, ) . Pd|P| S x|C (WR)whenIn(x, , Pa , Pd) . P| S x|C 1 in(x, ) . Pa . outC(x, ) . Pd|P| S x|C (WI)

    plesFl

    ttBFrtic(lmi

    5

    pt

    ew(TaaoiA

    default lease (i.e., a lease time interval predefined at the actorlevel). It returns a publication object with two methods: a cancelmethod that allows programmers to stop the propagation of theFig. 5. Bobs (a) NearbyFlock, (b) badmintonCou

    Fig. 5 shows Urbiflock on Bobs device during the process ofyping a guanote after playing a match with Carol and Denis. In par-icular, four different screenshots are displayed: (a) the contents ofobs NearbyFlock, (b) the contents of Bobs badmintonCouples-lock, (c) Bobs Guanotes inbox (that contains a guanote previouslyeceived from Carol replying to his first invitation), and (d) the edi-or for a new guanote to invite all his friends couples to participaten a badminton tournament. Note that there are few users collo-ated at this time with Bob (people in the NearbyFlock shown ina)) which belong to the badmintonCouplesFlock (b). As he wouldike to reach all couples interested in badminton for the tourna-ent, he selects the badmintonCouplesFlock in the receiver list

    n Fig. 5(d).

    .2. Defining and inserting TOTAM tuples

    In order to create a TOTAM system and add it to the network,rogrammers can invoke the makeTupleSpace constructor func-ion as follows:

    def totam:= makeTupleSpace(descriptor);

    totam.goOnline();

    This operation initializes a TOTAM system including the rulengine and the tuple space. Variables are defined with the key-ord def and assigned to a value with the assignment symbol

    :=). The newly created TOTAM system is then published in theOTAM network by means of the goOnline operation. This oper-tion returns a publication object with a cancel method to be

    ble to remove the system from the TOTAM network. From thenn, the newly created system perpetually looks for other systemsn the TOTAM network and exchanges its descriptor with them.s explained before, the descriptor contains semantic informationock, (c) Guanotes inbox and (d) Guanote editor.

    relevant to the propagation of tuples. In the Guanotes application,the description is embodied in the user profile which is imple-mented as an isolate including fields representing the semanticinformation associated with the user (e.g., name, gender, hobbies,etc.).

    We provide the out(tuple) operation to insert a private tuplein the tuple space. In order to insert a public tuple, thereby makingit available to other collocated TOTAM systems, the inject: oper-ation is provided. The code excerpt below illustrates the injectionof the guanote depicted in Fig. 5(d).

    def aGuanote:= tuple: [guanote, username, badmintonCouplesFlock,

    Guys, what about a 2-on-2 next week?];

    totam.inject: aGuanote;

    A tuple is created by means of the tuple: operation whichtakes as argument a list of fields (implemented in AmbientTalkas a table). As usual, the first field of a tuple is its type name.In this case, the tuples type name is the guanote type tag.2

    A tuple representing a guanote consists of the sender of thetuple (stored in the username variable), the receiver target group(in this case the badmintonCouplesFlock group) and a textualmessage.

    In its simplest form, the inject: operation takes as argu-ment a tuple and injects the tuple into the network with adefault context rule (i.e., the context rule is always true), and a2 Type tags are a classification mechanism employed in AmbientTalk to categorizeobjects explicitly using a nominal type.

  • of Sys

    tdmrcieS

    tticilpiaf

    t

    i

    dit

    5

    wtilTpeaosttTe

    t

    copy object implementing a number of methods which are calledby the the underlying TOTAM system before and after transmittinga tuple. In this section, we explain the API of TOTAMs propagationE. Gonzalez Boix et al. / The Journal

    uple in the TOTAM network, and a retract method that allowsevelopers to unexport a tuple injected into the network (byaking the system send an antituple to all TOTAM systems which

    eceived that tuple). A tuple carries a default propagation proto-ol that propagates it to all reachable TOTAM systems, exactly asn TOTA, i.e., it does not restrict the propagation of tuples. Wexplain how to encode and apply custom propagation protocols inection 5.4.Table A.4 shows the complete form of the inject: opera-

    ion. The withLease: parameter takes an time interval denotinghe specific duration of the lease associated with the tuple. ThenContext: parameter takes a context rule defined as a tableontaining the set of templates and constraints that need to be sat-sfied for the tuple to be perceivable. Constraints are conceived asogical conditions on the variables used in a template. For exam-le, consider that certain guanotes are only visible if the user isn, e.g., the cafeteria area. In order to model that a device is in

    room, the application could inject a dedicated public tuple asollows:

    otam.inject: (tuple: [inRoom, cafeteriaRoom])

    nContext:[tuple:[location, ?loc], withinBoundary(roomArea,?loc)];

    The inRoom tuple is a helper tuple which allows a guanote toetermine when the user is in the cafeteria area. To this end, thenRoom tuple carries a context rule which consists of two termshat need to match:

    First, there must be a tuple in the tuple space encoding the loca-tion of the user, i.e., matching the tuple: [location,?loc]template.3 The ? operator indicates a variable in a template. Asshown in Table A.4, variables are actually defined using the var:construct which takes a symbol as argument. This paper will usethe ? operator in order to ease the reading. In our example, thetemplate matches any location tuple in the tuple space.Second, the location tuple needs to satisfy a constraint: itscoordinates have to be within the area of the room. ThewithinBoundary function returns such a constraint given thecoordinates stored in the ?loc variable and the cafeteria areastored in roomArea variable.

    .3. Reading and removing tuples from the TOTAM network

    In order to read and remove public tuples from the TOTAM net-ork, programmers can use reactions to register a block of code

    hat is executed when a tuple matching a template is insertedn the tuple space, reminiscent to LIME reactions. In what fol-ows, we describe the 4 kinds of reactions supported (shown inable A.4). The when:read: operation takes as argument a tem-late to observe in the tuple space, and a closure that serves as avent handler to call when the tuple matching the template is avail-ble in the tuple space. It actually performs a reaction to a readperation, i.e., the matching tuple is not removed from the tuplepace. In its simplest form, the when:read: operation only triggershe event handler once for a matching tuple. If several perceivableuples match the template, one is chosen non-deterministically.he whenever:read: operation works analogously but it trigg-rs the event handler for every perceivable tuple matching the3 A template is created by means of the tuple: operation as well. However, onlyemplates can take variables as fields.tems and Software 92 (2014) 319 9

    template. The code excerpt below illustrates the usage of when-ever:read: in the implementation of the Guanotes application.

    def listenForGuanotesToOwner(guiListener) {def guanoteTemplate:= tuple: [guanote, ?from, ?to, ?msg];

    totam.whenever: guanoteTemplate read: {guiListener

  • 10 E. Gonzalez Boix et al. / The Journal of Systems and Software 92 (2014) 319

    Listing 1. The TOTAM propagation protocol at sender side.

    Listing 2. The TOTAM propagation protocol at receiver side.

    pp

    acdaaTdc

    aIstwuiaro

    gatptowcpm

    casinos, etc.). When a gangster commits a crime, policemen areinformed of the location and the amount of money stolen. Police-men can see the position of all nearby policemen and send messages

    5 Demos of the best student projects of the latest academic years are available athttp://www.youtube.com/playlist?list=PL71615F77073CD26C&feature=plcp.

    6 Flikken means cops in Flemish.7 http://www.lamosca.be/en/the-target.rotocols and how programmers can define custom propagationrotocols.Listing 1 shows the protocol before propagating the tuple (i.e.,

    t sender side). First, decideDie is called. It returns a boolean indi-ating whether or not the tuple should be removed. If the protocolecides not to remove the tuple, the protocol will be asked whether

    potential receiver is in the scope of this tuple. inScope takes asrgument the descriptor of the sender and receiver tuple space.he protocol can then decide to propagate the tuple to the receiverescriptor. Finally, before transmitting the tuple, the protocol canhange its content (line 5).

    Listing 2 shows the protocol on the receiver side. A tuple is firstsked whether it should enter the receiving tuple space (line 1).t will then be allowed to execute some action on the local tuplepace (line 2). Finally the tuple can change its content and decideo notify the local tuple space that it arrived (lines 3 and 4). Tuplesith a protocol which do not notify the local tuple space can besed, e.g., to remove inappropriate tuples. The code excerpt belowllustrates how the Guanotes application creates a custom prop-gation protocol to be carried by guanotes which should only beeceived by users within direct communication range, i.e., systemsnly one hop away.

    1 def makeGuanoteToNearbyUsers(from, msg){2 def oneHopProtocol:= propagationProtocol: {3 def hops:= 0;4 def inScope(senderTs, senderDes, receiverDes) {5 hops < 1;6 };7 def changeTupleContentOnReceive(ts) {8 hops:= hops +1;9 self.getContent();10 };11 };12 tuple: [guanote, from, to, msg]13 withPropagationProtocol: guanotesProtocol;14 };

    propagationProtocol: is an operation that allows the pro-rammer to quickly create a custom protocol. It expects asrgument a code block that is used to extend the default propaga-ion protocol prototype (which corresponds to a tuple which alwaysropagates to every tuple space encountered). In this example,he inScope and changeTupleContent methods are overriden inrder to limit the propagation of the guanote. The inScope methodill verify that the tuple has been transmitted only one hop. ThehangeTupleContent increments the hop counter. Line 12 showsrogrammers can associate a propagation protocol with a tuple byeans of the tuple:withPropagationProtocol: construct.Fig. 6. Flikken GUI on the gangster device (left) and a policeman device (right).

    6. Developing mobile applications with TOTAM

    We have build several applications in TOTAM to showcase thesuitability and applicability of its programming API. TOTAM has alsobeen used as a teaching platform in the Master in Computer Sciencecurriculum at the Vrije Universiteit Brussel, for a course on mobileand distributed computing. Students have used TOTAM for sim-ple exercises as well as programming projects implementing, e.g.,multi-player mobile games such as a urban game for collaborativenoise mapping5 Not only has application development served us tovalidate programming abstractions proposed in TOTAM, but it hasalso uncovered the real needs of developers.

    In this section, we elaborate on two applications that benefitfrom using TOTAM to enable communication in a mobile settingin which devices interact via wireless ad hoc connections. The firstone involves the ability to detect and react to changes in the appli-cation context, while the second one involves the ability to performcollaborative tasks in the presence of disconnections. We concludethe section by describing the use of TOTAM in an industrial casewith the Brussels public transport company.

    6.1. Flikken

    Flikken6 is a game in which players equipped with mobiledevices interact in a physical environment augmented with vir-tual objects. Flikken is a significant subset of an augmented realitygame inspired by the industrial game The Target.7. The game con-sists of a dangerous gangster on the loose with the goal of earning1 million euro by committing crimes. In order to commit crimesthe gangster needs to collect burglary tools around the city (knives,detonators, etc.). Policemen work together to shoot the gangsterbefore he achieves his goal.

    Fig. 6 shows the gangsters as well as a policemans mobiledevice at the time the gangster has burgled the local casino. Thegangster knows the locations with larger amounts of money (banks,

    http://www.youtube.com/playlist?list=PL71615F77073CD26C&feature=plcphttp://www.lamosca.be/en/the-target

  • of Sys

    taa

    cpthorspcu

    6

    mTtlcs

    tcsdtmtW

    dHtbtstttEoiBtat

    vpwt(ascgm

    any user which is already part of a drawing session. When a userjoins a drawing session, he can add, remove or move shapes onthe canvas of that session which is virtually shared between theE. Gonzalez Boix et al. / The Journal

    o each other in order to coordinate their movements. The gangsternd policemen are frequently informed of each others positionsnd can shoot at each other.Flikken epitomizes MANET applications that react to context

    hanges in the environment. Examples of such changes includelayers location, appearance and disappearance of players, andhe discovery of virtual objects while moving about. Moreover,ow to react to these changes highly depends on the receiversf the contextual information. For example, virtual objectsepresenting burglary tools should only be perceived by the gang-ter when he is close their location while they should not beerceived by policemen at all. In what follows, we describe theoordination and interaction between policemen and the gangstersing tuples.

    .1.1. Design and implementationEvery player has a TOTAM system. Once the game starts, police-

    en and gangster communicate by means of the TOTAM network.hroughout the city various context providers (i.e., TOTAM sys-ems) are placed playing the role of virtual objects or crimeocations by broadcasting the necessary tuples. A special type ofontext provider is at the headquarters (HQ) of the players whichignals the start of the chase.

    In this section, we only describe the set of tuples coordinatinghe core functionality which counts 11 tuples (6 of which carry austom context rule, and 2 a custom lease) and 7 reactions. Table 3hows an overview of the tuples used in the game. The tuples areivided into five categories depending on the entity that injectshem in the environment, i.e., all players, only gangster, only police-en, headquarters and city context providers. A tuple is denoted by

    he term and the first element of a tuple indicates its type name.e use capitals for constant values.The TOTAM system on each players device is identified by a

    escriptor including its username and the team that he belongs to.owever, since there is communication between policemen andhe gangster, tuples injected by players are not scoped on a teamasis. We make use of context rules to control the perception of cer-ain tuples when necessary (e.g., to make sure the gangster does notee certain tuples). In contrast, all tuples injected by the TOTAM sys-em at the headquarters are scoped on a team basis using the playeruple space descriptor. The players TOTAM system carries a privateuple (TeamInfo, uid, gip) indicating which team he belongs to.very player injects his location to the TOTAM network by meansf the tuple (PlayerInfo, uid, gip, location). This tuple is injectednto the tuple space with a custom lease as we will explain later.oth the PlayerInfo and TeamInfo tuples are often used in otheruples context rules to identify the current whereabouts of a playernd his team. For example, the tuple representing a grenade useshese tuples as follows:

    totam.inject: (tuple: [VirtualObject, grenade, location]);

    inContext: [tuple: [TeamInfo, ?u, GANGSTER],

    tuple: [PlayerInfo, ?u, GANGSTER], ?loc],

    inRange(location, ?loc)]

    The tuple (VirtualObject, grenade, location) should be onlyisable if the receiver is a gangster whose location is physicallyroximate to the virtual object. The inRange function checkshether the gangster location (given by ?loc in the PlayerInfo

    uple) is in euclidian distance with the location of the grenadestored in location). Upon removal of a VirtualObject tuple,

    private tuple (OwnsVirtualObject, object) is inserted in his tuple

    pace. CommitCrime tuples notify the gangster of a crime thatan be committed. As crimes can only be committed when theangster has certain burgling items, the context rule of the Com-itCrime tuple requires that certain OwnsVirtualObject tuplestems and Software 92 (2014) 319 11

    are present in the tuple space. For example, in order for thegangster to perceive the CommitCrime tuple for the grand-Casino, a (OwnsVirtualObject,grenade) tuple is needed as shownbelow.

    totam.inject: tuple(CommitCrime, grandCasino, location, reward)

    inContext: [tuple: [TeamInfo, ?u, GANGSTER],

    tuple: [PlayerInfo, ?u, GANGSTER, ?loc],

    inRange(location, ?loc),

    tuple(OwnsVirtualObject,grenade)];

    Note that since context rules can be developed separately,this enables programers to reuse rules to build different kinds oftuples, increasing reusability. As shown above, we have reused theinRange function to build both the rule for the different Virtu-alObject tuples and CommitCrime tuples. Decomposing a tupleinto content and context rule also leads to separation of concerns,increasing modularity.

    Each player also registers several reactions to (1) update hisGUI (e.g., to show the OwnsVirtualObject tuples collected), and(2) inject new tuples in response to the perceived ones. Forexample, when a gangster commits a crime, he injects a tuple(CrimeCommitted, name,location,reward) to notify policemen.The code below shows the reaction on PlayerInfo tuples installedby the application.

    def playerinfoTemplate:=

    tuple: [PlayerInfo, ?uid, ?tid, ?location];

    totam.whenever: playerinfoTemplate read: {GUI.displayPlayerPosition(tid, uid, location);

    } outOfContext: {def matchingPlayerinfoTemplate:=

    tuple: [PlayerInfo, uid, tid, ?loc];

    def tuple:= totam.rdp(matchingPlayerinfoTemplate);

    if: (nil == tuple) then: { GUI.showOffline(uid) };};

    Whenever a PlayerInfo tuple is read, the player updates hisGUI with the new location of that player. As PlayerInfo tuplesare injected with a custom lease, they are automatically removedfrom the tuple space after their time interval elapses triggering theoutOfContext: handler. In particular, opposing team membersreceive the players location with a lease of 6 minutes, and police-men share their location with a lease of 1 minute. In the example,the outOfContext: handler grays out the GUI representation of aplayer if no other PlayerInfo tuple for that player is in the TOTAMsystem. If the rdp operation does not return a tuple, the player isconsidered to be offline as he did not transmit his coordinates fora while.

    Note how the integration of context into reactions avoids hav-ing to write imperative code for inferring tuple perception. Theunderlying rule engine takes care of it, making the code easier tounderstand and maintain.

    6.2. WeScribble

    WeScribble is a collaborative drawing application that allowsusers to dynamically participate in a drawing session with otherpeople nearby.8 The application assumes no other infrastructurethan mobile devices and wireless ad hoc connections betweenthese devices. Users can join a drawing sessions by contacting8 A demo of the weScribble application is available at http://www.youtube.com/watch?v=k0HYqRCxtHc.

    http://www.youtube.com/watch?v=k0HYqRCxtHchttp://www.youtube.com/watch?v=k0HYqRCxtHc

  • 12 E. Gonzalez Boix et al. / The Journal of Systems and Software 92 (2014) 319

    Table 3Overview of the tuples used in Flikken.

    Tuple content Tuple context rule/lease Tuple description

    All players(TeamInfo, uid, gip) [true] Private tuple denoting the players team.(PlayerInfo, uid, gip, location) [(TeamInfo, ?u, ?team), ?team /=

    gip]/[6 min]Injected to opposite team members every 6 minutes to notifythe position of a player. Location is a 2-tuple indicating the(GPS) coordinates of the player.

    (OwnsVirtualObject, GUN, bullets) [true] Private tuple inserted by players when they pick up their gunat their HQ.

    Only the Gangster(CrimeCommitted, name,location,reward) [(TeamInfo, ?u, POLICEMAN)] Notifies policemen that the gangster committed a crime.(OwnsVirtualObject, type, properties) [true] Private tuple inserted when the gangster picks up a virtual

    object in the game area.

    Only policemen(PlayerInfo, uid, gip, location) [(TeamInfo, ?u, gip)]/[1 min] Notifies the position of a policemen to his colleagues every

    time he moves.

    Headquarters(InHeadquarters, location) [(PlayerInfo,?u,?team,?loc),

    inRange(location, ?loc)]Notifies that the player entered his HQ. Used to start the chase(when this tuple moves out of context for the gangsters HQ)and to reload policemens guns.

    (CrimeTarget, name, location) [true] Notifies the gangster of the position of crime targets.(CommitCrime,name, location,reward,vobj) [(PlayerInfo,?u, GANGSTER,?loc),

    inRange(location,?loc),hasVirtualObjects(vobj)]

    Notifies the gangster of the possibility of committing a crime.hasVirtualObjects takes an array of virtual object ids andchecks that the gangster has the requiredOwnsVirtualObject tuples.

    City Context Providers(VirtualObject, id, location) [(TeamInfo, ?u, GANGSTER),

    (PlayerInfo,?u, GANGSTER,?loc),inRange(location, ?loc)]

    Notifies the gangster of the nearby presence of a virtual object.inRange is a helper function to check that two locations are ineuclidian distance.

    (RechargeableVirtualObject,GUN, BULLETS) [(InHeadQuarters,?loc),(OwnsWeaponVO,GUN,?bullets),?bullets < BULLETS]

    Represents the players gun. The gangster gets only one chargeat the start of the game, while policemens guns are rechargedeach time they go back to their HQ.

    ddpums

    6

    srssca

    Fig. 7. weScribble drawing session over four Android devices.

    ifferent participants. Fig. 7 shows a screenshot of a weScribblerawing session running on Android mobile devices. We will call aarticipant in a drawing session a drawer. In its extended version,sers can draw several kind of shapes (e.g. rectangle, square, line),ove them in the canvas, and change their color. Users can alsoelect one or more shapes and group them in a grouped shape.

    .2.1. Design and implementationThe application (supporting rectangle, circles and lines as

    hapes) consists of 12 types of tuples, 10 read reactions and 2 in:eactions. The basic idea is that the canvas is represented by a tuple

    pace where devices can read and post Shape tuples representinghapes being drawn. The main challenges in the design of the appli-ation is to detect nearby drawers, the disconnection of drawers,nd updates on group shapes.Since TOTAM follows a replicated-based tuple space approach,it is important to avoid that drawers receive outdated tuples fromother drawers whose devices are not nearby, i.e., devices currentlynot connected to the TOTAM network. To this end, the applicationtuple space descriptor makes use of a drawing session id. When auser creates a drawing session, it places a tuple representing thesession id, which can be read by all users. Users joining a sessionfirst need to read a DrawingSession tuple and then update theirtuple space descriptor so that they only share Shape tuples for thatsession. This application showed the importance of providing sup-port for changing the tuple space descriptor dynamically which isfor example not necessary for the Flikken application. We will fur-ther discuss the implication of changing tuple space descriptors inSection 8.

    To ensure that players have access to the shapes that he wouldlike to modify created by other players, the application employs anin reactions on the shape tuple it needs to modify. If the tuple isnot returned, it means that the drawer who first created the shapehas disconnected so the selection of the shape does not succeed.If the tuple is returned, it means that the drawer is allowed tomodify the shape and it becomes temporary owner of the shape.In order to detect disconnection of drawers, each drawer injecteda Drawer tuple in the network with a lease of 30 seconds. If theDrawer tuple out of context listener was triggered and a morerecent Drawer tuple is not present in the tuple space, the drawer isconsidered to be disconnected, and its shapes gets grayed out in theGUI.

    In order for a drawer to create a group shape, the differentshapes forming the group should be accessible so that they can bebundled together into one group shape. For this reason, the imple-

    mentation injects a GroupShape tuple whose context rule specifiesthe presence in the tuple space of the individual shapes, and regis-ter a read reaction on the GroupShape tuple so that the shapes can

  • E. Gonzalez Boix et al. / The Journal of Sys

    bidtoGtesf

    6

    ccsaoatmn

    aorwDtaaf

    Fig. 8. Photos of a deployed bus.

    e merged and the GUI is notified. The use of such a context rules critical to deal with consistency issues. Note that when a newrawer joins the drawing session, it receives the individual Shapeuples and the GroupShape tuple in its tuple space. However, therder in which those tuples are read is nondeterministic, so if theroupShape tuple is read before any of the individual Shape tuples,he application will try to merge unavailable Shape tuples. Bymploying a context rule on the GroupShape tuple, developers areure that only when all the shapes are available the group will beormed.

    .3. Industrial case study

    TOTAM has been used to prototype a urban bulletin appli-ation in collaboration with the STIB, Brussels public transportompany. The application works like the bulletin boards that oneometimes sees at the exit of supermarkets with messages suchs Im looking for a housekeeper, but integrated in a small partf the Brussels public transportation system. Passengers can usen Android device to post messages on the bus and read messageshat were posted by previous passengers. Crossing buses exchangeessages such that they get percolated through the transportationetwork.Our experiments were conducted in May 2011 in a MIVB depot

    nd included 3 buses which were equipped with customizednboard computers. Fig. 8 shows a photo of the setup. Each bus car-ies a onboard computer (Pentium M-compatible with 1GB RAM)ith a 802.11a interface attached to the computer which providesHCP connections. Each bus also has a GPRS modem attached to

    he computer. The onboard computer runs Linux Debian 5.0 and

    dedicated AmbientTalk distribution. This modified AmbientTalkbles simultaneous connections to two different network inter-aces. This was required in order to enable both customer-to-bustems and Software 92 (2014) 319 13

    transfers and bus-to-bus transfers. Passengers were equipped withstock Android devices; we employed Google Nexus S, HTC Desire,and HTC Sensation phones running Android 4.0.

    Each passenger and bus carry a TOTAM tuple space representingthe bulletin board. Using an unoptimized TOTAM and AmbientTalkinterpreter, customer-to-bus tuple transfer took up till 3 s. Con-nections between the onboard wifi antenna and smartphone arestable until the distance between the smartphone and the bus isincreased to 60 m. Such a distance causes significant packet lossor even disconnections, strongly degrading the QoS. A demo of thecustomer-to-vehicle mobile bulletin board application is availableat http://www.youtube.com/watch?v=N7mxaPftod4.

    7. Software engineering analysis

    The goal of this section is to highlight how TOTAM features aidthe development of context-aware applications running on mobilead hoc networks from a software engineering point of view.

    7.1. Context representation

    One of the main benefits of TOTAM is that it provides a formof context representation in which a tuple itself can determine theruntime conditions in which a receiving application should be inorder to perceive the tuple. By introducing a rule engine into thetuple space system, the underlying system takes care of makingaccessible context information only when it is valid for the applica-tions context situation. A tuple space model with such abstractionshas the following benefits:

    1. Decomposing a tuple into content and context rule leads to sep-aration of concerns, increasing modularity.

    2. Since context rules can be developed separately, it enables pro-gramers to reuse the rules to build different kinds of tuples,increasing reusability. For example, in Flikken, we used ainRangeOfGangster(?loc) function to build the rule for thedifferent VirtualObject tuples which was also reused to buildthe three first conditions of CommitCrime tuples.

    3. Programmers do not need to add computational code to infertuple perception as the rule engine takes care of it in an efficientway, making the code easier to understand and maintain.

    7.2. Dealing with partial failures

    Another benefit of TOTAM is providing a tuple space model thatdeals with the effects of partial failures inherent to a mobile ad hocnetwork setting. By default, applications are not aware of the inter-mittent disconnections of other TOTAM systems in the networksince the model abstracts the configuration of the network. Whena higher degree of context-awareness is required, tuples can con-tain context rules describing the runtime conditions under whichthe tuples should be visible in the receiving tuple space. In orderto deal with permanent disconnections, programmers can injecttuples with a lease which determines how long the tuple shouldremain in the tuple space.

    Encoding leases as part of a tuples propagation protocol relievesprogrammers of manually encoding when a tuple should expirein the propagation protocol itself. Doing so is challenging becausetuples are replicated amongst the network and developers need totake into account clock synchronization. Keeping clocks synchro-nised is a well known problem in distributed systems (Tanenbaum

    and Steen, 2001), but this issue is exacerbated in a highly dis-connected environment since the system cannot provide strongguarantees about the expiration time. In other words, it could bethat some copy of a tuple is still unrightfully active in the system,

    http://www.youtube.com/watch?v=N7mxaPftod4

  • 14 E. Gonzalez Boix et al. / The Journal of Systems and Software 92 (2014) 319

    xTuple Spac e

    Descriptor

    Tuple send

    Descriptor send

    1

    4

    3

    2

    Totam T1

    Traditional approaches T1

    Totam T2

    1

    4

    3

    2

    Traditional approaches T2

    Totam T3

    Traditional approaches T3

    1

    4

    3

    2

    1

    4

    3

    2

    1

    4

    3

    2

    1

    4

    3

    2

    f best

    cmemtrotre

    8

    ispppestst

    wtpbaeooi

    8

    tssamaafa

    in contrast to approaches where the tuples are not scoped, in thesecases the number of exchanged tuples for one round is quadraticto the number of locations participating in the ring.Fig. 9. Set-up o

    ausing the tuple to be perceivable by applications. The developerust then add boilerplate code to ascertain whether the tuple isxpired or not. Because we encoded leases into the tuple spaceodel, the system takes care of the issues of clock synchroniza-

    ion. At worst, the asynchrony causes a tuple to be subject to aead operation. However, the tuple will not be available for inperations because for a in operation to succeed the owner ofhe tuple has to be contacted. When contacting the owner, theequesting tuple space will be informed that the leases tuple isxpired.

    . Evaluation

    To complete the above software engineering analysis, it is alsomportant to analyze the effectiveness of TOTAM from a distributedystem point of view. By making use of tuple space descriptors,rogrammers can scope their tuples preventing them to be trans-orted to unwanted locations. These descriptors are crucial torovide programmers with a hook to encode privacy strategies. Forxample, although the descriptors in the Flikken are limited to beimple objects carrying the team identifier, this can be extendedo compute an encryption challenge. By avoiding the unneces-ary tuple transportation, our approach can minimize networkraffic.

    Tuple space descriptors are exchanged between two locationshen they meet for the first time and whenever a location decides

    o change its description. In case descriptors stay constant andrevent the propagation of tuples they can drastically reduce theurden on the network. In the other case when descriptors change

    lot or do not prevent the transportation of tuples the dangerxists that the network traffic gets dominated by the transmissionf descriptors. In the remainder section, we evaluate when the usef tuple space descriptors is beneficial and in which cases it is notn terms of network traffic.

    .1. Worst case

    In the worst case there is one message that has to be transportedo all connected locations. This means that the exchange of the tuplepace descriptors is an overhead as the tuple was unlimited in itscope, i.e., the tuple floods the network. The network traffic gener-ted for this tuple to be sent over the network when two locationseet can be computed as follows. Every location x connecting to location y will first receive the descriptor Dy over the networknd then receive the tuple tx1. The total amount of network trafficor this tuple can thus be computed by summing the exchange ofll descriptors with the total amount of exchanged tuples. This is case scenario.

    shown in the following equation where n represents the numberof connected locations.

    NetworkTraffic =(

    nx=0

    ny=0

    Dy

    )+ n tx1 (1)

    In case the descriptors do not change they will only be trans-ported once when two locations discover each other. This meansthat from the second communicated tuple the cost of the descriptoris dropped in the above equation. The resulting equation is exactlythe traffic that is normally transferred (n Tx1) when not making useof tuple space descriptors. However in the worst case all connectedlocations change their descriptors for every transmitted tuple. Inthis case the overhead of transferring the descriptors is given by thefollowing equation where N is the number of transferred tuples.

    NetworkOverhead =(

    nx=0

    ny=0

    Dy

    ) N (2)

    The overhead of exchanging the descriptors will be quadratic tothe number of connected locations over time. This clearly showsthat when descriptors change a lot and tuples have to be sent toall connected locations encountered it is not beneficial to use tuplespace descriptors.

    8.2. Best case

    In the best meaningful case9 the sent tuples are sculpted to beonly sent to one location and the tuple space descriptors do notchange over time. We illustrate this case by a tuple that hops fromlocation to location in a ring. In every hop the tuple adjusts its scopeto the next hop in the ring configuration. We have illustrated thenetwork traffic generated by this scenario for TOTAM and tradi-tional approaches in Fig. 9. It is important to split up the networktraffic generated by TOTAM in the case for the first tuple and thesuccessive ones. As can be observed on the top left of the figure,before sending the first tuple over the ring all descriptors have tobe exchanged. However, when this tuple is further propagated overthe ring exchanging the descriptors is not necessary anymore so thenumber of exchanged tuples for one round equals the size of thering (as shown in the second and third step of the figure). This is9 The theoretical best case is when the tuple is meant for nobody and thus doesnot generate network traffic at all.

  • E. Gonzalez Boix et al. / The Journal of Sys

    8

    iditttTsosptg

    itFwstsuovtAbt

    sTstp

    8

    s

    Listing 3. TOTAM ring descriptor.

    .3. Benchmarks

    We now report on micro-benchmarks of our TOTAM prototypemplementation. In order to validate whether the use of tuple spaceescriptors helps the programmer to decrease the network trafficn his applications we have benchmarked two implementation ofhe ring example shown in the previous section. A first implemen-ation makes use of a tuple space descriptor that corresponds withhe number of the node in the ring where the tuple is jumping to.he relevant code of the protocol that implements this protocol ishown in Listing 3. The second implementation does not make usef tuple space descriptors and thus corresponds to traditional tuplepace based approaches. Therefore, the tuple is sent to each of thearticipants where it is stored in the memory of the receiving par-icipant. As argued in the previous section such an implementationenerates a considerable amount of network traffic.In our tests, first a ring of ten nodes is created, then a single tuple

    s inserted that jumps from node n in the ring to node n + 1. Theime in function of the number of hops the tuple jumps is shown inig. 10. The results depicted were obtained on an Intel Core 2 Duoith a processor speed of 2.53 GHz running Mac OS X (10.8.3). Ashown in this figure, the implementation with tuple space descrip-ors is significantly faster than the implementation without tuplepace descriptors. The figure shows that the overhead of not makingse of tuple space descriptors becoming visible after only a couplef hops. The main reason why the overhead becomes noticeableery fast, is that not only the network traffic is significantly higher,he processing time for matching tuples is also significantly higher.ll the received tuples of the nodes in the ring are processed oney one and while propagating nodes in the network all the tupleshat do not match still need to matched against the event handlers.

    In conclusion, our benchmarks confirm that the TOTAM tuplepace implementation can significantly reduce the network traffic.his results in a more responsive system, for twenty hops a 5 timepeedup was measured. Moreover, as there are less tuples receivedhe individual nodes in the network have less processing work toerform..4. Summary

    The use of tuple space descriptors in combination withcoped tuples has the potential to drastically reduce the network

    Fig. 10. Benchmark comparison of tuple propagation in a ring structure.tems and Software 92 (2014) 319 15

    traffic when (1) the tuples will be prevented from hopping toother locations and (2) the descriptors do not change often rela-tive to the number of tuples in the system. However, how often dothe descriptors change is highly application-dependent. For exam-ple, in Flikken, tuple descriptors do not change over time becauseplayers were not allowed to switch teams. In Guanotes, the tupledescriptor changes when the end-user updates its user profile. Asfuture work, we would like to conduct experiments with devices tomeasure the costs of changing tuple space descriptors for differentapplications as well as for different propagation strategies.

    9. Prior work

    As mentioned in the introduction, the TOTAM system describedin this paper is an updated version of the tuple space system withthe same name presented in previous work (Scholliers et al., 2009,2010). In this section, we highlight how the designed of the updatedTOTAM defers from its predecessor.

    In the first version of TOTAM, not all tuple space operationswere designed to be non-blocking. However, from other previouswork (Dedecker et al., 2006), we have found that a loosely-coupledcommunication model mitigates the effects of the hardware char-acteristics inherent to mobile ad hoc networks. As such, TOTAMsupdated version was re-designed from the ground up not to supportblocking operations.

    In addition, tuples were merely wrappers on objects rather thanfirst-class values. As a result, the design of tuples did not pre-serve encapsulation and the code for the propagation protocol wasinterwoven with the content of the tuple, hindering the reuse ofprotocols for other tuples and applications.

    Finally, the presented TOTAM proposes a redesigned propa-gation protocol API solving two main limitations that the initialAPI suffered from. First, the inScope operation did not includethe descriptor of both the sender and receiver tuple space. Thisforced developers to manually update changes on the senderdescriptor when a tuple arrived to a tuple space by misusing doAc-tion operation. Second, the first propagation API did not allow tochange the tuple content before being sent and received in a tuplespace.

    10. Related work

    In this section, we discuss related work with regard to thevarious concepts integrated in TOTAM, namely its support forcontext-awareness, its scoping mechanism and leasing model.Finally, we compare our approach to publish/subscribe middlewarewhich is closely related to tuple space model as it provides similardecoupling properties (Eugster et al., 2003).

    Context-awareness. We now discuss related tuple space sys-tems modeled for context-awareness and show how context-awaretuples differ from them. In TOTA, tuples themselves decide how toreplicate from node to node in the network. Because tuples canexecute code when they arrive at a node, they can be exploited toachieve context-awareness in an adaptive way. However, program-ming such tuples has proven to be difficult (Mamei and Zambonelli,2004). TOTA, therefore, provides several basic tuple propagationstrategies. None of these propagation strategies addresses the tupleperception problems tackled by our approach. Writing context-aware tuples in TOTA would require a considerable programmingeffort to react on the presence of an arbitrary combination of tuplesas it only allows reactions on a single tuple.GeoLinda (Pauty et al., 2007) augments federated tuple spaceswith a geometrical read operation read(s,p). Every tuple hasan associated shape and the rd operation only matches thosetuples whose shape intersects the addressing shape s. GeoLinda

  • 1 of Sys

    htnappMtp

    cSatttto

    fdcSat

    iSfAbvuotmdiif

    wlnitoiptfi

    fiotspswots

    tfi

    6 E. Gonzalez Boix et al. / The Journal

    as been designed to overcome the shortcomings of federateduple spaces for a small subset of potential context information,amely the physical location of devices. As such, it does not offer

    general solution for context-aware applications. In contrast, weropose a general solution based on context rules, which allowsrogrammers to write application-specific rules for their tuples.oreover, in GeoLinda the collocation of devices still plays a cen-

    ral role for tuple perception which can lead to erroneous contexterception.EgoSpaces provides the concept of a view, a declarative specifi-

    ation of a subset of the ambient tuples which should be perceived.uch views are defined by the receiver of tuples while in context-ware tuples it is the other way around. Context-aware tuples allowhe sender of a tuple to attach a context rule dictating the sys-em in which state the receiver should be in order to perceive theuple. EgoSpaces suffers from the same limitations as federateduple spaces since, at any given time, the available data dependsn connectivity (Julien and Roman, 2004).The Fact Space Model (Mostinckx et al., 2007) is a LIME-like

    ederated tuple space model that provides applications with aistributed knowledge base containing logic facts shared amongollocated devices. Unlike context-aware tuples, rules in the Factpace Model are not exchanged between collocated devices andre not bound to facts to limit the perception of context informa-ion.

    Scoping mechanisms. A number of approaches support scop-ng mechanisms in the context of tuple spaces. Coordination withcopes (Merrick and Wood, 2000) introduces the concepts of scopeor a tuple space. A scope represents a view on a flat tuple space.

    set of operations is defined on those views allowing scopes toe joined, nested, intersected and subtracted. Tuples may thus beisible from several different scopes. This mechanism is mainlysed to structure tuple spaces according to different viewpointsn a flat tuple space. However, scopes do not limit the propaga-ion of tuples, i.e., tuples are propagated to other tuple spaces butay not be visible for certain scopes. Since the system was notevised for mobile computing applications, they rely on a central-zed infrastructure. In contrast, TOTAM does not rely on any fixednfrastructure and tuples can be propagated through spontaneouslyormed MANETs.

    CAMA (Iliasov, 2006) is an agent-based tuple space systemhich allows the definition of a scope which agents can join and

    eave. Scopes are defined as containers in a tuple space and can beested in order to form hierarchical structures. This notion of scopemproves on coordination with scopes since inserted tuples are onlyransmitted to agents which reside in the same scope. However, inrder to send tuples to other scopes the agent first needs to changets scope. Tuples which are inserted in a specific scope can not beropagated automatically to other scopes. In TOTAM, by allowinghe tuple itself to decide whether it should be propagated, morene-grained sharing strategies can be expressed.L2imbo (Davies et al., 1998) is a tuple-space based platform

    or mobile computing which provides special features for qual-ty of service. Similar to CAMA, L2imbo introduces the conceptf multiple tuple spaces but suffers from the same limitations asuples do not have the ability to decide to which tuple space theyhould be propagated. It is interesting to note that L2imbo sup-orts time-outs associated with tuples. This makes possible for theystem to reorder tuples to make optimal use of the available net-ork connectivity. Similar to CAMA, L2imbo introduces the conceptf multiple tuple spaces but suffers from the same limitations asuples do not have the ability to change to which tuple space they

    hould be propagated.

    Evolving tuples (Stovall and Julien, 2007) have a field destina-ion that they can change while they are hopping. This destinationeld is used to determine where the tuple will be transmitted totems and Software 92 (2014) 319

    after leaving a host. However, the destination field can only bea broadcast address or a specific host address. In order to sendthe tuple to two broadcast addresses the programmer will haveto read the tuple and reinsert it to another broadcast address.Our approach uses semantic information to determine where itcan be transmitted thus allowing more fine-grained propagationrules.

    Inspired by LIME, TeenyLIME (Costa et al., 2006) introducesabstractions specially designed for wireless sensor networks(WSN). Every tuple space in TeenyLIME is shared only with one-hopneighbours, limiting the scope of tuples to one hop. Such limitationfits natural with WSN architectures where every node typicallyneeds access to nearby information (Costa et al., 2006). Scopingwas introduced to address the scarce resources issue in the contextof WSN. However, no other means are provided to express differ-ent propagation protocols, which need to be expressed in terms ofsingle-hop operations.

    Leasing models. Garbage collection of unused tuples is a knownproblem in tuple space approaches (Mamei and Zambonelli, 2009).Typically, a tuple space stores tuples which may never be subject toa remove operation, and which may never be garbage collected. Tosolve this problem, TOTAM employs the notion of leasing. Some tra-ditional tuple space approaches such as Objective Linda (Kielmann,1996), JavaSpaces (Freeman et al., 1999) and TSpaces (Wyckoffet al., 1998), augmented Lindas operations with a timeout: if amatching tuple is not found within the timeout, the operationreturns an error. In JavaSpaces and TSpaces, a tuple can be insertedin the tuple with a lease time denoting the maximum amount oftime before the tuple is automatically removed from the tuplespace. However, the centralized nature of those approaches doesnot make them applicable in a mobile environment. To the bestof our knowledge, Tiamat (McSorley and Evans, 2003) is the onlytuple space model for the mobile environment that includes a leas-ing model. Tiamat follows a federated tuple space model in whicheach operation is leased. Interestingly, the authors describe that inTiamat leases may be based on time or on other measures suchas the number of remote instances contacted. Unfortunately, nocode examples are provided to see how programmers can declareleases based on such conditions. Tiamat leasing model incorpo-rates the concept of expiration in the tuple space operations, butit does not provide listeners which allows application to react tothem.

    Mamei and Zambonelli (2009) remark the importance of incor-porating a garbage collection mechanism to TOTA to removeunused tuples. In TOTA, one can encode a leased tuple such as theone described in our work by means of a custom propagation rule.In particular, the propagation rule needs to update its content totake into account the notion of time, and stop its propagation. TheMessageTuple class described in the latest version of TOTA (Mameiand Zambonelli, 2009) defines a tuple that floods the network anddeletes itself after some time has passed. In TOTAM, because leas-ing is orthogonal to the propagation protocol, programmers donot need to manually encode in the propagation rule the passageof time, nor the retraction of the tuple from the network upon adelete operation.

    Omicini et al. (2005) extend ReSpecT (Denti et al., 1998), logic-based tuple space language with the notion of time. ReSpecT tuplecenters behave like tuple spaces whose behaviour is specified interms of reactions to events occurring in the tuple space. The notionof time is introduced into a tuple center with (1) some temporalpredicates to get information about tuple center and event time,and (2) timed reactions which specify reactions triggered by time

    events. Based on this extension, they discuss how some abstrac-tions that could be built by introducing leasing into tuples similarto what TOTAM supports. An interesting topic of future work wouldbe to investigate whether introducing leasing in TOTAM along the

  • of Sys

    pcs

    pbJ2antwtbrgebo

    acoanaooar

    scercist2

    1

    Aemspotslda

    toenb

    h

    E. Gonzalez Boix et al. / The Journal

    rinciples of (timed) tuple centers will allow us to build time-basedoordination patterns in a more modular way than our currentolution based on propagation protocols.

    Publish/subscribe systems. Many researchers have proposedublish/subscribe as a suitable communication model for MANETsecause of its loosely coupled nature (Meier, 2002; Cugola andacobsen, 2002; Eugster et al., 2003; Huang and Garcia-Molina,004). Publish/subscribe middleware typically does not offerbstractions for representing failures or reacting to network con-ectivity. In fact, communicating parties are usually not aware ofhe underlying network configuration, or even if a published eventas received by any subscriber; either failures are transparent

    o publishers and subscribers and the event notification serviceuffers events when subscribers disconnect, or the publishers areesponsible themselves for encoding failure handling and eventset lost if subscribers move out of communication range. Forxample, STEAM (Meier and Cahill, 2003) allows publish/subscribeased on physically location, but it is hard to describe scopes basedn semantic information as shown in the ambient game.With respect to our support for context-awareness, context-

    ware publish subscribe (CAPS) (Frey and Roman, 2007) is thelosest work as it allows certain events to be filtered dependingn the context of the receiver. More concretely, the publisher canssociate an event with a context of relevance. However, CAPS is sig-ificantly different from context-aware tuples. First, CAPS does notllow reactions on the removal of events, i.e., there is no dedicatedperation to react when an event moves out of context. More-ver, it does not provide coordination of distributed parties, i.e.,tomic removal of events is not supported. And last, the context ofelevance is always associated to a physical space.

    Some publish subscribe systems have explored the concept ofcope for events. In scoped REBECA (Ludger et al., 2002) systemsan create a scope in which events will be published. A scope can bextended and therefore form a tree of scopes. Subscribers will onlyeceive events of publishers which are in the same scope or have aommon ancestor in the scope hierarchy. Similar to CAMA, publish-ng an event in an other scope requires the publisher to change itcope first, forcing developers to manually reinsert the tuples intohe other scopes. Location-based publish/subscribe (Eugster et al.,005) suffers from the same limitation.

    1. Availability

    As previously mentioned, TOTAM has been implemented inmbientTalk, and its implementation is shipped with Ambi-ntTalks standard language library.10 In order to use the TOTAMiddleware, developers need to import the TOTAM module acces-ible via the lo