tinyos 2.1 tutorial at ipsn 2009

184
TinyOS 2.1 IPSN 2009 Stephen Dawson-Haggerty, Omprakash Gnawali, David Gay, Philip Levis, Răzvan Musăloiu-E., Kevin Klues, and John Regehr San Francisco, CA - April 16, 2009

Upload: gnawali

Post on 13-Dec-2014

7.170 views

Category:

Technology


4 download

DESCRIPTION

TinyOS tutorial at IPSN 2009

TRANSCRIPT

Page 1: TinyOS 2.1 tutorial at IPSN 2009

TinyOS 2.1IPSN 2009

Stephen Dawson-Haggerty, Omprakash Gnawali, David Gay, Philip Levis, Răzvan Musăloiu-E.,

Kevin Klues, and John Regehr

San Francisco, CA - April 16, 2009

Page 2: TinyOS 2.1 tutorial at IPSN 2009

2

Agenda

• 8:33: Overview (Om)• 8:40: Basics (Phil and David)• 9:30: TOSSIM (Razvan)• 9:45: Safe TinyOS (John)• 10:00: Threads (Kevin)• 10:15: break• 10:20: Protocols (Om)• 10:40: Upcoming (Stephen)• 10:50: Hands-on (Razvan, Om, et al.)• 11:30: End

Page 3: TinyOS 2.1 tutorial at IPSN 2009

3

What?

• An operating system for low power, embedded, wireless devices– Wireless sensor networks (WSNs)– Sensor-actuator networks– Embedded robotics

• Open source, open developer community

• http://www.tinyos.net

Page 4: TinyOS 2.1 tutorial at IPSN 2009

4

Who are we?

• Some principal developers and designers– Stephen Dawson-Haggerty: network protocols– David Gay: language design– Omprakash Gnawali: network protocols– Kevin Klues: core system– Philip Levis: core system– Răzvan Musăloiu-E.: network protocols– John Regehr: compilation tools

• There are many contributors besides us, they all deserve credit

Page 5: TinyOS 2.1 tutorial at IPSN 2009

5

Why?

• TinyOS is very powerful – Modern operating system and language

techniques in an embedded system– A lot of libraries, support code, and community

development

• TinyOS has a steep learning curve– It can take time to use all of its capabilities

• Give a jump-start on high level concepts and how to write applications

Page 6: TinyOS 2.1 tutorial at IPSN 2009

6

Goals

• Give you a high-level understanding of TinyOS’s structure and ideas

• Explain how to build and install applications

• Survey important libraries – Focus on very recent additions

• Give you the experience of writing a networked sensing application

Page 7: TinyOS 2.1 tutorial at IPSN 2009

7

Schedule

• 8:33: Overview (Om)• 8:40: Basics (Phil and David)• 9:30: TOSSIM (Razvan)• 9:45: Safe TinyOS (John)• 10:00: Threads (Kevin)• 10:15: break• 10:20: Protocols (Om)• 10:40: Upcoming (Stephen)• 10:50: Hands-on (Razvan, Om, et al.)• 11:30: End

Page 8: TinyOS 2.1 tutorial at IPSN 2009

BasicsPhilip Levis (Stanford)

David Gay (Intel Research)

8

Page 9: TinyOS 2.1 tutorial at IPSN 2009

9

Outline

• Components and interfaces– Basic example

• Tasks– More complex example

• Compiling and toolchain

Page 10: TinyOS 2.1 tutorial at IPSN 2009

10

TinyOS Components

• TinyOS and its applications are in nesC– C dialect with extra features

• Basic unit of nesC code is a component

• Components connect via interfaces– Connections called “wiring”

BAi

Page 11: TinyOS 2.1 tutorial at IPSN 2009

11

Components

• A component is a file (names must match)

• Modules are components that have variables and executable code

• Configurations are components that wire other components together

Page 12: TinyOS 2.1 tutorial at IPSN 2009

12

Component Example

• BlinkC wires BlinkP.Timer to TimerC.Timer

module BlinkP { … }implementation { int c; void increment() {c++;}}

configuration BlinkC { … }implementation { components new TimerC(); components BlinkC;

BlinkC.Timer -> TimerC;}

TimerCBlinkPTimer

Page 13: TinyOS 2.1 tutorial at IPSN 2009

13

Singletons and Generics

• Singleton components are unique: they exist in a global namespace

• Generics are instantiated: each instantiation is a new, independent copy

configuration BlinkC { … }implementation { components new TimerC(); components BlinkC;

BlinkC.Timer -> TimerC;}

Page 14: TinyOS 2.1 tutorial at IPSN 2009

14

Interfaces

• Collections of related functions

• Define how components connect

• Interfaces are bi-directional: for A->B– Commands are from A to B– Events are from B to A

• Can have parameters (types)interface Timer<tag> { command void startOneShot(uint32_t period); command void startPeriodic(uint32_t period); event void fired();}

Page 15: TinyOS 2.1 tutorial at IPSN 2009

15

Outline

• Components and interfaces– Basic example

• Tasks– More complex example

• Compiling and toolchain

Page 16: TinyOS 2.1 tutorial at IPSN 2009

16

Basic Example

• Goal: write an anti-theft device. Let’s start simple.

• Two parts:– Detecting theft.

• Assume: thieves put the motes in their pockets.• So, a “dark” mote is a stolen mote.• Every N ms check if light sensor is below some threshold

– Reporting theft.• Assume: bright flashing lights deter thieves.• Theft reporting algorithm: light the red LED for a little while!

• What we’ll see– Basic components, interfaces, wiring– Essential system interfaces for startup, timing, sensor

sampling

Page 17: TinyOS 2.1 tutorial at IPSN 2009

17

The Basics – Let’s Get Started

module AntiTheftC { uses interface Boot; uses interface Timer<TMilli> as Check; uses interface Read<uint16_t>;}implementation { event void Boot.booted() { call Check.startPeriodic(1000); } event void Check.fired() { call Read.read(); } event void Read.readDone(error_t ok, uint16_t val) { if (ok == SUCCESS && val < 200) theftLed(); }}

interface Boot { /* Signaled when OS booted */ event void booted();}

interface Timer<tag> { command void startOneShot(uint32_t period); command void startPeriodic(uint32_t period); event void fired();}

Components start with a signature specifying• the interfaces provided by the component• the interfaces used by the component

A module is a component implemented in C• with functions implementing commands

and events• and extensions to call commands, events

Page 18: TinyOS 2.1 tutorial at IPSN 2009

18

The Basics – Split-Phase Ops

module AntiTheftC { uses interface Boot; uses interface Timer<TMilli> as Check; uses interface Read<uint16_t>;}implementation { event void Boot.booted() { call Check.startPeriodic(1000); } event void Check.fired() { call Read.read(); } event void Read.readDone(error_t ok, uint16_t val) { if (ok == SUCCESS && val < 200) theftLed(); }}

In TinyOS, all long-running operations are split-phase:• A command starts the op: read• An event signals op completion: readDone

interface Read<val_t> { command error_t read(); event void readDone(error_t ok, val_t val);}

Page 19: TinyOS 2.1 tutorial at IPSN 2009

19

The Basics – Split-Phase Ops

module AntiTheftC { uses interface Boot; uses interface Timer<TMilli> as Check; uses interface Read<uint16_t>;}implementation { event void Boot.booted() { call Check.startPeriodic(1000); } event void Check.fired() { call Read.read(); } event void Read.readDone(error_t ok, uint16_t val) { if (ok == SUCCESS && val < 200) theftLed(); }}

In TinyOS, all long-running operations are split-phase:• A command starts the op: read• An event signals op completion: readDoneErrors are signalled using the error_t type, typically• Commands only allow one outstanding request• Events report any problems occurring in the op

interface Read<val_t> { command error_t read(); event void readDone(error_t ok, val_t val);}

Page 20: TinyOS 2.1 tutorial at IPSN 2009

20

The Basics – Configurations

configuration AntiTheftAppC { }implementation{ components AntiTheftC, MainC, LedsC;

AntiTheftC.Boot -> MainC.Boot; AntiTheftC.Leds -> LedsC;

components new TimerMilliC() as MyTimer; AntiTheftC.Check -> MyTimer;

components new PhotoC(); AntiTheftC.Read -> PhotoC;}

A configuration is a component built out of other components.It wires “used” to “provided” interfaces.It can instantiate generic componentsIt can itself provide and use interfaces

generic configuration TimerMilliC() { provides interface Timer<TMilli>;}implementation { ... }generic configuration PhotoC() {

provides interface Read;}implementation { ... }

Page 21: TinyOS 2.1 tutorial at IPSN 2009

21

Components

Page 22: TinyOS 2.1 tutorial at IPSN 2009

22

Outline

• Components and interfaces– Basic example

• Tasks and concurrency– More complex example

• Compiling and toolchain

Page 23: TinyOS 2.1 tutorial at IPSN 2009

23

Tasks

• TinyOS has a single stack: long-running computation can reduce responsiveness

• Tasks: mechanism to defer computation– Tells TinyOS “do this later”

• Tasks run to completion– TinyOS scheduler runs them one by one in the

order they post– Keep them short!

• Interrupts run on stack, can post tasks

Page 24: TinyOS 2.1 tutorial at IPSN 2009

24

Outline

• Components and interfaces– Basic example

• Tasks and concurrency– More complex example

• Compiling and toolchain

Page 25: TinyOS 2.1 tutorial at IPSN 2009

25

More Complex Application

• Let’s improve our anti-theft device. A clever thief could still steal our motes by keeping a light shining on them!– But the thief still needs to pick up a mote to steal it.– Theft Detection Algorithm 2: Every N ms, sample

acceleration at 100Hz and check if variance above some threshold

• What we’ll see– (Relatively) high frequency sampling support– Use of tasks to defer computation-intensive activities– TinyOS execution model

Page 26: TinyOS 2.1 tutorial at IPSN 2009

26

Advanced Sensing, Tasksuses interface ReadStream;uint16_t accelSamples[ACCEL_SAMPLES];event void Timer.fired() { call ReadStream.postBuffer(accelSamples, ACCEL_SAMPLES); call ReadStream.read(10000);}

event void ReadStream.readDone(error_t ok, uint32_t actualPeriod) { if (ok == SUCCESS) post checkAcceleration();}

task void checkAcceleration() { ... check acceleration and report theft...}

ReadStream is an interface for periodic sampling of a sensor into one or more buffers.• postBuffer adds one or more buffers for sampling• read starts the sampling operation• readDone is signalled when the last buffer is full

interface ReadStream<val_t> { command error_t postBuffer(val_t* buf, uint16_t count); command error_t read(uint32_t period); event void readDone(error_t ok, uint32_t actualPeriod);}

Page 27: TinyOS 2.1 tutorial at IPSN 2009

27

Advanced Sensing, Tasks

uint16_t accelSamples[SAMPLES];event void ReadStream.readDone(error_t ok, uint32_t actualPeriod) { if (ok == SUCCESS) post checkAcceleration();}task void checkAcceleration() { uint16_t i, avg, var;

for (avg = 0, i = 0; i < SAMPLES; i++) avg += accelSamples[i]; avg /= SAMPLES;

for (var = 0, i = 0; i < SAMPLES; i++) { int16_t diff = accelSamples[i] - avg; var += diff * diff; } if (var > 4 * SAMPLES) theftLed();}

In readDone, we need to compute the variance of the sample. We defer this “computationally-intensive” operation to a separate task, using post.We then compute the variance and report theft.

Page 28: TinyOS 2.1 tutorial at IPSN 2009

28

TinyOS Execution Model

RealMainP

AccelStreamC

AntiTheftC RealMainP

Stack

Task QueueTimer

Alarm

SchedulerP

Interrupt table

AntiTheftC

Timer

Alarm

serialreceive H/W timer A/D conv.

Page 29: TinyOS 2.1 tutorial at IPSN 2009

29

TinyOS Execution ModelStack

Task Queue

serialreceive H/W timer A/D conv. Interrupt table

timer task

RealMainP

AccelStreamC

AntiTheftC

Timer

Alarm

SchedulerPSchedulerP

Alarm

Timer

Page 30: TinyOS 2.1 tutorial at IPSN 2009

30

TinyOS Execution Model

SchedulerP

Stack

Task Queue

timer task

Interrupt table

RealMainP

AccelStreamC

AntiTheftC

Timer

Alarm

SchedulerPAntiTheftC

AccelStreamC

Timer

serialreceive H/W timer A/D conv.

Page 31: TinyOS 2.1 tutorial at IPSN 2009

31

Networking – “External” Types

#include “antitheft.h”module AntiTheftC { ... uses interface DisseminationValue<settings_t> as SettingsValue; } implementation { settings_t settings; event void SettingsValue.changed() { const settings_t *newSettings = call SettingsValue.get(); settings.detect = newSettings->detect; settings.alert = newSettings->alert; call Check.startPeriod(newSettings->checkInterval); }

event void Timer.fired() { if (settings.detect & DETECT_DARK) call Read.read(); if (settings.detect & DETECT_ACCEL) { call ReadStream.postBuffer(accelSamples, ACCEL_SAMPLES); call ReadStream.read(10000); } }

#ifndef ANTITHEFT_H#define ANTITHEFT_Htypedef nx_struct { nx_uint8_t alert, detect; nx_uint16_t checkInterval;} settings_t;#endif

External types (nx_...) provide C-like access, but:• platform-independent layout and endianness gives interoperability• no alignment restrictions means they can easily be used in network buffers• compiled to individual byte read/writes

Page 32: TinyOS 2.1 tutorial at IPSN 2009

32

TinyOS/nesC Summary

• Components and Interfaces– Programs built by writing and wiring components

• modules are components implemented in C• configurations are components written by assembling other

components

• Execution model– Execution happens in a series of tasks (atomic with respect

to each other) and interrupt handlers– No threads

• System services: startup, timing, sensing (so far)– (Mostly) represented by instantiatable generic components

• This instantiation happens at compile-time! (think C++ templates)

– All slow system requests are split-phase

Page 33: TinyOS 2.1 tutorial at IPSN 2009

33

Outline

• Components and interfaces– Basic example

• Tasks– More complex example

• Compiling and toolchain

Page 34: TinyOS 2.1 tutorial at IPSN 2009

34

The Toolchain

Native binary:

03 2F 779A F2 FF...

TinyOS

App

PC Applications

Page 35: TinyOS 2.1 tutorial at IPSN 2009

35

The Toolchain

TinyOS

Native binary:

03 2F 779A F2 FF...

App

PC Applications

Compile TinyOS applications

Page 36: TinyOS 2.1 tutorial at IPSN 2009

36

The Toolchain

Native binary:

03 2F 779A F2 FF...

TinyOS

App

PC Applications

Install applications on motes

Page 37: TinyOS 2.1 tutorial at IPSN 2009

37

The Toolchain

Native binary:

03 2F 779A F2 FF...

TinyOS

App

PC Applications

Build PC applications

Page 38: TinyOS 2.1 tutorial at IPSN 2009

38

The Toolchain

Native binary:

03 2F 779A F2 FF...

TinyOS

App

PC Applications

Document TinyOS

Page 39: TinyOS 2.1 tutorial at IPSN 2009

39

The “Make” System

Native binary:

03 2F 779A F2 FF...

make telosb install

automates nesC, C compilation,mote installation

TinyOS

App

PC Applications

Page 40: TinyOS 2.1 tutorial at IPSN 2009

40

“Make”: Compile Applications

ncc

gcc

int main() { scheduler_init(); ...}

Native binary:

03 2F 779A F2 FF...

Page 41: TinyOS 2.1 tutorial at IPSN 2009

41

“Make”: Install Applications

Native binary:

03 2F 779A F2 FF...

pybsl, uisp,etc

deluge

Page 42: TinyOS 2.1 tutorial at IPSN 2009

42

Build PC Applications

Native binary:

03 2F 779A F2 FF...

TinyOS

Java, C, Python apps

Packet formats, constants, etc

Talk withmotes

Page 43: TinyOS 2.1 tutorial at IPSN 2009

43

PC Applications:Extracting Information from TinyOS

mig

ncc –dump

ncg

Java, C orPython

app

packetformats

constants

<the kitchensink>

TinyOS

Page 44: TinyOS 2.1 tutorial at IPSN 2009

44

PC Applications:Talking to Motes

Java, C orPython

app

sf

packetlibs

packetlibs

Page 45: TinyOS 2.1 tutorial at IPSN 2009

45

Document TinyOS

nesdoc

Page 46: TinyOS 2.1 tutorial at IPSN 2009

TOSSIMRăzvan Musăloiu-E. (JHU)

46

Page 47: TinyOS 2.1 tutorial at IPSN 2009

What is TOSSIM?

Discrete event simulatorns2

47

Page 48: TinyOS 2.1 tutorial at IPSN 2009

Cycle-accurate simulatorsAvrora, MSPSim

Alternatives

48

Page 49: TinyOS 2.1 tutorial at IPSN 2009

49

Two directions

Portmake PC a supported platform

Virtualizesimulate one of the supported platforms

49

TOSSIMin tinyos-2.x

TOSSIMin tinyos-1.x

Page 50: TinyOS 2.1 tutorial at IPSN 2009

Features

• Simulates a MicaZ mote

– ATmega128L (128KB ROM, 4KB RAM)– CC2420

• Uses CPM to model the radio noise

• Supports two programming interfaces:

– Python– C++

50

Page 51: TinyOS 2.1 tutorial at IPSN 2009

51

Anatomy

51

TOSSIM

tos/lib/tossimtos/chips/atm128/simtos/chips/atm128/pins/simtos/chips/atm128/timer/simtos/chips/atm128/spi/simtos/platforms/mica/simtos/platforms/micaz/simtos/platforms/micaz/chips/cc2420/sim

Application

Makefile*.nc*.h

Simulation Driver

*.py | *.cc

Page 52: TinyOS 2.1 tutorial at IPSN 2009

52

Quick Overview

52

NesC

Glue

Python

C++

Application Simulation

Page 53: TinyOS 2.1 tutorial at IPSN 2009

53

The Building Process

$ make micaz sim

1.Generate an XML schema

2.Compile the application

3.Compile the Python support

4.Build a share object

5.Copying the Python support

$ ./sim.py

53

pytossim.o tossim.o

c-support.o

sim.o

app.xml

_TOSSIMmodule.o

TOSSIM.py

Page 54: TinyOS 2.1 tutorial at IPSN 2009

54

TOSSIM.py

Tossim

Radio

Mote

Packet

Mac

54

Page 55: TinyOS 2.1 tutorial at IPSN 2009

55

TOSSIM.Tossim

.getNode() → TOSSIM.Mote

.radio() → TOSSIM.Radio

.newPacket() → TOSSIM.Packet

.mac() → TOSSIM.Mac

.runNextEvent()

.ticksPerSecond()

.time()

55

Page 56: TinyOS 2.1 tutorial at IPSN 2009

56

10 seconds

from TOSSIM import *

t = Tossim([])

...

while t.time() < 10*t.ticksPerSecond():

t.runNextEvent()

56

Page 57: TinyOS 2.1 tutorial at IPSN 2009

57

dbg

Syntax

dbg(tag, format, arg1, arg2, ...);

Example

dbg(“Trickle”, “Starting time with time %u.\n”, timerVal);

Pythont = Tossim([])t.addChannel(“Trickle”, sys.stdout)

57

Page 58: TinyOS 2.1 tutorial at IPSN 2009

58

Useful Functions

58

char* sim_time_string()

sim_time_t sim_time()

int sim_random()

sim_time_t sim_ticks_per_sec()

typedef long long int sim_time_t;

Page 59: TinyOS 2.1 tutorial at IPSN 2009

59

Radio Model

59

Closest-fit Pattern Matching (CPM)

Improving Wireless Simulation Through Noise ModelingHyungJune Lee, Alberto Cerpa, and Philip Levis

IPSN 2007

Page 60: TinyOS 2.1 tutorial at IPSN 2009

60

Radio Model

60

Sender

Receiver

Page 61: TinyOS 2.1 tutorial at IPSN 2009

61

Noise Level

61

Meyer Heavy Casino Lab

Signal

SNRSNR

Page 62: TinyOS 2.1 tutorial at IPSN 2009

62

CC2420 SNR/PRR

62

Page 63: TinyOS 2.1 tutorial at IPSN 2009

63

TOSSIM.Radio

.add(source, destination, gain)

.connected(source, destination) → True/False

.gain(source, destination)

63

Page 64: TinyOS 2.1 tutorial at IPSN 2009

64

TOSSIM.Mote

.bootAtTime(time)

.addNoiseTraceReading(noise)

.createNoiseModel()

.isOn() → True/False

.turnOn()/.turnOff()

64

Page 65: TinyOS 2.1 tutorial at IPSN 2009

65

Example

65

0 1

2

-50 dB

-10 dB

from TOSSIM import *

t = Tossim([])

r = t.Radio()

mote0 = t.getNode(0)

mote1 = t.getNode(1)

mote2 = t.getNode(2)

r.add(0, 1, -10)

r.add(1, 0, -10)

r.add(1, 2, -50)

r.add(2, 1, -50)

Page 66: TinyOS 2.1 tutorial at IPSN 2009

66

Example (cont)

66

0 1

2

-50 dB

-10 dB

noise = file("meyer-short.txt")

lines = noise.readlines()

for line in lines:

str = line.strip()

if (str != ""):

val = int(str)

for m in [mote0, mote1, mote2]:

m.addNoiseTraceReading(val)

for m in [mote0, mote1, mote2]:

m.createNoiseModel()

Page 67: TinyOS 2.1 tutorial at IPSN 2009

67

Other Features

• Injecting packets

• Inspecting internal variables

• C++ interface

• Debuging using gdb

67

Page 68: TinyOS 2.1 tutorial at IPSN 2009

68

Improvements

• TossimLive

– SerialActiveMessageC

• CC2420sim

– Multiple channels– PacketLink– CC2420Packet: .getRSSI(), .getLQI()– ReadRssi()– Flash support

68

Page 69: TinyOS 2.1 tutorial at IPSN 2009

69

Future

Parametrized the PRR/SNR curve based on packet size (in progress)

Support for multiple binary images (harder)

69

Page 70: TinyOS 2.1 tutorial at IPSN 2009

Safe TinyOSJohn Regehr (Utah)

70

Page 71: TinyOS 2.1 tutorial at IPSN 2009

What is Safe TinyOS?

• Memory safe execution for TinyOS 2.1 apps– Compiler inserts safety checks– These checks trap pointer / array errors before

they can corrupt memory

• Behavior of memory-safe applications is unchanged

• Why use Safe TinyOS?– Debugging pointer and array problems on motes

can be extremely difficult

71

Page 72: TinyOS 2.1 tutorial at IPSN 2009

Using Safe TinyOS

• Must explicitly request safe compilation$ cd tinyos-2.x/apps/BaseStation

$ make micaz safe

18544 bytes in ROM

1724 bytes in RAM

$ make micaz

14888 bytes in ROM

1724 bytes in RAM

72

Page 73: TinyOS 2.1 tutorial at IPSN 2009

Designed to Fail

• In TinyOS 2.1: $ cd $TOSROOT/apps/tutorials/BlinkFail

$ make micaz install

• The application dies after a few seconds– BlinkFailC.nc has an obvious memory bug

• Next try this: $ make micaz safe install

• After a few seconds the mote starts blinking its LEDs in funny patterns

73

Page 74: TinyOS 2.1 tutorial at IPSN 2009

FLIDs

• Default behavior on safety violation is to output a FLID (Fault Location IDentifier) using the LEDs

• A FLID is 8 digits in base-4– No LEDs lit = 0– 1 LED lit = 1– 2 LEDs lit = 2– 3 LEDs lit = 3

• A tool decodes FLIDs into error messages

74

Page 75: TinyOS 2.1 tutorial at IPSN 2009

Decoding a FLID

$ tos-decode-flid ./build/micaz/flids.txt 00001020

Deputy error message for flid 0x0048:

BlinkFailC__a <= BlinkFailC__a + BlinkFailC__i++ + 1 (with no overflow): BlinkFailC.nc:70:

Assertion failed in CPtrArithAccess: BlinkFailC__a + BlinkFailC__i++ + 1 <= BlinkFailC__a + 10 (with no overflow)

75

Page 76: TinyOS 2.1 tutorial at IPSN 2009

Safe Components

• Safety is “opt in” at the level of nesC components

• This component is compiled as safe code: generic module SimpleArbiterP() @safe() { … }

• These components are “trusted” code: generic module SimpleArbiterP() @unsafe() { … }

generic module SimpleArbiterP() { … }

• Trusted code is compiled w/o safety checks

76

Page 77: TinyOS 2.1 tutorial at IPSN 2009

Porting Code to Safe TinyOS

• Recommended strategy1. Annotate a component as @safe()2. Compile application in safe mode3. Fix warnings / errors4. Repeat until no trusted components remain

• Arrays and pointers require annotations– Annotations are for Deputy, the safe C compiler

behind Safe TinyOS– Purpose of annotations is to link memory regions

with their bounds information

77

Page 78: TinyOS 2.1 tutorial at IPSN 2009

Annotation 1

• To declare msg, which always refers to a valid message_t

message_t* ONE msg = ...;

• Or if msg may be null

message_t* ONE_NOK msg;

• Most annotations have a _NOK form– But avoid using it when possible

78

Page 79: TinyOS 2.1 tutorial at IPSN 2009

Annotation 2

• To declare uartQueue as an array of 10 pointers to message_t– Where each element of the array must at all times

refer to a valid message_t

message_t* ONE uartQueue[10];

79

Page 80: TinyOS 2.1 tutorial at IPSN 2009

Annotation 3

• To declare reqBuf as a pointer that always points to a valid block of at least reqBytes uint8_ts:

uint8_t *COUNT(reqBytes) reqBuf;

• Array dereferencing / pointer arithmetic can be done on reqBuf:– reqBuf[0] is legal– reqBuf[reqBytes-1] is legal– reqBuf[reqBytes] results in a safety violation

80

Page 81: TinyOS 2.1 tutorial at IPSN 2009

Annotation 4

• Multiple-indirect pointers require an annotation at each level:

int *ONE *ONE pp = ...;

• However, these are uncommon in TinyOS

81

Page 82: TinyOS 2.1 tutorial at IPSN 2009

Annotation 5

• If you get stuck, the “trusted cast” offers an escape hatch:

cc2420_header_t* ONE x = TCAST( cc2420_header_t* ONE, (uint8_t *)msg + offsetof(message_t, data) - sizeof(cc2420_header_t)

);

82

Page 83: TinyOS 2.1 tutorial at IPSN 2009

Interface Annotation 1

• The getPayload() command from the Packet interface might be annotated like this:

command void* COUNT_NOK(len) getPayload (message_t* ONE msg,

uint8_t len);

83

Page 84: TinyOS 2.1 tutorial at IPSN 2009

Interface Annotation 2

• However, tinyos-2.x/tos/interfaces/Packet.nc contains:

* @param 'message_t* ONE msg' …

* @param len …

* @return 'void* COUNT_NOK(len)' … */

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

• nesC allows you to put annotations in documentation comments

84

Page 85: TinyOS 2.1 tutorial at IPSN 2009

Safe TinyOS Summary

• Safe execution is useful

• Safety annotations are good documentation

• Most Mica2, MicaZ, TelosB apps and core services are safe

• Safe TinyOS Tutorial:– http://docs.tinyos.net/index.php/Safe_TinyOS

85

Page 86: TinyOS 2.1 tutorial at IPSN 2009

ThreadsKevin Klues (UCB)

86

Page 87: TinyOS 2.1 tutorial at IPSN 2009

The Great Divide

• Event-Based Execution– More efficient– Less RAM usage– More complex

• Thread-Based Execution– Less Efficient– More RAM Usage– Less Complex

void myFunc() { error_t e = read(); //continue execution flow}void readDone(uint8_t val, error_t e) { //read() continuation code}

void myFunc() { error_t e; uint8_t val = read(&e); //read() continuation code}

TOSThreads aims to resolve this fundamental tension

87

Page 88: TinyOS 2.1 tutorial at IPSN 2009

TOSThreads in a Nutshell

• Natural extension to the existing TinyOS concurrency model

• Implements Full-Fledged Threads Library

• Introduces Minimal Disruption to TinyOS

• Provides Flexible Event-based / Thread-based Code Boundary

• Enables Dynamic Linking and Loading of Application Binaries at Runtime

• Standard C and nesC based APIs

88

Page 89: TinyOS 2.1 tutorial at IPSN 2009

Architecture Overview

Task Scheduler

Thread Scheduler

System Calls

TinyOS Thread

Application Threads

89

Page 90: TinyOS 2.1 tutorial at IPSN 2009

Blink Example (nesC)

configuration BlinkAppC {}implementation { components MainC, BlinkC, LedsC; components new ThreadC(STACK_SIZE);

MainC.Boot <- BlinkC; BlinkC.Thread -> ThreadC; BlinkC.Leds -> LedsC;}

module BlinkC { uses { interface Boot; interface Thread; interface Leds; }}implementation { event void Boot.booted() { call Thread.start(NULL); } event void Thread.run(void* arg) { for(;;) { call Leds.led0Toggle(); call Thread.sleep(BLINK_PERIOD); } }

90

Page 91: TinyOS 2.1 tutorial at IPSN 2009

Blink Example (standard C)

#include "tosthread.h"#include "tosthread_leds.h"

//Initialize variables associated with a threadtosthread_t blink;void blink_thread(void* arg);

void tosthread_main(void* arg) { tosthread_create(&blink, blink_thread, NULL, STACK_SIZE);}void blink_thread(void* arg) { for(;;) { led0Toggle(); tosthread_sleep(BLINK_PERIOD); }}

91

Page 92: TinyOS 2.1 tutorial at IPSN 2009

Modifications to TinyOS

• Change in boot sequence

• Small change is TinyOS task scheduler

• Additional post-amble in the interrupt sequence

92

Page 93: TinyOS 2.1 tutorial at IPSN 2009

Boot Sequence

event void TinyOS.booted() { atomic {

platform_bootstrap();

call Scheduler.init();

call PlatformInit.init(); while (call Scheduler.runNextTask());

call SoftwareInit.init(); while (call Scheduler.runNextTask());

} signal Boot.booted();

/* Spin in the Scheduler */ call Scheduler.taskLoop(); }

Standard TinyOS Boot Mainint main() { signal TinyOS.booted();

//Should never get here return -1;}

93

Page 94: TinyOS 2.1 tutorial at IPSN 2009

Boot Sequence

event void ThreadScheduler.booted() { setup_TinyOS_in_kernel_thread(); signal TinyOSBoot.booted(); }

Thread Scheduler Boot New Mainint main() { signal ThreadScheduler.booted();

//Should never get here return -1;}

94

Page 95: TinyOS 2.1 tutorial at IPSN 2009

Task Scheduler

command void Scheduler.taskLoop() { for (;;) { uint8_t nextTask; atomic {

while ((nextTask = popTask()) == NO_TASK)) call McuSleep.sleep();

} signal TaskBasic.runTask[nextTask](); } }

Original

command void Scheduler.taskLoop() { for (;;) { uint8_t nextTask; atomic {

while ((nextTask = popTask()) == NO_TASK) call ThreadScheduler.suspendThread(TOS_THREAD_ID);

} signal TaskBasic.runTask[nextTask](); } }

New

95

Page 96: TinyOS 2.1 tutorial at IPSN 2009

Interrupt Handlers

void interruptCurrentThread() { if( call TaskScheduler.hasTasks() ) { call ThreadScheduler.wakeupThread(TOS_THREAD_ID); call ThreadScheduler.interruptCurrentThread(); } }

TOSH_SIGNAL(ADC_VECTOR) { signal SIGNAL_ADC_VECTOR.fired(); atomic interruptCurrentThread(); }TOSH_SIGNAL(DACDMA_VECTOR) { signal SIGNAL_DACDMA_VECTOR.fired(); atomic interruptCurrentThread(); }….….

96

Page 97: TinyOS 2.1 tutorial at IPSN 2009

System Calls

TaskQueue

Routing

Arbiter

System CallTask Receive

Timer

Send

Receive

Sense

Block Storage

Application Thread System Calls

TinyOS Thread

97

Page 98: TinyOS 2.1 tutorial at IPSN 2009

Linking and Loading

• Full applications written in standard C

• Custom MicroExe format

• Multiple concurrently running applications

• Generic TinyLD component supporting multiple APIs

98

Page 99: TinyOS 2.1 tutorial at IPSN 2009

Resources

• TOSThreads Tutorialhttp://docs.tinyos.net/index.php/TOSThreads_Tutorial

• TOSThreads TEPhttp://www.tinyos.net/tinyos-2.x/doc/html/tep134.html

• Source CodeSystem code: tinyos-2.x/tos/lib/tosthreadsExample Applications: tinyos-2.x/apps/tosthreads

99

Page 100: TinyOS 2.1 tutorial at IPSN 2009

ProtocolsOmprakash Gnawali (USC)

100

Page 101: TinyOS 2.1 tutorial at IPSN 2009

Protocols in TinyOS 2.1

• Network Protocols– Collection: CTP, MultihopLQI– Dissemination: Drip, DIP

• Time Synchronization (FTSP)

• Over-the-air programming (Deluge)

101

Page 102: TinyOS 2.1 tutorial at IPSN 2009

Collection

• Collect data from the network to one or a small number of roots

• One of many traffic classes

• Available: MultihopLQI and CTP

102

Page 103: TinyOS 2.1 tutorial at IPSN 2009

MultihopLQI

• Mostly tested and used on platforms with CC2420– MicaZ, TelosB, …

• Small code footprint

• tos/lib/net/lqi

103

Page 104: TinyOS 2.1 tutorial at IPSN 2009

CTP

• Platform independent

• More consistent performance than with MultihopLQI

• Code footprint can be a concern

• tos/lib/net/ctp

104

Page 105: TinyOS 2.1 tutorial at IPSN 2009

CTP Architecture

Router

ForwarderLnk Estimator

Link Layer

Application

105

Page 106: TinyOS 2.1 tutorial at IPSN 2009

CTP Link Estimator

• Platform independent– Beacons and data packets

• Bi-directional ETX estimate

• Does not originate beacons itself

• Accurate but also agile

106

Page 107: TinyOS 2.1 tutorial at IPSN 2009

CTP Router

• ETX path metric

• Beacon interval can be 64 ms-x mins

• Select new path if better by at least 1.5 ETX

• Alternate parents

107

Page 108: TinyOS 2.1 tutorial at IPSN 2009

CTP Forwarder

• Duplicate suppression

• Retransmissions

• Loops trigger route updates

• Forward through alternate parents

108

Page 109: TinyOS 2.1 tutorial at IPSN 2009

CTP Reliability

109

Page 110: TinyOS 2.1 tutorial at IPSN 2009

Dissemination

• Send data to all the nodes Commands, configuration parameters

• Efficient and fast

• Available protocols – Drip and DIP

110

Page 111: TinyOS 2.1 tutorial at IPSN 2009

Drip

• Fast and efficient for small number of items

• Trickle timers for advertisements

• Suppression

• tos/lib/net/drip

111

Page 112: TinyOS 2.1 tutorial at IPSN 2009

DIP

• Efficiently Disseminates large number of items (can not fit in one packet)

• Use hashes and version vectors to detect and identify updates to the values

• tos/lib/net/dip

112

Page 113: TinyOS 2.1 tutorial at IPSN 2009

Deluge

• Over-the-air programming

• Disseminates code

• Programs the nodes

113

Page 114: TinyOS 2.1 tutorial at IPSN 2009

Deluge Details

• Supports Tmote Sky/EPIC and MicaZ.

• Bulk dissemination on top of Drip

• Python tools

• Support for MIB600. (new)

• tos/lib/net/Deluge, tos/lib/tosboot

114

Page 115: TinyOS 2.1 tutorial at IPSN 2009

Time Synchronization

• Global time on all the nodes

• Node with smallest id becomes the root

• Flooding Time Synchronization Protocol (FTSP)

• tos/lib/ftsp

115

Page 116: TinyOS 2.1 tutorial at IPSN 2009

UpcomingTechnologies

Stephen Dawson-Haggerty (UCB)

116

Page 117: TinyOS 2.1 tutorial at IPSN 2009

“Work in Progress”

• Proceeding in working groups– IEEE 802.15.4 – Zigbee– 6lowpan/IPv6

• Overall theme: leverage emerging standards

117

Page 118: TinyOS 2.1 tutorial at IPSN 2009

IEEE 802.15.4

• PHY/MAC specification

• MAC under development by working group– CSMA-CA– GTS– Slotted CSMA-CA

• Application interface in flux

• More reading:– tos/lib/mac/tkn154– http://www.tkn.tu-berlin.de/publications/papers/TKN154.pdf

AssociateP

Beacon-TransmitP

Coordinator-BroadcastP

Frame-DispatchP

NoCoord/DeviceCfpP

PibP

RadioControlP

SimpleTransfer-ArbiterP

Radio Driver / PHY

Promiscuous-ModeP

RadioTx RadioRx RadioOff EnergyDetection

ScanP

ResourceRadio[Tx/Rx/Off]

PollPIndirectTxP

Beacon-SynchronizeP

Coord-RealignmentP

DataP

FrameTxFrameRx

Alarm / Timer

FrameDis-patchQueueP

Symbol Clock

MCPS-SAPMLME-SAP

TKN154P

DisAssociateP

RxEnableP

118

Page 119: TinyOS 2.1 tutorial at IPSN 2009

ZigBee

• Network protocol and application stack built on IEEE 802.15.4

• Goal: standards-complaint Zigbee-pro stack built on 802.15.4 stack– Cluster-tree, mesh routing– Security– Application profiles: i.e. HVAC, Sensing

119

Page 120: TinyOS 2.1 tutorial at IPSN 2009

IPv6

• IPv6 a good fit for sensor networks– What about large header size? 6loWPAN

• Ideas about many important issues– Management– Configuration– Security

• TEP138, draft-tavakoli-hydro-01

120

Page 121: TinyOS 2.1 tutorial at IPSN 2009

IPv6

• BLIP: IPv6 for TinyOS– Current progress: being integrated into core

• Useful basic feature set– Mesh routing– TCP/UDP

• Lots of tools, libraries for building apps– Shell, network reprogramming, RPC, …

121

Page 122: TinyOS 2.1 tutorial at IPSN 2009

An IP Network

• “sensor network” ≈ “IP subnet”

• “TOS_NODE_ID” ≈ “IP address”

• “base station” ≈ “edge router”

• “application gateway” no longer exists

internetinternet

backhaul linksedge routers

node routers

122

Page 123: TinyOS 2.1 tutorial at IPSN 2009

Addressing• 128-bit address space

• Lots of IPv6 RFCs deal with this: RFC2461, RFC4862

Address type Example TinyOS usage

Link-local unicast fe80::beef L2 Mapped

Link-local multicast ff02::1 Radio local broadcast

Global unicast 2001::64 Routable address

Network ID/64 Interface ID/64

123

Page 124: TinyOS 2.1 tutorial at IPSN 2009

Useful Interfaces

interface UDP {command error_t bind(uint16_t port);command error_t sendto(struct sockaddr_in6 *dest,

void *payload, uint16_t len);event void recvfrom(struct sockaddr_in6 *src, void *payload,

uint16_t len, struct ip_metadata *meta);}

interface ICMPPing { command error_t ping(struct in6_addr *target,

uint16_t period, uint16_t n); event void pingReply(struct in6_addr *source,

struct icmp_stats *stats); event void pingDone(uint16_t ping_rcv, uint16_t ping_n);}

UD

PSock

etC

ICM

PR

esp

on

derC

124

Page 125: TinyOS 2.1 tutorial at IPSN 2009

Address Structures

• A lot like linux: ip.h

struct sockaddr_in6 { uint16_t sin6_port; struct in6_addr sin6_addr;};

125

Page 126: TinyOS 2.1 tutorial at IPSN 2009

Example App: Sense & Send

event Timer.fired() {call Read.read();

}Read.readDone(error_t result, uint16_t val) {

struct sockaddr_in6 dest;nx_struct report r;r.reading = val;inet_pton6(“2001::64”, &dest.sin6_addr);dest.sin6_port = htons(REPORT_PORT);call UDP.sendto(dest, &r, sizeof(r));

}

Configuration MyAppC{} implementation {

components MyAppP, new UdpSocketC();MyAppP.UDP -> UdpSocketC;...

}

126

Page 127: TinyOS 2.1 tutorial at IPSN 2009

Conclusions

• Exciting developments expected in 2009!

• Project links:– 802.15.4: http://tinyos.stanford.edu:8000/15.4_WG/ – Zigbee: http://www.open-zb.net/– BLIP: http://smote.cs.berkeley.edu:8000/tracenv/wiki/blip

127

Page 128: TinyOS 2.1 tutorial at IPSN 2009

Hands-onSession

Răzvan, Om, et al.

128

Page 129: TinyOS 2.1 tutorial at IPSN 2009

129

Goals

1.Install TinyOS

2.Layout of tinyos-2.x

3.Write two applications(A) DisseminationDemoClient(B) CollectionsDemoClient

129

Page 130: TinyOS 2.1 tutorial at IPSN 2009

130

Options

• LiveCD– XubunTOS– Customized Ubuntu 8.10 LiveCD

• Native– Linux

• .rpm packages• .deb packages

– Windows: Cygwin + .rpm packages

– MacOS X• stow• macports

130

Recommended

Today

Page 131: TinyOS 2.1 tutorial at IPSN 2009

131

Other Options

• VMware– Jetos

• based on JeOS (Ubuntu Server 8.04)• optimized for ssh access• very small: 190MB compressed

– Lenny• based on Debian 5.0 “Lenny”• graphical interface using XFCE• bigger: 300MB compressed

– XubunTOS

131

Page 132: TinyOS 2.1 tutorial at IPSN 2009

132

Components

• NesC: nesc_*.deb

• Cross compiler– binutils: msp430-binutils-tinyos_*.deb– gcc: msp430-gcc-tinyos_*.deb– libc: msp430-libc-tinyos_*.deb– gdb (optional)

• Deputy: deputy-tinyos_*.deb

132

Page 133: TinyOS 2.1 tutorial at IPSN 2009

133

Environment

133

export TOSROOT=$HOME/local/src/tinyos-2.xexport TOSDIR=$TOSROOT/tosexport MAKERULES=$TOSROOT/support/make/Makerules

export CLASSPATH=$TOSROOT/support/sdk/java/tinyos.jar:.export PYTHONPATH=$TOSROOT/support/sdk/python

Page 134: TinyOS 2.1 tutorial at IPSN 2009

134

Architectures

• AVR– mica2, mica2dot– micaz– btnode– IRIS

• ARM– imote2

134

• MSP430– telosb, sky– shimmer– eyesIFX– tinynode– epic

• 8051– CC2430– CC1110/CC1111

Page 135: TinyOS 2.1 tutorial at IPSN 2009

135

Layout

135

+ tinyos-2.x + apps + docs + support + tools + tos

Page 136: TinyOS 2.1 tutorial at IPSN 2009

136

Layout

136

+ apps + Blink + Null + RadioCountToLeds + MultihopOscilloscope + tests + ... + ...+ docs+ support+ tools+ tos

Page 137: TinyOS 2.1 tutorial at IPSN 2009

137

Layout

137

+ apps+ docs + html + pdf + txt + ...+ support+ tools+ tos

Page 138: TinyOS 2.1 tutorial at IPSN 2009

138

Layout

138

+ apps+ docs+ support + make - Makerules + avr/ + msp/ + ... + sdk+ tools+ tos

Page 139: TinyOS 2.1 tutorial at IPSN 2009

139

Layout

139

+ apps+ docs+ support + make + sdk + c + cpp + java + python+ tools+ tos

Page 140: TinyOS 2.1 tutorial at IPSN 2009

140

Layout

140

+ support + sdk + c + blip + sf + cpp + sf + java - tinyos.jar + python + tinyos - tos.py

Page 141: TinyOS 2.1 tutorial at IPSN 2009

141

Layout

141

+ apps+ docs+ support+ tools+ tos + chips + interfaces + lib + platforms + sensorboards + systems + types

Page 142: TinyOS 2.1 tutorial at IPSN 2009

142

Layout

142

+ tos + chips + atm128 + msp430 + pxa27x + cc2420 + cc1000 + at45db + stm25p + sht11 + ...

Page 143: TinyOS 2.1 tutorial at IPSN 2009

143

Layout

143

+ tos + chips + interfaces - Boot.nc - SplitControl.nc - StdControl.nc - ... + lib + platforms + sensorboards + systems + types

Page 144: TinyOS 2.1 tutorial at IPSN 2009

144

Layout

144

+ tos + lib + net + printf + timer + tosthreads + serial - SerialActiveMessageC.nc - SerialAMSenderC.nc - SerialAMReceiverC.nc - ... + ...

Page 145: TinyOS 2.1 tutorial at IPSN 2009

145

Layout

145

+ tos + lib + net + ctp + 4bitle + drip + Deluge + dip + blip + ...

Page 146: TinyOS 2.1 tutorial at IPSN 2009

146

Layout

146

+ tos + systems - AMReceiverC.nc - AMSenderC.nc - MainC.nc - LedsC.nc - TimerMilliC.nc - ...

Page 147: TinyOS 2.1 tutorial at IPSN 2009

147

Layout

147

+ tos + chips + interfaces + lib + platforms + sensorboards + systems + types - TinyError.h - messssage.h - ...

Page 148: TinyOS 2.1 tutorial at IPSN 2009

Applications

DisseminationDemo

CollectionDemo

148

Page 149: TinyOS 2.1 tutorial at IPSN 2009

149

DisseminationDemo

149

Page 150: TinyOS 2.1 tutorial at IPSN 2009

150

DisseminationDemo• DisseminationDemoClient

– start the radio– start Drip– when a new value is received print its contents

• DisseminationDemoServer– start the radio– start Drip– start a periodic timer– on each firing or the timer increment a counter

and disseminate it

150

Page 151: TinyOS 2.1 tutorial at IPSN 2009

151

DisseminationDemoClient

151

MainCActiveMessage

CDissemination

CDisseminator

C

DisseminationDemoClientC

Boot SplitControl StdControlDisseminationValue

<nx_uint32_t>

Page 152: TinyOS 2.1 tutorial at IPSN 2009

152

DisseminationDemoClient

• Interfaces– Boot– StdControl– SplitControl– DisseminationValue<t>

152

• Components– MainC– ActiveMessageC– DisseminationC– DisseminatorC

Page 153: TinyOS 2.1 tutorial at IPSN 2009

153

tos/interfaces/Boot.nc

153

interface Boot { event void booted();}

Page 154: TinyOS 2.1 tutorial at IPSN 2009

154

tos/interfaces/StdControl.nc

154

interface StdControl{ command error_t start(); command error_t stop();}

Page 155: TinyOS 2.1 tutorial at IPSN 2009

155

tos/interfaces/SplitControl.nc

155

interface SplitControl{ command error_t start(); event void startDone(error_t error); command error_t stop(); event void stopDone(error_t error);}

Page 156: TinyOS 2.1 tutorial at IPSN 2009

156

tos/lib/net/DisseminationValue.nc

156

interface DisseminationValue<t> { command const t* get(); command void set(const t*); event void changed();}

Page 157: TinyOS 2.1 tutorial at IPSN 2009

157

tos/system/MainC.nc

157

configuration MainC { provides interface Boot; uses interface Init as SoftwareInit;}

implementation { ...}

Page 158: TinyOS 2.1 tutorial at IPSN 2009

158

tos/platforms/telosa/ActiveMessageC.nc

158

configuration ActiveMessageC { provides { interface SplitControl; ... }}

implementation { ...}

Page 159: TinyOS 2.1 tutorial at IPSN 2009

159

tos/lib/net/drip/DisseminationC.nc

159

configuration DisseminationC { provides interface StdControl;}

implementation { ...}

Page 160: TinyOS 2.1 tutorial at IPSN 2009

160

tos/lib/net/drip/DisseminatorC.nc

160

generic configuration DisseminatorC(typedef t, uint16_t key) { provides interface DisseminationValue<t>; provides interface DisseminationUpdate<t>;}

implementation { ...}

Page 161: TinyOS 2.1 tutorial at IPSN 2009

161

Makefile

161

COMPONENT=DisseminationDemoClientAppC

CFLAGS += -I%T/lib/netCFLAGS += -I%T/lib/net/dripCFLAGS += -I%T/lib/printf

include $(MAKERULES)

Page 162: TinyOS 2.1 tutorial at IPSN 2009

162

Commands

162

$ make telosb

$ make telosb install,42

$ tos-dump.py serial@/dev/ttyUSB0:115200

Page 163: TinyOS 2.1 tutorial at IPSN 2009

163

Summary

163

tos/interfaces/Boot.nctos/interfaces/StdControl.nctos/interfaces/SplitControl.nc

tos/system/MainC.nctos/platforms/telosa/ActiveMessageC.nctos/lib/net/drip/DisseminationC.nctos/lib/net/drip/DisseminatorC.nc

Page 164: TinyOS 2.1 tutorial at IPSN 2009

164

DisseminationDemoClientAppC.nc

configuration DisseminationDemoClientAppC { }

implementation

{

components MainC;

components DisseminationC;

components new DisseminatorC(nx_uint32_t, 2009);

components DisseminationDemoClientC;

components ActiveMessageC;

DisseminationDemoClientC.Boot -> MainC;

DisseminationDemoClientC.DisseminationStdControl -> DisseminationC;

DisseminationDemoClientC.DisseminationValue -> DisseminatorC;

DisseminationDemoClientC.RadioSplitControl -> ActiveMessageC;

}

164

Page 165: TinyOS 2.1 tutorial at IPSN 2009

165

DisseminationDemoClientC.nc

module DisseminationDemoClientC{ uses { interface Boot; interface DisseminationValue<nx_uint32_t>; interface StdControl as DisseminationStdControl; interface SplitControl as RadioSplitControl; }}

implementation{ nx_uint32_t counter;

event void Boot.booted() { call RadioSplitControl.start(); }

...

}

165

Page 166: TinyOS 2.1 tutorial at IPSN 2009

166

DisseminationDemoClientC.nc

module DisseminationDemoClientC{ ...}

implementation{

...

event void RadioSplitControl.startDone(error_t error) { call DisseminationStdControl.start(); }

event void DisseminationValue.changed() { printf("R: %lu\n", *(call DisseminationValue.get())); printfflush(); }

event void RadioSplitControl.stopDone(error_t error) { }}

166

Page 167: TinyOS 2.1 tutorial at IPSN 2009

167

CollectionDemo

167

Page 168: TinyOS 2.1 tutorial at IPSN 2009

168

CollectionDemo• CollectionDemoClient

– start the radio– start CTP– start a periodic timer– on each firing or the timer increment a counter

and sent it over CTP

• CollectionDemoServer– start the radio– start CTP– when a new value is received print its contents

168

Page 169: TinyOS 2.1 tutorial at IPSN 2009

169

CollectionDemoClient

169

MainCActiveMessage

CCollection

CCollectionSende

rC

CollectionDemoClientC

Boot SplitControl StdControl Send

TimerMilliC

Timer<TMilli>

Page 170: TinyOS 2.1 tutorial at IPSN 2009

170

CollectionDemoClient

• Interfaces– Boot– StdControl– SplitControl– Send– Timer<TMilli>

170

• Components– MainC– ActiveMessageC– CollectionC– CollectionSenderC– TimerMilliC

Page 171: TinyOS 2.1 tutorial at IPSN 2009

171

CollectionDemoClient

• Interfaces– Boot– StdControl– SplitControl– Send– Timer<TMilli>

171

• Components– MainC– ActiveMessageC– CollectionC– CollectionSenderC– TimerMilliC

Page 172: TinyOS 2.1 tutorial at IPSN 2009

172

tos/interfaces/Send.nc

172

interface Send { command error_t send(message_t* msg, uint8_t len); event void sendDone(message_t* msg, error_t error); command uint8_t maxPayloadLength(); command void* getPayload(message_t* msg, uint8_t len);

command error_t cancel(message_t* msg);}

Page 173: TinyOS 2.1 tutorial at IPSN 2009

173

tos/lib/net/ctp/CollectionC.nc

173

configuration CollectionC { provides { interface StdControl; ... }}

implementation { ...}

Page 174: TinyOS 2.1 tutorial at IPSN 2009

174

tos/lib/net/ctp/CollectionSenderC.nc

174

generic configurationCollectionSenderC(collection_id_t collectid) { provides { interface Send; interface Packet; }}

implementation { ...}

Page 175: TinyOS 2.1 tutorial at IPSN 2009

175

tos/system/TimerMilliC.nc

175

generic configuration TimerMilliC() { provides interface Timer<TMilli>;}

implementation { ...}

Page 176: TinyOS 2.1 tutorial at IPSN 2009

176

Makefile

176

COMPONENT=CollectionDemoClientAppC

CFLAGS += -I%T/lib/netCFLAGS += -I%T/lib/net/ctpCFLAGS += -I%T/lib/net/4bitleCFLAGS += -I%T/lib/printf

include $(MAKERULES)

Page 177: TinyOS 2.1 tutorial at IPSN 2009

177

Summary

177

tos/interfaces/Boot.nctos/interfaces/StdControl.nctos/interfaces/SplitControl.nctos/interfaces/Send.nctos/lib/timer/Timer.nc

tos/system/MainC.nctos/system/TimerMilliC.nctos/platforms/telosa/ActiveMessageC.nctos/lib/net/ctp/CollectionC.nctos/lib/net/ctp/CollectionSenderC.nc

Page 178: TinyOS 2.1 tutorial at IPSN 2009

178

CollectionDemoClientAppC.nc

configuration CollectionDemoClientAppC { }

implementation

{

components MainC;

components ActiveMessageC;

components CollectionC;

components new CollectionSenderC(16);

components new TimerMilliC() as Timer;

components CollectionDemoClientC;

CollectionDemoClientC.Boot -> MainC;

CollectionDemoClientC.RadioSplitControl -> ActiveMessageC;

CollectionDemoClientC.CollectionStdControl -> CollectionC;

CollectionDemoClientC.Send -> CollectionSenderC;

CollectionDemoClientC.Timer -> Timer;

}

178

Page 179: TinyOS 2.1 tutorial at IPSN 2009

179

CollectionDemoClientC.nc

module CollectionDemoClientC{ uses { interface Boot; interface SplitControl as RadioSplitControl; interface StdControl as CollectionStdControl; interface Send; interface Timer<TMilli>; }}

implementation{ message_t smsg;

typedef nx_struct { nx_uint8_t string[8]; nx_uint16_t counter; } name_t; name_t *name;

...}

179

Page 180: TinyOS 2.1 tutorial at IPSN 2009

180

CollectionDemoClientC.nc

module CollectionDemoClientC{ ...}

implementation{

...

event void Boot.booted() { name = call Send.getPayload(&smsg, sizeof(name_t)); strcpy((char*)name->string, "name"); name->counter = 0; call RadioSplitControl.start(); }

...

}

180

Page 181: TinyOS 2.1 tutorial at IPSN 2009

181

CollectionDemoClientC.nc

module CollectionDemoClientC{ ...}

implementation{

...

event void RadioSplitControl.startDone(error_t error) { call CollectionStdControl.start(); call Timer.startPeriodic(1024); }

...

}

181

Page 182: TinyOS 2.1 tutorial at IPSN 2009

182

CollectionDemoClientC.nc

module CollectionDemoClientC{ ...}

implementation{

...

event void Timer.fired() { error_t error; name->counter++; error = call Send.send(&smsg, sizeof(name_t)); printf("S: %d %d\n", name->counter, error); printfflush(); }

event void Send.sendDone(message_t* msg, error_t error) { } event void RadioSplitControl.stopDone(error_t error) { }}

182

Page 183: TinyOS 2.1 tutorial at IPSN 2009

183

Code available athttp://docs.tinyos.net/index.php/Ipsn2009-tutorial

183

Page 184: TinyOS 2.1 tutorial at IPSN 2009

184

The End.

184