View
4
Download
0
Category
Preview:
Citation preview
TinyOS
Ankit GuptaKaran ManglaLakshya GoelNitin Jain
Overview of TinyOS
Industrial motivations behind TinyOSWhat is TinyOS?TinyOS vs. traditional OSTinyOS design modelsTinyOS structure
Industrial Motivations behind TinyOSLow power wireless communication devices
Particularly wireless networked sensors;Physical limitations
Computation abilityMemoryPower supply High-level concurrency
What is TinyOS?
An event-based operating system designed for wireless networked sensors.Designed to support concurrency-intensive operations required by networked sensors with minimal hardware requirements.Developed by the EECS Department of U.C. Berkeley.
C and Assembly languagesSource code size: 500KB, 16KB commented lines
TinyOS vs. Traditional OS
Special purpose (not general purpose)Resource constraint
4MHz ATMEL 8535 8bit MCU 512 byte RAM and 8K Flash
No dedicated I/O controller (missed deadline means loss data)One program at one time (no multi-programming)Thin-threads (tasks)
TinyOS Design Models
Component-based model (modularity)Simple functions are incorporated in components with clean interfaces;Complex functions can be implemented by composing components.
Event-based modelInteract with outside by events (no command shell)There are two kinds of events for TinyOS:
External events : Clock events and message events;Internal events triggered by external events.
TinyOS Structure
CommunicationActuating Sensing Communication
Application
Main (scheduler)
Hardware Abstractions (ADC, CLOCK, I2C, LEDS, PHOTO, UART, RFM)
Consists of a scheduler and a graph of components.
Outline
Component StructureConcurrency ModelTinyOS schedulersMemory Model
TinyOS Component StructureA TinyOS Component:
Frame (storage)Tasks (computation & concurrency)
Time consuming computations;Have no hard real-time requirements;
Commands and events (interfaces)
Layout of an interface
Can use other interfacesProvide events
To be coded by the interface userProvides commands
Coded by the interface provider
Tasks
Perform longer operationsCan be preempted by hardware event handler but not by other tasksDeclaration: task void <name>() { ... }Posting a task: post taskname();Done from within command, event or another task
Commands
Function call across component boundarycause action to be initiated bounded amount of work
cannot blockalways return status (0 => error)
component can refuse to perform command
share call stack and execution contextaccess to local framecommands may post tasks or call commands
Events
Upcall to notify action has occuredbounded (and small) amount of workaccess local frame, shares stack
Lowest-level events triggered by hardware interrupts
hardware abstraction components perform critical section and enable interrupts
May signal events or call commandsEvents may call commands
Concurrency Model
Two threads of executionTasksHardware Event Handler – handles context switch for multiple level interrupts
Both preemptable by asynchronous codePossibility of race condition
NesC warns while compilingMethod of making a block atomic allowed
Concurrency Model (cont.)
AtomicityDisable hardware interrupt handling thread while atomic code is running
TinyOS schedulers (Cont.)Task scheduler
Implement FIFO scheduler in sched.cData structure
Circular queue TOS_sched_entry_T TOS_queue[MAX_THREADS];
FunctionsTOS_sched_init();TOS_empty();TOS_post();TOS_schedule_task();
TOS_queue
Any Component (e.g. SHELL)
MAIN ComponentSchedule next task in queue (TOS_schedule_task)
Post task into queue (TOS_post)
Memory Model
STATIC memory(except msg buffers)No heap(malloc)No function pointers
Global variables Available on a per-frame basis
Local variables Saved on the stackDeclared within a method
Msg buffers allocated statically by components,nut shared dynamically by ownership discipline
Memory Requirement
One task at a time – non preemptive kernelNo local variables in eventsBuffers for active messagingStack copy not with each task – reduce memory requirement – hence non preemptive
Active Messages
What are active messages?
Active Messages (AM) is a simple, extensible paradigm for message-based communication.Used in parallel and distributed computing systems .Centered on the concept of integrating communication and computation, as well as matching communication primitives to hardware capabilities.
Why Not Standard Messaging Protocols ?
Low level networking protocols of legacy stacks typically require :
Kilobytes of memory at a minimum And performance is dependent on a fast processing component.
Routing protocols implemented above these are : ComplexPlace bandwidth demands that become unatenable for links with kilobits per second throughput.
Cont.
Sockets - Not well suited to the constrained environment of tiny network devices. Interfaces centered on “stop and wait”semantics do not meet the power and agility requirements of these small devices such as Motes.
Why Active Messaging ?
Fundamental fit between the event based nature of network sensor applications and the event based primitives of the ActiveMessages communication.The lightweight architecture of Active Messages can be leveraged to balance the need for an extensible communication framework while maintaining efficiency and agility. Event based handler invocation model allows application developers to avoid busy-waiting for data to arrive and allows the system to overlap communication with other activities such as interacting with sensors or executing other applications.Event centric nature of Active Messages makes it a natural fit for these devices.
Active Messaging Fundamentals
tos/system/AMStandard.ncLayers Involved
Specifying message data to sendSpecifying receiver’s addressDetermining when message’s memory can be reusedBuffering Incoming messageProcessing Message
Handler ID required to be specified
A TinyOS Application Example
CommunicationLedsC
BLINK
Main (scheduler)
Hardware Abstractions (CLOCK and LEDS)
TimerM
HPLclock
The above application is used to toggle a Led on the mote at fixed intervals.
This is a configuration file which provides the top-level wiring of the applicationMain is a special component which is used to initialize the system.The wiring consist of joining interfaces required by certain components to those provided by other components that are being used.
Blink.ncconfiguration Blink {}implementation {
components Main, BlinkM, SingleTimer, LedsC;Main.StdControl -> SingleTimer.StdControl;Main.StdControl -> BlinkM.StdControl;BlinkM.Timer -> SingleTimer.Timer;BlinkM.Leds -> LedsC;
}
RealMain.ncmodule RealMain {
uses {command result_t hardwareInit();interface StdControl;interface Pot;
}}implementation{
int main() __attribute__ ((C, spontaneous)) {call hardwareInit();call Pot.init(10);TOSH_sched_init();
call StdControl.init();call StdControl.start();__nesc_enable_interrupt();
while(1) {TOSH_run_task();
}}
}
The above component is a module file ,which are used to define implementations of components.It is used to initialize all application.Its Std Control interface is mapped onto that used by Main and hence when it utilizes this interface it communicates with all components that are connected to the Main component. Most components have a Std Control interface as this is what initializes every component.When nesC compiles the application into C the main function involves one call to Std Contol init followed by a call to Std Control start to start the application. This is then followed by starting the task scheduler.This function also consists of calls to Initialize the hardware and power settings of the mote. These calls are wired to lower levelcomponents which directly interface with the device controllers for the system.
Implementation of Main Component
BlinkM.ncmodule BlinkM {
provides {interface StdControl;
}uses {
interface Timer;interface Leds;
}}implementation {command result_t StdControl.init() {
call Leds.init(); return SUCCESS;
}command result_t StdControl.start() {
// Start a repeating timer that fires every 1000msreturn call Timer.start(TIMER_REPEAT, 1000);
}command result_t StdControl.stop() {
return call Timer.stop();}
event result_t Timer.fired(){
call Leds.redToggle();return SUCCESS;
}}
The previous slide gives us the code for the top-level component of the Blink application.As we see it provides an interface Std Control which is provided by all applications which must be initialized as startup.Further we see that it only requires one Timer and one Ledsinterface for this application.The application basically waits for a timer event to signal a given time period after which it toggles its Leds. No tasks are required for this particular application.The LedsC code which we use just runs a function which writes to the register controlling the Leds to toggle the Led when the command Leds.redToggle is called.
TimerM.nctask void signalOneTimer() {
uint8_t itimer = dequeue();if (itimer < NUM_TIMERS)
signal Timer.fired[itimer]();}
task void HandleFire() {uint8_t i; setIntervalFlag = 1;
if (mState) {for (i=0;i<NUM_TIMERS;i++) {
if (mState&(0x1<<i)) {mTimerList[i].ticksLeft -= (mInterval+1) ; if (mTimerList[i].ticksLeft<=2) {
if (mTimerList[i].type==TIMER_REPEAT) {mTimerList[i].ticksLeft += mTimerList[i].ticks;
} else {// one shot timer mState &=~(0x1<<i);
}enqueue(i);
post signalOneTimer();}}}}
adjustInterval();}
async event result_t Clock.fire() {post HandleFire();
return SUCCESS;}
Here we have displayed a portion of the TimerM.nc module which we use in this application.Now the BlinkM module requires a timer event to inform it when to toggle its Leds.The above module file defines a timer component which maintains multiple timers.We see that on receiving an alarm from the clock it checks whichtimer has finished and post a task to signal a timer fired event for that timer.Note that for a single timer we could directly signal the event for timer.fired within Clock.fire which would allow a more real time implementation of the system.However the extra calculations required for allowing multiple timers means that the computation cannot be done inside an event handler and must be posted as a task.
Implementation of the SingleTimer component
HPLclock.ncTOSH_INTERRUPT(SIG_OUTPUT_COMPARE0) {
atomic {if (set_flag) {
mscale = nextScale;nextScale|=0x8;
outp(nextScale, TCCR0);
outp(minterval, OCR0);
set_flag=0;}
}signal Clock.fire();
}Hardware.h#define TOSH_INTERRUPT(signame) \
void signame() __attribute__ ((interrupt, spontaneous, C))
The above codes are platform specific files which define the interface to the actual hardware.HPLclock.nc is a low level component containing code for interfacing with the clock device driver on the mica2 platform.Hardware.h is the file that contains many primitive functions defined in C which can be called by other higher level components.This is the file that varies from implementation to implementation.Let us look at how nesC allows us to define interrupt handlers.
Vector table is predefined to point to interrupt routines with predetermined namesBy using the appropriate name, your routine will be called when the corresponding interrupt occurs The extra code needed to allow context switching is enabled by tagging the interrupt function with __attribute__((interrupt))
Thus we see that the function TOSH_INTERRUPT(signame) can be used to define interrupt handlers.
Hardware Interface of the application
Available Components
Application level Components
Functionality
AM_BEACON.c Application that periodically broadcasts out identity information. On each clock interrupt, it sends out a predetermined packet of information
AM_BOUNCER.c Equivalent to a ping handler. Accepts a packet coming in from the network and responds with a packet sent back to the original sender.
AM_ECHO.c A component that forwards data through a node. Essentially, this is a router for a source based routing algorithm.
Available components
Main level object Functionality
MAIN.c Required component that initializes the system and starts the scheduler. All applications must include this component.
sched.c System Scheduler, must be included in all applications. This is a simple FIFO scheduler that is used to schedule the tasks.
Active messaging layer
AM.c When packet arrives, check address and dispatch message to appropriate message handler.
AM_STANDARD.c Base station with UART forwarding. This component behaves same as AM.c component EXCEPT that if a packet is sent to the address 0x7e, it is directed to UART instead of radio.
Available components
Packet Transport Layer
Functionality
PACKETOBJ.c This component takes a pointer to a byte array to be sent down to the byte level component below it. It hands the bytes down to byte level component one at a time.
CRCPACKETOBJ.c Checks for CRC validity. This component performs same function as basic PACKETOBJ.c component except that it transmits additional two bytes.
UART_PACKET.c This packet level component is almost identical to PACKETOBJ.c component except it sends to UART instead of radio.
Available components
Radio Byte Engine (use one)
Functionality
RADIO_BYTE.c A byte level component used with RFM component. This component accepts bytes from packet layer component, encodes them for transmission, and passes the bits down to the RFM component one at a time. As bits arrive from the radio, it collects the bits together into a byte worth, decodes byte and then sends the decoded byte up to the packet layer.
SEC_DED_RADIO_BYTE.c
Provides Single error correction/Double error detection. Also detects preamble and start symbol detection. Also uses RFM for sending and receiving bits.
Available components
UART Transport Layer
Functionality
RADIO.c This component performs bit level control over the radio. Addtionally, it controls the amount of time per bit.
UART.c Takes bytes 1 at a time and transmits them over UART. When the component is ready to handle another byte, it fires TX_DONE event. When a byte arrives from the UART, the component fires the BYTE_ARRIVAL event.
Lower level device Components
CLOCK.c Signals periodic events. It initialized with the interval with which to fire event and then periodically fires CLOCK_EVENT at that rate.
LEDS.c Controls the outputs of the LED's
Available components
Lower level device components
Functionality
ADC.c Provides A/D support for analog sensors (Asynchronous interface)
MIC.c,PHOTO.c,SOUNDER.c,VOLTAGE.c
Interface to MicrophoneInterface to PhotosensorInterface to Sound DeviceInterface to Voltage sensors
Recommended