2Topics Localization and Positioning Synchronization and Security IntroductionWhat are WSNs?An example: ESBWSN applicationsEnergy conservationAd-hoc routingBasic principlesOverview of routing protocolsData-centric protocolsRumor RoutingGeographical protocolsLocalization and PositioningSynchronization and SecurityThe TinyOS operating systemThe TinyDB query systemProto programming language
3Introduction: What are WSNs? Sensors, connected into wireless networks, are:Very small computer systemsWith very high interconnection ability
4Introduction: What are WSNs? 2 Overview of networking technologies
5Introduction: What are WSNs? 3 The idea of wireless sensor networks was first popularized by scientists from UC BerkeleyThey have developed:series of sensor nodes (so-called mica nodes)open-source softwareTinyOS operating systemTinyDB query system for efficient manipulation of sensed dataAn interesting fact:one of the first applications for small interconnected autonomous systems was in submarine warfareIntegrated Undersea Sound Survelliance System (IUSS)
6Introduction: What are WSNs? 4 Sensor network (def):a set of small autonomous systems (sensor nodes) working together to solve at least one common problemtheir tasks always include some way of perception of the physical environmentSensor nodes:basic units in a sensor networkthey are usually powered by batteries and they have some kind of a radio transceiverAlternative names:motes (most often)smart dust
7Architecture of a sensor node Block diagram of a typical sensor node (mote)
9WSN Applications Treatment of ill people: wearable computing under-skin implants – measurement of blood parameters, early detection of some illnessesalready marketed – capsules with 24 hours of battery life which move through the patient’s body and relay images to the doctor through another device worn externally by the patientEmbedded systems: home automationtemperature measurementalarm systemsTraffic – sensors in cars, early traffic congestion warningMilitary applicationsMany other; new applications are constantly devised.
10One application: Camalie Vineyards One mote in the vineyards: Crossbow mica2dot mote, NiMH batteries, solar panel, 3V voltage regulator. Source: .
11One application: Camalie Vineyards 2 The visitors of the Camalie Vineyards website can view graphs of ambient temperature (with respect to time) in all points where sensors are present. Slightly colder temperatures come from sensors in the wine cellar; dysfunctional motes report absolute zero. Source: .
12Topics Localization and Positioning Synchronization and Security IntroductionWhat are WSNs?An example: ESBWSN applicationsEnergy conservationAd-hoc routingBasic principlesOverview of routing protocolsData-centric protocolsRumor RoutingGeographical protocolsLocalization and PositioningSynchronization and SecurityThe TinyOS operating systemThe TinyDB query systemProto programming language
13Energy conservationCareful use of available energy is of paramount importance in WSNsBatteries, in most cases, cannot be recharged!Inefficient energy use shortens battery life considerably!Some of the methods for reduced energy consumption and prolonged battery life:Passive conservation methodsUse of sophisticated energy sourcesPlacement of sensors into energy efficient topologiesActive conservation methodsHardware solutions (watchdog timer, reduced clock frequency...)Energy aware routing protocols; energy efficient medium access (MAC layer)The choice of an energy-saving operating system
14Energy sources for motes Rechargeable macro-batteries as a secondary energy sourceMicro-batteries on a waferUltracapacitorsThey not only hold electrical charge in the dielectric,they also hold ionic charge in the double electrical layerEnergy density larger than in ordinary capacitors by an order of magnitudeMicro Fuel CellsMicroturbinesRadioactive power sourcesSolar cellsEnergy of the human bodyWearable computingHydrogen micro-fuel cell4mm micro turbineSource: 
15Energy conservation: hardware solutions Watchdog timersdeliberately turn the power down if the software is stuck in an infinite loopSleep statesVariable voltage processingDeliberate performance degradation by dropping the voltage and reducing the clock frequencyso the same task could be done with smaller energy consumption, at the expense of performance.Variable Voltage ProcessingSame task can be performed with smaller energy consumption if voltage and frequency are reduced (shaded area). Source: 
16MAC energy aware protocols Energy aware protocols are used at the MAC layer (energy efficient medium access).Basic principle:Energy required for signal transmission is proportional to d αd – distance between two nodesα – attenuation factor (medium dependent)
17MAC energy aware protocols 2 For optimum α = 2, transmitting a signal to ½ of distance requires ¼ of energy: (½ d)2 = ¼ d2→ If a protocol can find a node on ½ distance to target, which can supply additional ¼ of energy to transmit the signal through the remaining half, ½ of energy is saved!(½ d)2 + (½ d)2 = ¼ d2 + ¼ d2 = ½ d2
18Energy solutions in the ESB Microcontroller TI MSP340: energy consumption 3V, 1mA (3mW)total energy consumption is 12mA at 4.5 V, plus additional 12mA during data transmissionprogram memory: 8KB EEPROMonly 2KB of conventional RAM memory; 60KB Flash RAM for special purposes only (high energy consumption!)watchdog timer: uses an NMI interrupt to shut the node down immediately, if software gets stuck in an infinite loopsleep mod, consumes only mA (practically equivalent to battery self-discharge)Printed circuit of the ESB
19Topics Localization and Positioning Synchronization and Security IntroductionWhat are WSNs?An example: ESBWSN applicationsEnergy conservationAd-hoc routingBasic principlesOverview of routing protocolsData-centric protocolsRumor RoutingGeographical protocolsLocalization and PositioningSynchronization and SecurityThe TinyOS operating systemThe TinyDB query systemProto programming language
20Ad-hoc routingWireless networks: computer networks with wireless communication linksAd-hoc networks:in ad-hoc nets every node can forward packagesthe decision whether each node will or will not forward packages is made dynamically,with regard to current connectivity matrix.Comparison:in conventional computer networks, there are dedicated nodes (routers, switches, hubs...) which forward packages.Such approach is impossible in ad hoc networks – all nodes are constantly on the move, connectivity changes all the time so there are no good candidates for dedicated routers.
21Ad-hoc routingIn ad-hoc networks, individual nodes have no a priori knowledge of network topologywhen connected, they gradually discover other nodesBasic principle:a newly connected nodes advertises it’s presencereads broadcast messages from neighboring nodesIn this way, a node gradually discovers:the positions of other nodes in a network,ways to reach each one of them.
22Ad-hoc routingWhen enough time has passed, routing protocol convergence is established.When this happens, each node “knows” about all the other nodes in the net, and how to reach each one of them.Convergence time is total time elapsed from when the network topology is changed (for example, when a communication link goes down) to when all nodes have restructured their routing tables in accordance with the change.
23Ad-hoc routingConventional networks use data-centric routing: each node has an unique data identifier which serves as its address on the network (IP-address, MAC-address...)Some ad-hoc networks use different conceptsFor example, it might not be necessary for information to be routed from a specific starting point to a specific endpoint, but only to be propagated and diffused through the network. This is called Rumor Routing.Or, geographical coordinates could be used as means for addressing (Geographical Routing).
25Data-centric protocols 1 Proactive protocols:maintain consistent knowledge of network topology through routing tables which are exchanged between nodes periodicallyDrawbacks:network bandwidth is wasted: routing tables are an overhead which decreases available bandwidth for useful datasome paths are never used, and yet they are kept in the tablessimulations show very long convergence time some proactive protocols never converge in large wireless networks!Example:WRP – Wireless Routing Protocol
26Data-centric protocols 2 Reactive protocols:information about paths is not kept; a path is discovered on demand only, by flooding the network with Route Request packagesDrawbacks:on demand path discovery introduces significant delaysflooding the network can lead to severe network congestionExamples: can be found, in detail, in AODV – Ad-hoc On-demand Distance VectorDSR – Dynamic Source RoutingTORA – Temporally Oriented Routing Algorithm
27Data-centric protocols 3 Hybrid protocols:locally proactive, globally reactivee.g. ZRP – Zone Routing ProtocolThe network is divided into routing zonesthe zone is usually an sphere with a specified diameter, measured in hop countsthe nodes positioned at the maximum distance from central node X are called peripheral nodes for the routing zone centered at X.When package needs to be sent from node A to node B:if B is within the same routing zone as A, local routing table is looked up to find the path to B (proactive behaviour),if this is not the case, Route Request packages are sent to all peripheral nodeseach peripheral node repeats this step (checks whether the destination B is inside its routing zone).
28Data-centric protocols 4 ZRP example:A sphere centered at S: is a zone of radius ρ = 2J, G, H, I: peripheral nodesIf a package is sent from node S to node G:Destination is within the same zone, routing table is looked up.If a package is sent from node S to node T:Destination is in a different zone, Route Request packages are sent to nodes G, H, I, J.Node I discovers that T is within its routing zone (d = 2),It looks up its routing table, and sends the package to L.
29Rumor Routingfirst proposed by Braginsky and Estrin (UCLA) in their paper .All nodes are divided into two groups:nodes that perceive events,nodes which seek information about events, from the nodes of the preceding groupThere is no network topologyThere is no coordinate systemThe protocol doesn’t try to find an optimum route, it seeks only to relay the information end-to-endsub-optimum routes are satisfactory for this purpose
30Rumor Routing 2 Rumor Routing protocol: 1 Events A and B are perceived on some nodesAn agent is sent from both groups (A and B) to “spread rumors” about the whereabouts of possible sources of information for events A and BWhen agent B meets agent A on its way, it goes on to spread information about both events A and B11232Illustration of Rumor Routing protocol(Source: )
31Rumor Routing 3 1 Handling the information requests: A node requests information about event AIt’s request “moves blindly” through the network until it stumbles upon a node visited by the information spreading agent. While moving, it leaves traces so it can backtrack when information is found.When a node visited by the agent is found, a route is followed to the source of informationInformation is retrieved and brought back to the source of the request.243Illustration of Rumor Routing protocol(Source: )
32Geographical Protocols: An Overview Routing relies on geographical position information (as opposed to data centric routing)Destination for a package is a specific areae.g. a city, a section of a highway, or, at the micro level, a part of the conference roomrecipient cannot determine exactly who is the sender, it can only determine roughly from where the package came fromRouting decision are made with respect to real, spatial coordinatesFor that to be possible, positioning information is necessaryone way of obtaining position information is GPS (Global Positioning System)
33An example: GeoCast Proposed by Navas and Imielinski, 1997. Three-tiered architecture:GeoHosts are endpoints of the networkClient processes (applications) are run on themGeoHosts initiate message transferOn receipt of the package, they check if their geographical region is the destination of the package.GeoGateways are the network’s entry and exit pointsGeoHosts communicate with GeoRouters through broadcast messagesa GeoGateway is responsible for a given area specified by a radiusGeoRouters perform the actual routingthey are aware of the coordinates of neighboring GeoRouters and GeoGatewaysthey route the package through neighboring GeoRouters to the destination GeoGateway so that it can reach the destination geographical area.
35GeoCast routing 3 Source:  GeoCast communication: Client ProcessGeoCast communication:A node on Net A perceives the eventIt sends a message to its GeoGatewayGateway forwards the message to a neighboring GeoRouterRouting is performedAt some moment, destination Gateway is direct neighbor to a router; the router hands the message to destination Gateway.Destination Gateway delivers the message to Net B.EventGeoRouterGeoGatewayGeoHostDirect messageClient ProcessSource: 
36GeoCast routingWith classical IP networks, next hop address is determined by looking up a routing tableWith GeoCast, destination addresses are areas specified by necessary parametersif the area is a circle, location of center and length of radius are requiredif the area is a polygon, locations of all angles are requiredRouters are organized in a hierarchical mannerrouters responsible for smaller geographical areas are lower in the hierarchyrouters responsible for larger geographical areas are lower in the hierarchy
37GeoCast routingA client process, running on a GeoHost, delivers a message to its GeoRouter through its network’s GeoGatewayGeoRouter consults lower-level GeoRouters and determines:Is there any overlap between the zone of responsibility of the lower level router, and the destination area?If there is an overlap, the message is forwared to the lower-level GeoRouter.When this is repeated for all lower level routers, was the destination area covered completely?If it was, the procedure ends here.If it wasn’t, the message is unicast to a higher level router, responsible for wider geographical area, which repeats the procedure starting at 2.
38GeoCast routingIn order to implement the described procedure, another procedure is necessary, one that will determine if the two areas overlap.If the two areas are both circles, the procedure is simpleif the distance between centers is smaller than the sum of the radiuses, the circles indeed overlap
39GeoCast routingIf the two areas are a circle and a polygon, or they are both polygons, things get complicatedGeographical calculations of higher complexity are necessaryComparison with IP nets:In IP networks, a simple query on the routing table is all that is necessaryIn GeoCast networks, routing decision complexity is several orders of magnitude higher!
40Routing Protocols: A Conclusion Rough classification of protocols:Data-centric: an address is some kind of datum (e.g. an IP address – 4 bytes of data)Diffusion: it is not necessary to address individual nodes, only to diffuse the information through the networkGeographical: an address is a geographical area, described by geographical parametersMost uses for data centric protocols are outside of wireless sensor networksDiffusion protocols are simplebut they are suitable only for a small number of use casesGeographical protocols are conceptually most suitable for wireless sensor networksbut making a routing decision can be very complex
41Topics Localization and Positioning Synchronization and Security IntroductionWhat are WSNs?An example: ESBWSN applicationsEnergy conservationAd-hoc routingBasic principlesOverview of routing protocolsData-centric protocolsRumor RoutingGeographical protocolsLocalization and PositioningSynchronization and SecurityThe TinyOS operating systemThe TinyDB query systemProto programming language
42Localization and Positioning Measurements by sensor networks are substantially more valuable if the location of measurement is knownTherefore, a sensor has to be aware of its position in the real worldTwo approaches:LocalizationPositioningBCA
43Localization and Positioning 2 Localization: location of the sensor is given as relative to some local pointit is then possible to calculate distances and angles between individual nodesbut it is not possible to determine the sensor’s global positionPositioning: a sensor is given absolute coordinates on the world mape.g. coordinates can be longitude and latitude
44Localization and Positioning 3 The simplest solution to the problem of positioning is to put a GPS device in each sensor node.GPS receivers are still too expensive and too big!The remaining possibilities can be divided into 4 groups (picture).1 Some nodes know their position, and distances between nodes are known.2 No node knows its position, but distances between nodes are known.3 Some nodes know their position, but distances between nodes are not known.4 No node knows its position and distances between nodes are not known.
45Localization and Positioning 4 Global coordinates are available for the complete topology,Only local coordinates are known,It is possible only to roughly estimate the position of the whole system,Only the network’s connectivity matrix is available.1 Some nodes know their position, and distances between nodes are known.2 No node knows its position, but distances between nodes are known.3 Some nodes know their position, but distances between nodes are not known.4 No node knows its position and distances between nodes are not known.
46Localization and Positioning 5 Since only some nodes need to be aware of their position in order to establish positioning for the complete network,only some nodes need to be equipped with a GPS device,because of high energy consumption, GPS could be turned on only occasionally,in those intervals, remaining nodes perform localization with respect to the GPS-equipped nodes.Alternate solution: instead of equipping them with a GPS device, some nodes could have their position manually input by an operator (based on measurements from his GPS device).This solution is sometimes neither practical nor possible!For mobile networks, public positioning stations are usually used.
47PositioningPositioning of every node is possible in Case 1 from the tablethat is the case when positions of some nodes are known, and distances between nodes are known, too.Three already positioned nodes are enough to determine position of another nodeif the distances between nodes are known.one way of measuring distance is measuring the attenuation of the radio signalIf some of the 3 nodes is not positioned with sufficient precision, the error propagates quickly!
48Positioning (2D)pi, pj – already positioned nodesn – newly added nodeWe consider two spheres, with radiuses dn, i i dn, j, around their centers pi i pjThey intersect in two points: n i n’The final step in positioning is to choose one of these pointsIn order to do this, we need the third already positioned nodeMutual visibility is checked with the third node, in order to discount one of the points n i n’.In satellite positioning (3D) the final step is usually unnecessary;the object has to be on Earth’s surface→ points in space or below surface are instantly discarded
49LocalizationIn case no node is aware of it’s position, but distances between nodes are known, localization is the only possible approach.Capkun, Hamdi, Hubaux, “GPS-free Positioning in Mobile Ad-hoc Networks”Describes the procedure which establishes a global coordinate system (CS)based on measurements of distances between nodes
50LocalizationBasic procedure for establishment of a global coordinate system (CS), in a two-dimensional environment, is as follows:Each node searches for its immediate neighborsin this way, “immediate neighborhood”, consisting of all nodes one hop away, is formed.The distance table obtained in (1) is sent to all neighborsIn each node a local coordinate system is established, with that node in the centerFor each node n, two additional nodes p and q are chosen from the immediate neighborhood, in order to define x and y axesx-axis is a line drawn from the circle, through node p, oriented outwardsy-axis is always perpendicular to the x-axis, node q is necessary only to determine its orientation
51LocalizationIn each node, the remaining nodes’ positions are expressed in the local coordinate systemOne of the local coordinate systems is chosen (for example, CS of node i); origins of all other CS’s have their locations in the CS of node iFor each node j, j ≠ i:Axes are rotated so that they become parallel to axes of CS iCoordinates of the origin of CSj, with respect to CSi, are added to coordinates of all pointsd in CSj.In this way, all local coordinate systems are unified into a global coordinate system, in which node i holds the position (0,0).
52Localization and Positioning: Conclusion For the measurements to be truly useful, it is necessary to know the location of the measurement.When some of the nodes are aware of their global position, it is possible to establish positioning information for each node in the network.If there are no such nodes, it is still possible to construct a local coordinate system.
53Topics Localization and Positioning Synchronization and Security IntroductionWhat are WSNs?Primer čvora senzoraWSN applicationsEnergy conservationAd-hoc routingBasic principlesOverview of routing protocolsData-centric protocolsRumor RoutingGeographical protocolsLocalization and PositioningSynchronization and SecurityThe TinyOS operating systemThe TinyDB query systemProto programming language
54SynchronizationTime synchronization of events and activities is essential in all distributed systemsIn wireless sensor networks:even more precise synchronization is neededand it has to obtained with scarce critical resources (battery power, communication channel availability, etc.)Comparison with conventional distributed systems:each node can operate only as long as its batteries lasttherefore, clocks in all nodes cannot be maintained from a central place (so called master clock) as that node may run out of powereach use of the CPU and the communication medium comes with a great price in energytherefore, existing systems aren’t good enough!
55SynchronizationPossible distortions of measured time, as the clock propagates through the sensor network:Jitter: “podrhtavanje” časovnika usled nepreciznosti.Skew: the clock becomes faster or slower than normal (frequency distortion)Drift: measured time differs by a constant offset (phase distortion)this is a problem only if different nodes have different offsetsSource: 
56SynchronizationThere is no optimum solution with satisfies all criteria (preciseness, lifespan, availability)Different approaches are often combinedSome commonly applied solutions:Explicit synchronizationinstead of keeping all clocks in synch all the timeevents are recorded with respect to local timewhen needed, these time marks are converted to another scale on demand onlyPeer-to-peer synchronizationamount of synch related errors between two nodes is proportional to distance between themtherefore, keeping a centralized clock is not a good approachinstead, only neighboring nodes exchange synch related information
57Security Sensor networks usually consist of a large number of nodes To supervise each node is practically impossibleTherefore, sensor networks are:highly susceptible to logical and physical attacksand communication interceptiona node could be seized, reprogrammed, then put back into the networkby means of reverse engineering, nodes could be designed to trick the network into treating them as authenticVarious forms of abuse are then possibleintercepting confidential information (sensed data)falsifying sensor readingsDistributed Denial of Service (DDoS) attacks.
58SecurityTo protect every single node from reprogramming is economically unfeasibleOther approaches are used:node-to-node authentication: nodes in the network have to prove their identity to each othernode revocation: when an intruding node is discovered, it is forbidden to access the network any furtherApplied protocols have to be made resilientMeaning, the network has to be able to continue functioning properly, even if some nodes are compromised.
59Security 3 Privacy of sensed data is kept by encryption Conventional approach – large keysUnsuitable for sensor networks – because of limited memory!Commonly applied approach – hop-to-hop encryptionMessages are encrypted using short keys in every nodeDrawback: if one node in the chain is taken over, there is no more encryption for any messages passing through that nodeMultipath routingbefore it is sent, the message is broken into several chunksthese chunks move through the network using different routesthey are not reassembled until they reach the destination
60Security 4 DoS attacks – another threat through DDoS attacks, attackers can deliberately drain the batteriesphysical protection:spread spectrum communicationfrequency hoppinglogical protection: constantly checking and discarding messages with invalid authenticity informationdanger: in this way, the very protection from DDoS can drain the battery!because, power is constantly spent on authenticity checks for incoming messages
61SecurityEnergy cost of added security through authentification: as much as 71% extra energy cost is due to increased amount of transmission!
62Synchronization and Security: Conclusion These are the problems also present in conventional networksHowever, because of different architecture, many traditional approaches are not suitableSolutions for sensor networks have to be designed with respect to the specific architecture of sensor nodesmost of all, the scarcity of energy resources
63Topics Localization and Positioning Synchronization and Security IntroductionWhat are WSNs?Primer čvora senzoraWSN applicationsEnergy conservationAd-hoc routingBasic principlesOverview of routing protocolsData-centric protocolsRumor RoutingGeographical protocolsLocalization and PositioningSynchronization and SecurityThe TinyOS operating systemThe TinyDB query systemProto programming language
64TinyOSBecause of the specific architecture of sensor networks, a suitable operating system had to be devisedConventional OSes for embedded systemsVxWorksWindows CEPalmOSQNXThey all require ROM of 100KB or more!The ESB, introduced in Chapter 1, has only 8 KB ROM!Because of this, TinyOS was developed.
65Characteristics of TinyOS Event-driven programmingconventional context switching is impossible, there is no room for the stack!a system of components is used instead; each component has its own static area in memory (“frame”)in this way, the need for stack is eliminatedprograms are executed only in response to the eventsevents are registered by components beforehandEnergy conservationInterrupt polling is forbidden: if the CPU constantly checks the status register, battery power is continuously expendedInterrupt masking is forbidden, too: node which requests the interrupt would spend power while it waits
66TinyOS Architecture TinyOS has: Each component advertises: a short-term task schedulercomponents, which usually have:command handling routines (command handlers)event handling routines (event handlers)a fixed amount of allocated memory (frame)a few simple tasksEach component advertises:which commands it can handle,which events it can report.All tasks, commands, and event handler routines are executed only within the allocated memory frame
67TinyOS ArchitectureMemory frames are allocated statically at compile timeCommands are issued by higher level components, to lower level componentsthey place parameters on pre-defined locations within the memory framethey deposit tasks for later executionat some moment, they provide feedback to the caller componentEvent handling routines:respond to hardware eventswrite information to the memory framedeposit tasks for later executionsignal events to higher level componentsissue commands to lower level components
68TinyOS Architecture 3 Tasks: perform the actual workwith respect to other tasks, they are atomiconce started, they cannot be interrupted by other taskshigher level events, however, can interrupt them (pre-emption)issue commands to lower level componentssignal events to higher level componentsdeposit new tasks to their componentShort-term scheduler: a simple FIFO buffer
69TinyOS: An example Component A message transfer componentSends and receives individual packages to/from the lower levelSends and receives whole messages to/from the higher levelAs all components, it sends commands to the lower level:an initialization command: init,power management command: power(mode)It recieves the same components from the higher level
70TinyOS: An example Component 2 It also sends the transfer initiation command: TX_packet (buf)It responds to following events (from lower level):package is transmitted TX_packet_done (success)package is received RX_packet_done (buffer)It signals the following events (to higher level):message is transmitted msg_send_done (success)message is received msg_rec (type, data)
71TinyOS: An example Component 3 This code is used to declare the message transfer component
72TinyOS: An example Component 4 An illustration of the amount of occupied memory in a typical sensor node:Our component, AM, takes up 356 bytes of ROM and 40 bytes of RAMIn the list of components, we can also see the components which provide for hardware abstractionFor example, RFM represents the built-in RFM transcieverA fully functional sensor node needs only 3450 bytes of ROM and 226 bytes of RAM!
73Topics Localization and Positioning Synchronization and Security IntroductionWhat are WSNs?Primer čvora senzoraWSN applicationsEnergy conservationAd-hoc routingBasic principlesOverview of routing protocolsData-centric protocolsRumor RoutingGeographical protocolsLocalization and PositioningSynchronization and SecurityThe TinyOS operating systemThe TinyDB query systemProto programming language
74TinyDBA query processing system, which gathers information from sensor nodes which have TinyOS installedIt uses a declarative programming language, TinySQLQueries are always performed on a unique, default, logic table: sensorsThe sensors table has:one row, for each measurement performed by any sensor node;one column, for each relevant attribute of the measurement: nodeID, temp, state, ...It is bundled together with TinyOS as a component which is installed on every mote in the net
75TinyDBTinySQL is very similar to standard SQL, but there are some very important conceptual differencesIt also has aggregate functions and triggersA query, once input, is performed repeatedlyperforming frequency is input through the epoch parameterit has to be chosen carefully, having in mind the limited battery capacityQueries can be input:visually, through an application bundled with TinyOSthrough coding, in a language very similar to SQL
76TinyDB 3 Basic form of the query: An example: SELECT select-list[FROM sensors]WHERE where-clause[GROUP BY gb-list[HAVING having-list]][TRIGGER ACTION cmd-name[(param)]][EPOCH DURATION integer]An example:SELECT tempFROM sensorsWHERE temp > threshTRIGGER ACTION SetSnd(512)EPOCH DURATION 512If temperature higher than specified threshold is found on any sensor, a beep 512ms long is sounded, and the query is performed again after 512ms.
77TinyDB 4 Queries can be performed in response to external events, too for example: an event which signals that the temperature has risen above some thresholdTwo procedures are necessary:Writing a component which detects the event and notifies TinyDB that it has indeed happenedA query in TinyDB of the form: on event: SELECT...
78TinyDBExample:ON evtTest:SELECT nodeid,lightSAMPLE PERIOD 1024In response to event evtTest, sensed light data is collected every 1 second.
79Topics Localization and Positioning Synchronization and Security IntroductionWhat are WSNs?Primer čvora senzoraWSN applicationsEnergy conservationAd-hoc routingBasic principlesOverview of routing protocolsData-centric protocolsRumor RoutingGeographical protocolsLocalization and PositioningSynchronization and SecurityThe TinyOS operating systemThe TinyDB query systemProto programming language
80Proto programming language Proto: a high-level programming language used to program sensor and actuator networksProposed by Jonathan Bachrach and Jacob Bealfrom the Massachusetts’ Institute of Technology Computer Science and Artificial Intelligence laboratory (MIT-CSAIL)Paper: “Programming sensor networks as an amorphous medium” 
81Proto programming language 2 The goals of the Proto language:to relieve the programmer from worrying about the physical aspects of sensor network programmingthe exact way of providing fast, efficient and robust communication between nodes is below the barrier of abstractioninstead, the programmer writes declarative code, such asIf the temperature is high, (sensor measurement)Then, the field should be watered, every few hours (a command to actuators)
82Proto programming language 3 In order to accomplish this,the sensor network is imagined as an amorphous mediumContinuous field of calculable materialSensed data in each sensor node is a point in the fieldDimensions and physical distribution of the points is not knownEach point in the amorphous field:executes the same codeadvertises its state to the immediate neighborhoodApproximation of an amorphous medium
83Proto programming language 4 Proto programs manipulate over fieldsOne field is a mapping scheme which assigns some value to a set of points in space
84Proto programming language 5 Primitives in Proto can be:terminalsoperatorscommon arithmetic operators, in prefix notationif operatorspecial primitivesmuxsense and actlet and def
85Proto programming language 6 Primitives can be combined into complex expressionsBesides the individual fields, field streams can be also usedWhen evaluating expressions with field streams, the result has to be calculated separately for each field from the streamTherefore, the result is a field stream, too
86Proto programming language 7 Terminals correspond to constants and they generate fieldsFor example, the terminal 2 generates a field with value 2 in every pointOperators calculate the output field using a set of input fieldsfor example, the expression generates a field with value 7 in every pointthe if operator has standard meaning
87Proto programming language 8 mux uses a selector field of booleans in order to generate a field in which for every point, one of two possible values is chosen: the value from the corresponding point in field #1, or, the value from the corresponding point in field #2.this is performed for each point separately, with respect to the boolean value in the corresponding point in the selector field.
88Proto programming language 9 sense and act represent the sensor readings and actuator commands, respectively.They are analogous to, for example, read and write procedures in PascalIn this way, Proto programs communicate with their environment.let assigns a value to a variableE.g. (let x 3)def defines a procedure (a macro)E.g. (def sq(x) (* x x))
89Proto examplesExample (a): terminal 2 generates a field which has value 2 in every point (“2”)Example (b): we add up the field “2” with field stream (“1”, “3”) the result is a field stream (“3”, “5”)
90Proto examplesExample (c): input parameters are fields “2”, “3” and field stream (“false”, “true”)As the selector is a field stream and not a field, the result will be a field stream tooOne field from the result field stream corresponds to selector field “false”: that is field “3”selector has semantics “do we choose the first field?”, and as it is false, we choose the 2ndSecond field corresponds to “true”; that is field “2”
91Proto examples 3 Example (d): a complex operation Firstly, terminals 2 and 5 generate fields “2” and “5”Secondly, as a result of add operation the result field “7” is generated.
92Proto examplesExample (e): definition of a procedure we define sq(x) as x*xExample (f): terminal 3 generates field “3” as a result of a sq call, field “9” is generatedProto code: (def sq(x) (* x x)) sq(3)
93Proto examplesan input and output example: input – light is perceived output – a signalization light is emitted
94Proto examplesthe following code turns the red light emitter on each sensor where any light is perceived
95nbrs (x): neighborhood of point x Proto: reduce-nbrsProto also has primitives which enable it to describe behavior which depends not only on a single point in space (single sensor), but it’s immediate neighborhood, tooThe neighborhood of a single point is an infinite number of pointsAmorphous medium – continuous space!nbrs (x): neighborhood of point x
96Proto: reduce-nbrsThe reduce-nbrs primitive summarizes the neighborhood of a single pointusing some quantificator applicable to infinite setsProto has five such quantificators:integralforallexistslimsup equivalent to max, for infinite setsliminf equivalent to min, for infinite sets
97Proto: reduce-nbrsIn this way, implicit communication between points is establishedBy aggregating the values in neighborhood of x, the points from the neighborhood communicate their value to xReal-life communication has a delayProto simulates this delay using primitives delay and letfed
98An example Proto application the Threat Avoidance problemIf we have:current coordinates,a means for perceiving the danger (threat sensor)a model of exponentially falling dangerhow can we calculate the safest route?Implementation in the nesC language (standard procedure language for sensor networks) ~ 2000 lines of codeImplementation in Proto: only 22 lines of code
99An example Proto application 2 In order to test the threat avoidance program, a model is requiredSo, we describe a model with exponentially falling danger:
100An example Proto application 3 Now, with regard to our current location, we can calculate the cumulative probability of survival
101An example Proto application 4 Greedy-ascent procedure: in every point, the direction for next move is chosen in which the threat is best avoided
102An example Proto application 5 By combining all these procedures, a complete solution for threat avoidance is obtained
103An example Proto application 6 The results obtained when the threat avoidance program is run on a simulatorFor more information, please consult  and .
104References Thomas Hänselmann, Sensor Networks,  Jason Hill et al., System Architecture Directions for Networked Sensors, Department of EE/CS, UC Berkeley  Sam Madden, Joe Hellerstein, Wei Hong, TinyDB: In-Network Query Processing with TinyOS, UC Berkeley,  David Braginsky, Deborah Estrin, Rumor Routing in Sensor Networks, LECS-UCLA  Joe Polastre, Rachel Rubin, GeoMote: Geographical Network Architecture for Sensor Networks, CS Berkeley  Jeremy Elson, Time Synchronization in Wireless Sensor Networks, UCLA,  Jonathan Bachrach, Jacob Beal, Programming a Sensor Network as an Amorphous Medium, MIT-CSAIL,  Haowen Chan, Adrian Perrig, Security and Privacy in Sensor Networks, Carnegie Mellon University,  Jacob Beal, Continuous Semantics of Proto, MIT-CSAIL, 2006.
105References Đ. Trifunović, N.Milanović, V.Milutinović, Ad-hoc Networks: Estabilishing node-to-node communication with no infrastructure needed,  en.wikipedia.org, USA,  USA,  M. Ilyas, I. Mahgoub (ed.), Handbook of Sensor Networks: Compact Wireless and Wired Sensing Systems, CRC Press,  I. Stojmenović (ed.), Handbook of Sensor Networks: Algorithms and Architectures, Wiley, 2004.