Programming Abstractions in Wireless Sensor Networks Professor Jack Stankovic Department of Computer...

Post on 11-Jan-2016

222 views 3 download

Tags:

Transcript of Programming Abstractions in Wireless Sensor Networks Professor Jack Stankovic Department of Computer...

Programming Abstractionsin

Wireless Sensor Networks

Professor Jack StankovicDepartment of Computer

ScienceUniversity of Virginia

ImportanceImportance

• Raise the level of abstraction• Move out of the domain of HW and

embedded systems programmer• Amplify the applications addressed –

programmed by domain experts• More reliable

• One of the most important areas of research to make WSN widely used

ContextContext

System DevelopmentEnvironment

Analysis/Tools

Use of SystemSQL/Queries

Actual Programming

Programming ModelsProgramming Models

• Environmental (domain specific, tracking, monitoring, …)– EnviroSuite

• Data/Database Centric - Queries– SQL, TinyBD, Cougar– Statistical and range queries

• Middleware APIs and Services– Group Management, Token machine language

(Regiment), Milan (QoS based), Agilla– Support for other models

• Components• Database• Event • Agent

Programming ModelsProgramming Models

• Components– nesC

• Virtual Machines– Mate

• Functional Macro-programming– Regiment (regions, streams)

• (Mobile) Scripts– SensorWare

• Extend TCL interpreter with support for commands such as query, send, wait, replicate, …

• Provides execution environment for Scripts

• Events– Publish/subscribe– DSWare, SNEDL, Impala

Programming ModelsProgramming Models

• Model Driven• Swarm computing• Java• Linux

Program What?Program What?

• Low level protocols (MAC, routing, …)

• Middleware services• Application• Use of system

– Queries

Blurs

Sensor/Actuator/CommunicationSensor/Actuator/Communication

HeterogeneousHomogeneous

Resource management, team formation, networking, aggregation, …

Severe constraints power, memory, bandwidth, cpu, cost, ...

ReliabilityReliability

• Make an unreliable platform reliable!!

• HW (motes) are/will be very reliable

• Environment/wireless communication will not be reliable

AbstractionsAbstractions

• Program as a whole – not individual nodes

• Hide details (which ones, expose what)– Single node decisions– Asynchrony– Race conditions– False alarms– Retries– Physical details (e.g., location, sensor characteristics,

…)– Faults– Scale– Storage locations

Other QuestionsOther Questions

• How to disseminate programs– Flooding, viral programs, gossip

protocols

• Efficient on small, embedded, real-time devices

• Long-lived systems – Disseminate again– Disseminate pieces of executable

Environmental Paradigm

Environmental Paradigm

• Current Paradigms– Single node abstractions– Explicit interactions between nodes– Read sensor data; fuse data; move data– Set actuators

• Environmental Paradigm– Reflect the physical world directly– Virtual world of entities (fire, people, vehicles,

pesticide, velocity, location, areas, …)

EnviroSuiteEnviroSuite

• Way to think– Events – measurable environmental activities– Events mapped to programming objects– Computation is attached to these objects

• Report location, compute velocity, …

• Library provides protocols for sensor data processing, object maintenance, inter-object coordination, aggregation mechanisms, etc.

personevent

Base Station

vehicleevent

object type: VEHICLE object ID: vehicle01

method:report location to thebase station every 5seconds

attribute: location

object type: PERSON object ID: person01

method:turn on a nearby micro-phone if current locationis less than 1 mile awayfrom the base station

attribute: location

mapping

EnviroSuite

EnviroSuiteEnviroSuite

event-object VEHICLE { object_creation_condition = ferrous object && background sound object_resolution = 6; // minimal distance between // two events object_function = report.Location; object_function = report.Speed;}

ferrous object && background sound

This statement is supported by drivers in a library:

Level of Knowledge Required

Level of Knowledge Required

• Ferrous object– Which signal processing module?– What parameter specifications need to

be made?

– We are programming in an application that interacts with the environment – how divorced from that fact can the programmer be?

Routing Protocol - SPEEDRouting Protocol - SPEED

E2E Di stance

j

FS

iD

Actual Speed

Speed todestination(Set Point )

E2E Delay is bound by E2E Distance/Speed SetPoint

USES VELOCITY

Expose Velocity

Radio Irregularity Radio Irregularity

DOI = Degree of Irregularity

DOI = 0.05 DOI = 0.2

Do NotExpose

Data/Database CentricData/Database Centric

• Query Processing Architectures (SQL-based)– Process the queries– Route the queries– Retrieve information efficiently (in time and

with low energy costs)

• Storage Architectures– How/where to store collected data from

sensors– In-network storage

• At local node• Data centric – name the data and hash to a location• Multi-resolution (hierarchies)

Example of QueryExample of Query

• Retrieve, every 30 seconds, the rainfall level if it is greater than 50 mm

SELECT R.Sensor.getRainfallLevel()FROM RFSensors RWHERE R.Sensor.getRainfallLevel() > 50AND $every(30);

Many other extensions to query capabilityincluding statistical and range based queries

Content Dissemination - Caching

Content Dissemination - Caching

Information source(Aperiodic updates)

Data replicas(Placement?)

Receivers(Refresh Rate,Accuracy)

Goal: Find the optimal communication path to send sensory data from a monitored source to multiple (mobile) sinks such that energy usage is minimized.

Middleware APIsMiddleware APIs

• Group Management– Create– Terminate– Merge– Join/Leave– Assign function

• Track target• Classify target• Map temperature region

– Consensus

Group ManagementGroup Management

IR Camera

Group ManagementGroup Management

IR Camera

Examples: Tracking and

Map Regions

Examples: Tracking and

Map Regions

Base Station

Group Management - APIGroup Management - API

– Create_Group(name,function,criterion,atleast,accuracy) - implicit and explicit

– Destroy_Group(name)– Join()– Leave()– Merge()– Move_COG()– Expand() -- to gain sensing confidence– Shrink() -- to save power– Commit(grp_ID) - to synchronize group re-

configurations

Other ServicesOther Services

• Naming• Directory• Location• Monitor• Configure• …

QuestionQuestion

• How general/specific should a middleware service be?

Function of severity of resource constraints

Severe

Careful interoperabilityExactly what is needed and no more!

ExcessCapacity

More general servicesUseable by many

Functional Macro-Programming (Regiment)

Functional Macro-Programming (Regiment)

• Apply function to data from a stream• Aggregate samples from a stream• Filter stream• Define/Disseminate Events from a

area (region)

AreaBaseStationAbstract

Regions

Streams

Regiment (cont.)Regiment (cont.)

• Set frequency• Fidelity• Contour finding• Combine regions• Anchors (leaders for a region)

• Functional Language

RegimentRegiment

• Abstractions– Streams, Spaces, Events, Anchors

(leader for a region), When (time)– Regions – group of nodes with some

relationship to each other• Like the function for a group in previous

middleware slides• Ex. – all nodes within k radio hops of node N• Ex. – all nodes whose proximity sensor

records a hit

Token Machine Language (TML)Token Machine Language (TML)

• Kind of middleware to support Regiment PL

• Regiment– Compiler transforms a macro-program

written in functional style into an efficient nodal program based on a token machine

– Token machine is an intermediate language (target) for Regiment

TMLTML

NODE

Token Handlers –Atomic Tasks

Token from Network

Name of Token HandlerDataGenerate

Tokens

Components - nesCComponents - nesC

• Underlying execution model (TinyOS)– Tasks and Events– Split phase operation

• Modules– Component Specification – Interfaces– Component Implementation

• Configurations– Wiring Diagrams

Tasks and EventsTasks and Events

• Tasks– Deferred computation– Non-preemptable by other tasks– Scheduled FCFS from task queue

• Events– Execution of an interrupt handler– Runs to completion– Can preempt tasks and can be

preempted by other events

Application ExampleApplication Example

RFM

Radio byte

i2c

Tempphoto

Messaging Layer

clocksbit

byte

packet Radio Packet

Routing Layer

sensing applicationapplication

HW

SW

ADC

messaging

routing

UART Packet

UART byte

Components - nesCComponents - nesC

• The nesC model:– Interfaces:

• uses• provides

– Components:• modules• configurations

• Application:= graph of components

Component A

Component B

ComponentD

Component C

Application

configurationconfigurationComponent

E

ComponentF

EnviroTrack on top ofnesC

InterfacesInterfaces

• Examples of interfaces:

interface StdControl { command result_t init (); command result_t start (); command result_t stop ();}

interface Timer { command result_t start (char type, uint32_t

interval); command result_t stop (); event result_t fired ();}

interface SendMsg { command result_t send (uint16_t

addr, uint8_t len, TOS_MsgPtr

p); event result_t sendDone ();}

interface ReceiveMsg { event TOS_MsgPtr receive (TOS_MsgPtr

m);}

StdControl.nc Timer.nc

ReceiveMsg.ncSendMsg.nc

ModulesModules

• Implements a component’s specification with C code:

module MyCompM { provides interface X; provides interface Y; uses interface Z;}implementation {…// C code}

MyCompM.nc

ModulesModules

• Posting Tasks:

module BlinkM {…}implementation {… task void processing () { if(state) call Leds.redOn(); else call Leds.redOff(); }

event result_t Timer.fired () { state = !state; post processing(); return SUCCESS; }…} BlinkM.nc

Configuration ExampleConfiguration Example

• Blink application• Wiring Example

configuration BlinkC { }

implementation { components Main, BlinkM, ClockC,

LedsC;

Main.StdControl->BlinkM.StdControl; BlinkM.Clock->ClockC; BlinkM.Leds->LedsC;}

ClockC LedsC

Main

BlinkC

BlinkM

BlinkC.nc

Future?Future?

• Different component models?

• nesC components are “low level” with a fair amount of syntax

• Envirosuite, Mate, etc. do build on top of nesC

Mate – Virtual Machine Mate – Virtual Machine

TinyOS

Mate VM(interprets)

24 Instruction ProgramsEach instructionexecutes as task(slow)

Code capsules

Code CapsulesCode Capsules

• One capsule = 24 instructions• Fits into single TOS packet

– Energy efficient

• Atomic reception• Code Capsule

– Type and version information– Types: send, receive, timer, subroutine

• Larger programs – use several capsules

ValueValue

• Re-programmability– Re-task a network

• Parameter adjustment

• Self-replication– One of the special instructions on the

VM is forward (which supports a viral-like infection of the entire network)

• Incremental addition of new nodes

Propagation ExamplePropagation Example

Node Enters the NetworkNode Enters the Network

Instruction SetInstruction Set

One byte per instruction Three classes: basic, s-type, x-type

•basic: arithmatic, halting, LED operation•s-type: messaging system•x-type: pushc, blez

8 instructions reserved for users to define Instruction polymorphism

•Example: add(data, message, sensing)

User Defined Instructions User Defined Instructions

TinyOS

Mate VM(interprets)

24 Instruction Programs

Code capsules InstructionsUnderstood byMate

User defined

1 2 3 4

1 3

3

1

- Sound alarm

- Write to flash

Mate ArchitectureMate Architecture

0 1 2 3

Subroutines

Clo

ck

Sen

d

Receiv

e

Events

gets/sets

0 1 2 3

Subroutines

Clo

ck

Sen

d

Receiv

e

Events

gets/sets

Co

de

OperandStack

ReturnStack

PC

Co

de

OperandStack

ReturnStack

PC

Stack based architecture Operand stack Return address stack

Three events/execution contexts:•Clock timer•Message reception•Message send

Code Example(1)Code Example(1)

• Display Counter to LEDgets # Push heap variable on stackpushc 1 # Push 1 on stackadd # Pop twice, add, push resultcopy # Copy top of stacksets # Pop, set heappushc 7 # Push 0x0007 onto stackand # Take bottom 3 bits of valueputled # Pop, set LEDs to bit patternhalt #

Code Example(2)Code Example(2)

• Sense and Sendpushc 1 # Light is sensor 1sense # Push light reading on stackpushm # Push message buffer on stackclear # Clear message bufferadd # Append reading to buffersend # Send message using built-inhalt # ad-hoc routing system

TinyOS Sense and Send

TinyOS Sense and Sendevent result_t Timer.fired() {

if (state == IDLE && call Photo.sense()) {state = SENSE;}return SUCCESS;

}event result_t Photo.dataReady(uint16_t data) {

if (state == SENSE) {packet->reading = data;if (call SendMsg.send(packet, sizeof(DataBuf)) {

state = SENDING;} else {state = IDLE;}

}return SUCCESS;

}event result_t SendMsg.sendDone(TOS_MsgPtr msg) {

if (state == SENDING) {state = IDLE;}return SUCCESS;

}

Component BreakdownComponent Breakdown

• 7286 bytes code, 603 bytes RAM

QuestionsQuestions

• What should a programmer see?– New language– New middleware– Services– Components– Abstracts models– All the above– None of the above

QuestionsQuestions

• What would have made your life easier in doing the programming assignments?

• What makes it easier to get the system to work?– Debugging tools

• Initially (in programming environment)• On real platform

IdeasIdeas

• Move code to node – executes on middleware, VM, interpreter

• Domain specific (good or bad?)• Regions/Streams• Expose/Hide?

– Performance– Physical systems

• Disseminate

SummarySummary

• Very active area– It must be

• Solutions can have large impact– Applications programmers rather than

system experts

• Standard?– Analogy to real-time computing and

programming languages?• WSN-Java?

Final QuestionFinal Question

• Will there be GP WSNs (and how might that affect the programming abstractions)?