June 2008 WEI L4 - TinyOS Prog 1
Wireless Embedded Inter-Networking
Foundations of Ubiquitous Sensor Networks
TinyOS 2.0 Programing – An IPv6 Kernel Approach
David E. CullerUniversity of California, Berkeley
June 2008 WEI L4 - TinyOS Prog 2
Example Complete Network Embedded System
MicrocontrollerAbstraction
Interface
Init/
Boo
t
PersistentAttributes &
Event Streams
DeviceAttributes &
Event Streams
Mot
or
Ligh
t
Blo
cks
Vib
ratio
n
Log
s
File
s
DeviceAbstraction
Interface
Core OSInterface
ServiceInterface
Flash Radio Serial Sensor / ActuatorC
omm
and
s
Att
ribut
es
Eve
nts
Dis
cove
ry
NetworkEpidemics and Routing
Mes
sage
s
Man
agem
ent
&
Pow
er
Domain-Specific Application Components
Net
Pro
g
Links
Do
ma
in-S
pec
ific
Dev
ice
Dri
vers
Telos micaZ imote2 other
SPI i2cuarttimersched ADC
resource
June 2008 WEI L4 - TinyOS Prog 3
Outline
• Key TinyOS Concepts
• TinyOS Abstraction Architecture
• A Simple Event-Driven Example
• Execution Model
• Critical system elements– Timers, Sensors, Communication
• Service Architecture
June 2008 WEI L4 - TinyOS Prog 4
TinyOS 2.0
• Primary Reference: http://www.tinyos.net/tinyos-2.x/doc/
• http://www.tinyos.net/tinyos-2.x/doc/html/tutorial/
• http://nescc.sourceforge.net/papers/nesc-ref.pdf
June 2008 WEI L4 - TinyOS Prog 5
Key TinyOS Concepts
• Application / System = Graph of Components + Scheduler
• Module: component that implements functionality directly
• Configuration: component that composes components into a larger component by connecting their interfaces
• Interface: Logically related collection of commands and events with a strongly typed (polymorphic) signature
– May be parameterized by type argument
– Provided to components or Used by components
• Command: Operation performed (called) across components to initiate action.
• Event: Operation performed (signaled) across components for notification.
• Task: Independent thread of control instantiated within a component. Non-preemptive relative to other task.
• Synchronous and Asynchronous contexts of execution.
June 2008 WEI L4 - TinyOS Prog 6
TinyOS Abstraction Architecture
• HPL – Hardware Presentation Layer– Components that encapsulate physical hardware units
– Provide convenient software interface to the hardware.
– The hardware is the state and computational processes.
– Commands and events map to toggling pins and wires
• HAL –Hardware Abstraction Layer– Components that provide useful services upon the basic HW
– Permitted to expose any capabilities of the hardware
» Some platforms have more ADC channels, Timers, DMA channels, capture registers, …
– Logically consistent, but unconstrained
• HIL – Hardware Independent Layer– Components that provide well-defined services in a manner
that is the same across hardware platforms.
– Implement common interfaces over available HAL
June 2008 WEI L4 - TinyOS Prog 7
Illustration
June 2008 WEI L4 - TinyOS Prog 8
TinyOS – a tool for defining abstractions
• All of these layers are constructed with the same TinyOS primitives.
• We’ll illustrate them from a simple application down.
• Note, components are not objects, but they have strong similarities.
– Some components encapsulate physical hardware.
– All components are allocated statically (compile time)
» Whole system analysis and optimization
– Logically, all components have internal state, internal concurrency, and external interfaces (Commands and Events)
– Command & Event handlers are essentially public methods
– Locally scoped
» Method invocation and method hander need not have same name (like libraries and objects)
» Resolved statically by wiring• Permits interpositioning
June 2008 WEI L4 - TinyOS Prog 9
Platform is a collection of Chips
• TinyOS 2.x components provide the capabilities of the chips.
• TinyOS 2.x components glue to together those capabilities into a consistent system.
• TinyOS 2.x components provide higher level capabilities and services
June 2008 WEI L4 - TinyOS Prog 10
Overall System Configuration (std)
June 2008 WEI L4 - TinyOS Prog 11
TinyOS IPv6 Network Kernel
ActuatorActuatorSensorsSensorsTimer FlashRadio Sensor Actuator
• Network Kernel– Manages communication and storage
– Scheduler (decides when to signal events)
IPv6 Network Kernel DriverDriverDriverDriverDriver Driver
Application
June 2008 WEI L4 - TinyOS Prog 12
Illustration of TinyOS Programming Concepts
June 2008 WEI L4 - TinyOS Prog 13
A simple event-driven module – BlinkM.nc
• Coding conventions: TEP3
#include "Timer.h"module BlinkM{ uses interface Boot; uses interface Timer<TMilli> as Timer0; uses interface Leds;}implementation{ event void Boot.booted() { call Timer0.startPeriodic( 250 ); }
event void Timer0.fired() { call Leds.led0Toggle(); }
BlinkM
Timer0Boot Leds
Module
Module name
Interfaces• Boot• Timer• Leds
Internal name of external interface
June 2008 WEI L4 - TinyOS Prog 14
A simple event-drvien module (cont)
#include "Timer.h"module BlinkM{ uses interface Boot; uses interface Timer<TMilli> as Timer0; uses interface Leds;}implementation{ event void Boot.booted() { call Timer0.startPeriodic( 250 ); }
event void Timer0.fired() { call Leds.led0Toggle(); }
BlinkM
Timer0Boot Leds
Two Event Handlers
Each services external eventby calling command on some subsystem
? ? ?
June 2008 WEI L4 - TinyOS Prog 15
Simple example: Boot interface
• $tinyOS-2.x/tos/interfaces/
• Defined in TEP 107 – Boot Sequence
• Consists of a single event.
• Hardware and operating system actions prior to this simple event may vary widely from platform to platform.
• Allows module to initialize itself, which may require actions in various other parts of the system.
interface Boot { /** * Signaled when the system has booted successfully. Components can * assume the system has been initialized properly. Services may * need to be started to work, however. * * @see StdControl * @see SplitConrol * @see TEP 107: Boot Sequence */
event void booted();}
June 2008 WEI L4 - TinyOS Prog 16
Simple example: LEDs interface
• $tinyOS-2.x/tos/interfaces/• set of Commands
– Cause action– get/set a physical attribute (3 bits)
• async => OK to use even within interrupt handlers• Physical wiring of LEDs to microcontroller IO pins may vary=> We will implement a simplified version
#include "Leds.h"
interface Leds { async command void led0On(); async command void led0Off(); async command void led0Toggle(); async command void led1On(); ... /* * @param val a bitmask describing the on/off settings of the LEDs */
async command uint8_t get(); async command void set(uint8_t val);}
June 2008 WEI L4 - TinyOS Prog 17
Timer
• $tinyOS-2.x/tos/lib/timer/Timer.nc• Rich application timer service built upon lower level capabilities that may be very
different on different platform– Microcontrollers have very idiosyncratic timers
• Parameterized by precision
interface Timer<precision_tag>{ command void startPeriodic(uint32_t dt); event void fired(); command void startOneShot(uint32_t dt); command void stop();
command bool isRunning(); command bool isOneShot(); command void startPeriodicAt(uint32_t t0, uint32_t dt); command void startOneShotAt(uint32_t t0, uint32_t dt); command uint32_t getNow(); command uint32_t gett0(); command uint32_t getdt();}
June 2008 WEI L4 - TinyOS Prog 18
TinyOS Directory Structure
• tos/system/ - Core TinyOS components. This directory's
– components are the ones necessary for TinyOS to actually run.
• tos/interfaces/ - Core TinyOS interfaces, including– hardware-independent abstractions. Expected to be heavily used not
just by tos/system but throughout all other code. tos/interfaces should only contain interfaces named in TEPs.
• tos/platforms/ - code specific to mote platforms, but chip-independent.
• tos/chips/***/ - code specific to particular chips and to chips on particular platforms.
• tos/lib/***/ - interfaces and components which extend the usefulness of TinyOS but which are not viewed as essential to its operation.
• apps/, apps/demos, apps/tests, apps/tutorials.
June 2008 WEI L4 - TinyOS Prog 19
Kernel Overlay for this course
• Trunk– Kernel
» Include
» Interfaces
» Lib
» Make
» Src
» Tools
– TOS: TinyOS code that we will work with
» Drivers – abstractions of phyisical hardware• Epic
• Telosb
» Lib – Useful serves
» App*
– Binaries – precompiled tinyos Apps
– Unix
June 2008 WEI L4 - TinyOS Prog 20
Timers
• Timers are a fundamental element of Embedded Systems– Microcontrollers offer a wide range of different hardware features
– Idiosyncratic
• Logically Timers have – Precision- unit of time the present
– Width - # bits in the value
– Accuracy- how close to the precision they obtain
• TEP102 defines complete TinyOS timer architecture
• Direct access to low-level hardware
• Clean virtualized access to application level timers
#include "Timer.h“
…typedef struct { } TMilli; // 1024 ticks per second typedef struct { } T32khz; // 32768 ticks per secondtypedef struct { } TMicro; // 1048576 ticks per second
June 2008 WEI L4 - TinyOS Prog 21
Example – multiple virtual timers#include "Timer.h"
module Blink3M{ uses interface Timer<TMilli> as Timer0; uses interface Timer<TMilli> as Timer1; uses interface Timer<TMilli> as Timer2; uses interface Leds; uses interface Boot;}implementation{ event void Boot.booted() { call Timer0.startPeriodic( 250 ); call Timer1.startPeriodic( 500 ); call Timer2.startPeriodic( 1000 ); }
event void Timer0.fired() { call Leds.led0Toggle(); } event void Timer1.fired() { call Leds.led1Toggle(); } event void Timer2.fired() { call Leds.led2Toggle(); }}
June 2008 WEI L4 - TinyOS Prog 22
Composition
• Our event-driven component, Blink, may be built directly on the hardware
– For a particular microcontroller on a particular platform
• or on a simple layer for a variety of platforms
• or on a full-function kernel
• Or it may run in a simulator on a PC,
• Or…
• As long as it is wired to components that provide the interfaces that this component uses.
• And it can be used in a large system or application
June 2008 WEI L4 - TinyOS Prog 23
Configuration
• Generic components create service instances of an underlying service. Here, a virtual timer.
• If the interface name is same in the two components, only one need be specified.
configuration BlinkAppC{}implementation{ components MainC, BlinkM, LedsC; components new TimerMilliC() as Timer;
BlinkM -> MainC.Boot; BlinkM.Leds -> LedsC; BlinkM.Timer0 -> Timer.Timer;}
BlinkM
Timer0Boot Leds
MainCBoot
LedsC
Leds
Timer
Timer
BlinkAppC
June 2008 WEI L4 - TinyOS Prog 24
A Different Configuration
• Same module configured to utilize a very different system substrate.
configuration blinkC{}
implementation{ components blinkM; components MainC; components Kernel;
blinkM.Boot -> Kernel.Boot; blinkM.Leds -> Kernel.Leds; components new TimerMilliC(); blinkM.Timer0 -> TimerMilliC.Timer;}
BlinkM
Timer0Boot Leds
TimerMillic
Timer
BlinkC
Kernel
Boot Leds
June 2008 WEI L4 - TinyOS Prog 25
Execution Behavior
• Timer interrupt is mapped to a TinyOS event.– Handled in a safe context
• Performs simple operations.
• When activity stops, entire system sleeps– In the lowest possible sleep state
• Never wait, never spin. Automated, whole-system power management.
June 2008 WEI L4 - TinyOS Prog 26
Module state
• Private scope• Sharing through
explicit interface only!– Concurrency,
concurrency, concurrency!
– Robustness, robustness, robustness
• Static extent• HW independent type
– unlike int, long, char
module BlinkC {
uses interface Timer<TMilli> as Timer0;
uses interface Leds;
users interface Boot;
}
implementation
{
uint8_t counter = 0;
event void Boot.booted()
{
call Timer0.startPeriodic( 250 );
}
event void Timer0.fired()
{
counter++;
call Leds.set(counter);
}
}
June 2008 WEI L4 - TinyOS Prog 27
TinyOS / NesC Platform Independent Types
• Common numeric types
• Bool, …
• Network Types– Compiler does the grunt work to map to canonical form
http://nescc.sourceforge.net
June 2008 WEI L4 - TinyOS Prog 28
Events• Call commands
• Signal events
• Provider of interface handles calls and signals events
• User of interface calls commands and handles signals
module BlinkM {
uses interface Timer<TMilli> as Timer0;
uses interface Leds;
uses interface Boot;
provides interface Notify<bool> as Rollover;
}
implementation
{
uint8_t counter = 0;
event void Boot.booted()
{ call Timer0.startPeriodic( 250 ); }
event void Timer0.fired()
{
counter++;
call Leds.set(counter);
if (!counter) signal Rollover.notify(TRUE);
}
}
BlinkM
Timer0Boot Leds
Rollover
Notify
June 2008 WEI L4 - TinyOS Prog 29
Examples - Event-Driven Execution
Hardware
Phy
Link
Network
Transport
HplSignal
RadioFlash MCU
Ports ADCTimers
Sof
twar
e
Kernel
HTTP – application protocol
Web Server Application
Drivers
Data Presentation
Hardware
Phy
Link
Network
Transport
HplSignal
RadioFlash MCU
Ports ADCTimers
Sof
twar
e
Kernel
HTTP – application protocol
Web Server Application
Drivers
Data Presentation
Start
Timer Fire
TCP
Bind
recv
Start
Service request
June 2008 WEI L4 - TinyOS Prog 30
Split-Phase Operations
• For potentially long latency operations– Don’t want to spin-wait, polling for completion– Don’t want blocking call - hangs till completion– Don’t want to sprinkle the code with explicit sleeps and yields
• Instead,– Want to service other concurrent activities will waiting– Want to go sleep if there are none, and wake up upon
completion
• Split-phase operation– Call command to initiate action– Subsystem will signal event when complete
• The classic concurrent I/O problem, but also want energy efficiency.
– Parallelism, or sleep.– Event-driven execution is fast and low power!
June 2008 WEI L4 - TinyOS Prog 31
Examples/* Power-hog Blocking Call */
if (send() == SUCCESS) {
sendCount++;
}
/* Split-phase call */
// start phase
…
call send();
…
}
//completion phase
void sendDone(error_t err) {
if (err == SUCCESS) {
sendCount++;
}
}
/* Programmed delay */
state = WAITING;
op1();
sleep(500);
op2();
state = RUNNING
state = WAITING;
op1();
call Timer.startOneShot(500);
command void Timer.fired() {
op2();
state = RUNNING;
June 2008 WEI L4 - TinyOS Prog 32
Examples - Split-Phase
Hardware
Phy
Link
Network
Transport
HplSignal
RadioFlash MCU
Ports ADCTimers
Sof
twar
e
Kernel
HTTP – application protocol
Web Server Application
Drivers
Data Presentation
Hardware
Phy
Link
Network
Transport
HplSignal
RadioFlash MCU
Ports ADCTimers
Sof
twar
e
Kernel
HTTP – application protocol
Web Server Application
Drivers
Data Presentation
Sample
Ready
Read
ReadDone
June 2008 WEI L4 - TinyOS Prog 33
Sensor Readings
• Sensors are embedded I/O devices– Analog, digital, … many forms with many interfaces
• To obtain a reading– configure the sensor
» and/or the hardware module it is attached to, • ADC and associated analog electronics
• SPI bus, I2C, UART
– Read the sensor data
• TinyOS 2.x allows applications to do this in a platform-independent manner
June 2008 WEI L4 - TinyOS Prog 34
Read Interface
• Split-phase data acquisition of typed values
• Flow-control handshake between concurrent processed– Hardware or software
• $tinyOS-2.x/tos/interface/read.nc
interface Read<val_t> {
/* Initiates a read of the value.
* @return SUCCESS if a readDone() event will eventually come back.
*/
command error_t read();
/**
* Signals the completion of the read().
*
* @param result SUCCESS if the read() was successful
* @param val the value that has been read
*/
event void readDone( error_t result, val_t val );
}
June 2008 WEI L4 - TinyOS Prog 35
Example#include "Timer.h"module SenseM{ uses { interface Boot; interface Leds; interface Timer<TMilli>; interface Read<uint16_t>; }}implementation{ #define SAMPLING_FREQUENCY 100 event void Boot.booted() { call Timer.startPeriodic(SAMPLING_FREQUENCY); }
event void Timer.fired() { call Read.read(); }
event void Read.readDone(error_t result, uint16_t data) { if (result == SUCCESS){ call Leds.set(data & 0x07);} }}
• What does it sense?
June 2008 WEI L4 - TinyOS Prog 36
Temp example configuration
configuration TempDispAppC { } implementation { components SenseM, MainC, LedsC, new TimerMilliC() as Timer, TempC ;
SenseM.Boot -> MainC; SenseM.Leds -> LedsC; SenseM.Timer -> TimerMilliC; SenseM.Read -> TempC;}
SenseM
Timer0Boot Leds
MainCBoot
LedsC
Leds
Timer
Timer
TempDispAppC
Read
TempC
Read
June 2008 WEI L4 - TinyOS Prog 37
Concurrency
• Commands and event glue together concurrent activities
• Hardware units operate on parallel– Commands used to initiate activity
– Events used to signal completion, etc.
• System software components are very similar– But they don’t have dedicated hardware to keep working on
the command.
– Tasks are used for that
• Decouple execution and leave room for juggling– Use lots of little tasks to keep things flowing
• Preempted by async events (interrupts)– Not other tasks
June 2008 WEI L4 - TinyOS Prog 38
Tasks – Crossing the Asynch / Synch Boundary
module UserP { provides interface Button; uses interface Boot; uses interface Msp430Port as Pin; uses interface Msp430PortInterrupt as PinInt;}
implementation { event void Boot.booted() { call Pin.setDirection(0); /* Input */ call PinInt.edge(1); /* Rising edge, button release */ call PinInt.enable(1); /* Enable interrupts */ }
task void fire() { signal Button.pressed(); /* Signal event to upper layers */ } async event void PinInt.fired() { post fire(); }}
June 2008 WEI L4 - TinyOS Prog 39
Examples - Tasks
Hardware
Phy
Link
Network
Transport
HplSignal
RadioFlash MCU
Ports ADCTimers
Sof
twar
e
Kernel
HTTP – application protocol
Web Server Application
Drivers
Data Presentation
Hardware
Phy
Link
Network
Transport
HplSignal
RadioFlash MCU
Ports ADCTimers
Sof
twar
e
Kernel
HTTP – application protocol
Web Server Application
Drivers
Data Presentation
Sample
Ready
fired
readDone
serviceReqnotify
fired
June 2008 WEI L4 - TinyOS Prog 40
Tasks• Need to juggle many potentially
bursty events.• If you cannot get the job done
quickly, record the parameters locally and post a task to do it later.
• Tasks are preempted by lower level (async) events.
– Allow other parts of the system to get the processor.
– Without complex critical semaphores, critical sections, priority inversion, schedulers, etc.
/* BAD TIMER EVENT HANDLER */
event void Timer0.fired() {
uint32_t i;
for (i = 0; i < 400001; i++) {
call Leds.led0Toggle();
}
}
Hardware
Interrupts
even
ts
commands
Tasks
/* Better way to do a silly thing */
task void computeTask() {
uint32_t i;
for (i = 0; i < 400001; i++) {}
}
event void Timer0.fired() {
call Leds.led0Toggle();
post computeTask();
}
June 2008 WEI L4 - TinyOS Prog 41
Uses of tasks (???)
• High speed sampling
• Filtering
• Queueing
• Smoothing
• Detection
• Classification
• …
June 2008 WEI L4 - TinyOS Prog 42
Networking
• Traditional TinyOS communication is based on active messages
– Send a structure to <node,handlerId>
– Receive is just a network event that signals the hander with a message
• Earliest TinyOS (0.3) was essentially moving Active Messages and the Threaded Abstract Machine (TAM) from the MPP domain to emdedded devices.
– Parallel Machine communication is internal!
– Sensor networks are networks, not distributed computers
– They connect to OTHER NETWORKS
• Active Messages covered in Appendix– But I don’t use them any more
June 2008 WEI L4 - TinyOS Prog 43
Transit Network (IP or not)
Access point - Base station - Proxy
Sensor Patch
Patch Network
Data Service
Intranet/Internet (IP)
Client Data Browsingand Processing
Sensor Node
GatewayGateway
Verification links
Other information sources
Sensor Node
Canonical SensorNet Network Architecture
June 2008 WEI L4 - TinyOS Prog 44
Typical IP Network
InternetInternet
ISP
Company Router / Firewall
externallyaccessible hosts
DMZ
WiFiWiFi
Internal Private networks
ethernet
serial linesleased linkspoint-point links
internally accessible hosts
Stand-alone networks
inaccessiblehosts
WiFIWiFI
External networksVPNtunnels
June 2008 WEI L4 - TinyOS Prog 45
TinyOS 2x Embedded IP Architecture
GPIO Pins
Ext. INT
ADCSPI, i2c,UART
Low-Power 802.15.4
Vir
tua
lm
s T
imer
s Timer
RTCS
che
dul
er
Fla
shS
tora
ge
arbiters
Pw
r M
gr
UDP/TCP L4Basic Health &Mgmt Services Basic
ConfigurationServices
Sensor Drivers
OTAIP 6LowPAN L2
IP route L3
Higher Level Embedded Web Services
June 2008 WEI L4 - TinyOS Prog 46
WSNs in an IP context
InternetInternet
Stand-alone embedded networks
monitoring devices
ad hocembedded
network
controllers& analytics
IP-basedembedded
network
monitoring devices
ad hocembedded
network
controllers& analytics
IP-basedembedded
network
Router /Firewall
gatewaycomputer
IP-basedcorporatenetworks
InternetInternet
IP-basedcorporatenetworks
Internally connected embedded networks
June 2008 WEI L4 - TinyOS Prog 47
Issues in Communication Abstraction• Names
– What are they?– What do they mean? What is their scope?– How are they allocated?– How are they translated into useful properties
» Address? Physical Resource?
• Storage– Transmit
» When can it be reused? How do you know? What do you do when it is full?
– Receive» When is it allocated? Reclaimed? By whom? What
happens when it overflows?– Asynchronous event
» How do you know that something has arrived?
• Many more issues in actually performing the requested communication
June 2008 WEI L4 - TinyOS Prog 48
Answers: Naming
• TinyOS Active Messages– TOS_local_addr, 16 bits, only within “a network”, allocated at
program download time– Scope limited to TOS_group, within PAN, Channel, and
physical extent.– The standards that try to do it all with IEEE 802.15.4 16 bit
short address are not much better
• IP Architecture– Link name: IEEE 802.15.4 => EUID64 & SA16
» EUID64 globally unique, SA16 assigned to be unique over the PAN
– Net name: IP address» Prefix | Interface Id» Must be unique within routability extent» Several IP address: Link Local, Global, Multicast, …
- Service name: Port- Hostname Translated to IP by DNS
June 2008 WEI L4 - TinyOS Prog 49
Answers: Storage
• TinyOS Active Messages– Sender app allocates send buffer, OS owns it till sendDone
event
– OS provides App with recv buffer, app must return it or a replacement
• BSD Sockets– Sender app allocate buffer, copied to kernel on send
– Receiver allocates buffer and passes pointer to kernel, kernel copies
– Additional sets of buffer managed within the kernel
• TinyOS Sockets ???
June 2008 WEI L4 - TinyOS Prog 50
UDP Interface
• Wiring to a UDP interface is enough for sendto• Standard Unix sockaddr_in6_t• Bind – associates the component that uses the interface with the port
– Starts receiving whatever datagrams come in on it
• Sendto sends a datagram from a buf to a IP destination– Neighbor, intra-PAN, inter-network (wherever it needs to go!)– Linklocal address is 1-hop neighbor– Pan-wide routable prefix– Error when not in network or overrun transmit resources
• Recvfrom gets a buffer with a datagram and metadata about it• Able to fill the 15.4 frame without knowing details of header
compression
interface Udp { command error_t bind( uint16_t port ); command uint16_t getMaxPayloadLength( const sockaddr_in6_t *to ); command error_t sendto( const void *buf, uint16_t len, const sockaddr_in6_t *to ); event void recvfrom( void *buf, uint16_t len, sockaddr_in6_t *from,
link_metadata_t *metadata );}
June 2008 WEI L4 - TinyOS Prog 51
And what about TCP
• UDP is a datagram transport– Essentially the same as AM
– Fits naturally in event-driven model
– Can use NesC platform independent data structure to have unambiguous packet formats without hton / ntoh error prone bit twiddling.
• But TCP is a stream protocol…
June 2008 WEI L4 - TinyOS Prog 52
TCP Interface
• Transitions of the TCP protocol reflected as events• Recv per segment• Send is NOT SPLIT PHASE !!!
interface Tcp { command error_t bind(uint16_t port, uint8_t *buf, uint16_t bufsize); event bool accept( sockaddr_in6_t *to ); command error_t connect( const sockaddr_in6_t *to, uint8_t *buf,
uint16_t bufsize ); event void connected(); command error_t send( const void *buf, uint16_t len ); event void acked(); event uint16_t recv( void *buf, uint16_t len ); command error_t close( bool force ); event void closed(); }
June 2008 WEI L4 - TinyOS Prog 53
Example TinyOS Service Architecture
HardwareAbstraction
Layer
Basic OSinterface
ServiceAPI
Flash Radio / Uart Sensor/Actuator
Volumes Buses & ADCsLinks
File
s
Logs
RF
Ligh
t
Sou
nder
Oth
er
Com
man
ds
Att
ribut
es
Eve
nts
Dis
cove
ry
Blo
cks
OT
A p
rogr
am
NetworkM
essa
ges
Hardware
Man
agem
ent
&
Pw
r
Application
June 2008 WEI L4 - TinyOS Prog 54
Permanent Data Storage
• TinyOS 2.x provides three basic storage abstractions: – small objects,
– circular logs, and
– large objects.
• also provides interfaces the underlying storage services and components that provide these interfaces.
• Flash devices– ST Microelectronics M25Pxx family of flash memories used in the
Telos family of motes (tos/chips/stm25p)
– Atmel AT45DB family of flash memories used in the Mica2/MicaZ motes (tos/chips/at45b)
– Special pxa271p30 versions for the Intel Mote2 contributed by Arch Rock. (tos/platforms/intelmote2)
• TEP103
June 2008 WEI L4 - TinyOS Prog 55
Storage Interfaces and Components
• Interfaces– BlockRead
– BlockWrite
– Mount
– ConfigStorage
– LogRead
– LogWrite
– Storage.h
Components– ConfigStorageC - Configuration Data
» calibration, identity, location, sensing configuration, ..
– LogStorageC
» data
– BlockStorageC
» Code, …
June 2008 WEI L4 - TinyOS Prog 56
Volumes
• TinyOS 2.x divides a flash chip into one or more fixed-sized volumes that are specified at compile-time using an XML file.
June 2008 WEI L4 - TinyOS Prog 57
Example – blink period config
Define config storage object
chipname.xml file
Added to the TinyOS configuration
New interfaces for the module
Wire to the new interfaces
June 2008 WEI L4 - TinyOS Prog 58
On boot – Mount and Read
June 2008 WEI L4 - TinyOS Prog 59
Config data – done, write, commit
June 2008 WEI L4 - TinyOS Prog 60
Network Embedded Systems
HardwareAbstraction
Layer
Basic OSinterface
ServiceAPI
Flash Radio / Uart Sensor/Actuator
Volumes Buses & ADCsLinks
File
s
Logs
RF
Ligh
t
Sou
nder
Oth
er
Com
man
ds
Att
ribut
es
Eve
nts
Dis
cove
ry
Blo
cks
OT
A p
rogr
am
NetworkM
essa
ges
Hardware
Man
agem
ent
&
Pw
r
Application
June 2008 WEI L4 - TinyOS Prog 61
IP/6LoWPAN “Kernel Component”component KernelC { provides interface Boot; provides interface Timer<TMilli> as TimerMilli[ uint8_t id ]; provides interface TaskBasic[ uint8_t id ]; provides interface GlobalTime<TMilli>; /* Global Time – NTP */ provides interface LocalIeeeEui64; /* EUI MAC Address */ provides interface Udp as Udp0; /* Udp */ provides interface Udp as Udp1; provides interface Tcp as Tcp0; /* Tcp */ provides interface Tcp as Tcp1; provides interface IPv6Addresses; /* IPv6 Utility Functions */ provides interface IPv6Notify; /* MCU generated interrupts */ provides interface HplSignal as HplSignalAdc12; provides interface HplSignal as HplSignalPort1; provides interface HplSignal as HplSignalPort2; provides interface HplSignal as HplSignalTimerA0; provides interface HplSignal as HplSignalTimerA1; provides interface HplSignal as HplSignalTimerB0; provides interface HplSignal as HplSignalTimerB1;}
June 2008 WEI L4 - TinyOS Prog 62
TinyOS IPv6 Network Kernel
ActuatorActuatorSensorsSensorsTimer FlashRadio Sensor Actuator
• Network Kernel– Manages communication and storage
– Scheduler (decides when to signal events)
IPv6 Network Kernel DriverDriverDriverDriverDriver Driver
Application
June 2008 WEI L4 - TinyOS Prog 63
Network Embedded Systems
HardwareAbstraction
Layer
Basic OSinterface
ServiceAPI
Flash Radio / Uart Sensor/Actuator
Volumes Buses & ADCsLinks
Con
fig
Logs
RF
Ligh
t
Sou
nder
Oth
er
Blo
cks
OT
A
6LoWPAN Network
Hardware
Man
agem
ent
&
Pw
r
Application
ICMP / UDP / TCP
Sys
tat
nets
tat
Ech
o
Our kernelboundary
June 2008 WEI L4 - TinyOS Prog 64
TinyOS Concepts not yet covered
• Generic Components– Generic modules and generic configurations
– Multiple instances
– Type polymorphism
– Storage and configuration
– Discovery
• Parameterized interfaces– Index array of interfaces to other components
– Dispatch, services
– Virtualization
• Platform independent structs– Replace xdr and all that
– Eliminate error prone bit twiddling
June 2008 WEI L4 - TinyOS Prog 65
Discussion
June 2008 WEI L4 - TinyOS Prog 66
Traditional TinyOS Active Messages
June 2008 WEI L4 - TinyOS Prog 67
Sensor NETWORK
• We have a flexible, low-power, event-driven sensor / actuator platform.
• Let’s add the network
• Send / Receive of information
• Dispatching incoming data to computation processes that will handle it.
– Automate in a systematic fashion
• Parsing the packet– Define the structure, let the compiler do the work.
– Handler knows what it should be receiving
June 2008 WEI L4 - TinyOS Prog 68
message_t structure• Packet - Provides the basic accessors for the message_t
abstract data type. This interface provides commands for clearing a message's contents, getting its payload length, and getting a pointer to its payload area.
• Send - Provides the basic address-free message sending interface. This interface provides commands for sending a message and canceling a pending message send. The interface provides an event to indicate whether a message was sent successfully or not. It also provides convenience functions for getting the message's maximum payload as well as a pointer to a message's payload area.
• Receive - Provides the basic message reception interface. This interface provides an event for receiving messages. It also provides, for convenience, commands for getting a message's payload length and getting a pointer to a message's payload area.
• PacketAcknowledgements - Provides a mechanism for requesting acknowledgements on a per-packet basis.
• RadioTimeStamping - Provides time stamping information for radio transmission and reception.
June 2008 WEI L4 - TinyOS Prog 69
Active Messages - Dispatching messages to their handlers• AM type – dispatch selector
– Frame_type at link layer
– IP Protocol Field at network layer
– Port at Transport layer
• AM_address
• AMPacket - Similar to Packet, provides the basic AM accessors for the message_t abstract data type. This interface provides commands for getting a node's AM address, an AM packet's destination, and an AM packet's type. Commands are also provides for setting an AM packet's destination and type, and checking whether the destination is the local node.
• AMSend - Similar to Send, provides the basic Active Message sending interface. The key difference between AMSend and Send is that AMSend takes a destination AM address in its send command.
June 2008 WEI L4 - TinyOS Prog 70
Communication Components
• AMReceiverC - Provides the following interfaces: Receive, Packet, and AMPacket.
• AMSenderC - Provides AMSend, Packet, AMPacket, and PacketAcknowledgements as Acks.
• AMSnooperC - Provides Receive, Packet, and AMPacket.
• AMSnoopingReceiverC - Provides Receive, Packet, and AMPacket.
• ActiveMessageAddressC - Provides commands to get and set the node's active message address. This interface is not for general use and changing the a node's active message address can break the network stack, so avoid using it unless you know what you are doing.
June 2008 WEI L4 - TinyOS Prog 71
HAL to HIL
• Since TinyOS supports multiple platforms, each of which might have their own implementation of the radio drivers, an additional, platform-specific, naming wrapper called ActiveMessageC is used to bridge these interfaces to their underlying, platform-specific implementations. ActiveMessageC provides most of the communication interfaces presented above.
• Platform-specific versions of ActiveMessageC, as well the underlying implementations which may be shared by multiple platforms (e.g. Telos and MicaZ) include:
– ActiveMessageC for the intelmote2, micaz, telosa, and telosb are all implemented by CC2420ActiveMessageC.
– ActiveMessageC for the mica2 platform is implemented by CC1000ActiveMessageC.
– ActiveMessageC for the eyesIFX platform is implemented by Tda5250ActiveMessageC.
June 2008 WEI L4 - TinyOS Prog 72
tos/types/message.h.
• Link level concept used throughout the TinyOS research community and industry.
• How does this move forward to IP/WSN?
typedef nx_struct message_t {
nx_uint8_t header[sizeof(message_header_t)];
nx_uint8_t data[TOSH_DATA_LENGTH];
nx_uint8_t footer[sizeof(message_header_t)];
nx_uint8_t metadata[sizeof(message_metadata_t)];
} message_t;
June 2008 WEI L4 - TinyOS Prog 73
Sending a packet to the neighborhood#include <Timer.h>#include "BlinkToRadio.h"
module BlinkToRadioC { uses interface Boot; uses interface Leds; uses interface Timer<TMilli> as Timer0; uses interface Packet; uses interface AMPacket; uses interface AMSend; uses interface Receive; uses interface SplitControl as AMControl;}implementation { uint16_t counter; message_t pkt; bool busy = FALSE;
event void Boot.booted() { call AMControl.start(); } event void AMControl.startDone(error_t err) { if (err == SUCCESS) { call Timer0.startPeriodic(TIMER_PERIOD_MILLI); } }
June 2008 WEI L4 - TinyOS Prog 74
Sending a packet to the neighborhood event void Timer0.fired() { counter++; if (!busy) { BlinkToRadioMsg* btrpkt = (BlinkToRadioMsg*)(call Packet.getPayload(&pkt, NULL)); btrpkt->nodeid = TOS_NODE_ID; btrpkt->counter = counter; if (call AMSend.send(AM_BROADCAST_ADDR, &pkt, sizeof(BlinkToRadioMsg)) == SUCCESS) { busy = TRUE; } } }
event void AMSend.sendDone(message_t* msg, error_t err) { if (&pkt == msg) { busy = FALSE; } }
event message_t* Receive.receive(message_t* msg, void* payload, uint8_t len){ if (len == sizeof(BlinkToRadioMsg)) { BlinkToRadioMsg* btrpkt = (BlinkToRadioMsg*)payload; call Leds.set(btrpkt->counter & 0x7); } return msg; }}
June 2008 WEI L4 - TinyOS Prog 75
Receive – a network event
• Service the incoming message– Automatically dispatched by type to the handler
• Return the buffer– Or if you want to keep it, you need to return another one.
• Overlay a network type structure on the packet so the compiler does the parsing.
event message_t* Receive.receive(message_t* msg, void* payload, uint8_t len) {
if (len == sizeof(BlinkToRadioMsg)) {
BlinkToRadioMsg* btrpkt = (BlinkToRadioMsg*)payload;
call Leds.set(btrpkt->counter);
}
return msg;
}
enum { AM_BLINKTORADIO = 6, };
typedef nx_struct BlinkToRadioMsg {
nx_uint16_t nodeid;
nx_uint16_t counter;
} BlinkToRadioMsg;
June 2008 WEI L4 - TinyOS Prog 76
Communication-Centric Operating Systems Design Elements• Packets cross between different kinds of machines
– Small Endian vs Large Endian– Representation of data types – int, long, char, …
• Protocols have specific message formats Network Types Overlay network type struct on the packet and let the compiler do the
shifting, masking, and endian conversion Eliminate error-prone parsing code
• Protocols are realized by state machines that advance on message events
– Make external communication events as simple as internal events
• Network stacks involve dispatching on types at several levels
– Frame type, Protocol Number, port number– Provide support for dispatch
• Packet events are intrinsically connected with buffer management
– Make is a robust and simple as possible.
June 2008 WEI L4 - TinyOS Prog 77
AM_ID – port number#include <Timer.h>
#include "BlinkToRadio.h"
configuration BlinkToRadioAppC {
}
implementation {
components MainC, LedsC;
components BlinkToRadioC as App;
components new TimerMilliC() as Timer0;
components ActiveMessageC;
components new AMSenderC(AM_BLINKTORADIO);
components new AMReceiverC(AM_BLINKTORADIO);
App.Boot -> MainC;
App.Leds -> LedsC;
App.Timer0 -> Timer0;
App.Packet -> AMSenderC;
App.AMPacket -> AMSenderC;
App.AMControl -> ActiveMessageC;
App.AMSend -> AMSenderC;
App.Receive -> AMReceiverC;
}
June 2008 WEI L4 - TinyOS Prog 78
Indexed interfaces for dispatch
• Clients & Applications have individual view
• Provider has global view
Active Message
Network Stack Implementation
Hardware
SVC x SVC y SVC z SVC w
June 2008 WEI L4 - TinyOS Prog 79
Active Messages
• Concept – message carries unique identifier of handler that is to process it
– Directly off the link
– Compile time formation and parsing
» It is a Structure
– Bounded storage
» Consume the receive buffer immediately
• Has been the central networking abstraction in all version of TinyOS
– Used for all the multihop routing protocols, …
• Link frame derived from SW usage
• TCP/UDP / IP / 6LoWPAN will cause first serious re-examination of Message_T
June 2008 WEI L4 - TinyOS Prog 80
Parameterized Wiring
• Active Message clients wire to distinct AM_id– Unique ID of the service handler
• Many other system services provided to multiple clients (independently) but do not need a “protocol id”
• NesC “Unique” allocates new interfaces at compile time
– Relative to a key set
– Whole system compilation => tight resource allocation
June 2008 WEI L4 - TinyOS Prog 81
Wiring Examples ???