Programming in nesC (and TOSSIM)

Slides:



Advertisements
Similar presentations
How to use TinyOS Jason Hill Rob Szewczyk Alec Woo David Culler An event based execution environment for Networked Sensors.
Advertisements

A System Architecture for Tiny Networked Devices
TinyOS Tutorial, Part I Phil Levis et al. MobiSys 2003.
1 Tomás Sánchez López July 9, 2004 Real-time & Embedded Systems Laboratory TinyOS … in deep.
EMS1EP Lecture 4 Intro to Programming Dr. Robert Ross.
NesC Prepared for the Multimedia Networks Group University of Virginia.
Feb 2007WSN Training: First Steps in nesC Programming1 First Steps in TinyOS and nesC Programming Topics  Timer Application: MyApp  Application directory.
1 Lab 3 Objectives  Case study: “Hello world” program on motes  Write you first program on mote.
Sensor Network Platforms and Tools
Overview: Chapter 7  Sensor node platforms must contend with many issues  Energy consumption  Sensing environment  Networking  Real-time constraints.
Mote Programming. 如何 compile 程式  make [re]install. : desired device address : target platform  install vs. reinstall install : compile the application.
TOSSIM A simulator for TinyOS Presented at SenSys 2003 Presented by : Bhavana Presented by : Bhavana 16 th March, 2005.
TinyOS Introduction Advanced Computer Networks. TinyOS Outline  Introduction to the Architecture of TinyOS and nesC  Component Model –Components, interfaces,
Contiki A Lightweight and Flexible Operating System for Tiny Networked Sensors Presented by: Jeremy Schiff.
How to Code on TinyOS Xufei Mao Advisor: Dr. Xiang-yang Li CS Dept. IIT.
Jason Hill, Robert Szewczyk, Alec Woo Spring 2000 TinyOS Operating System for Networked Sensors Networked SensorsSystem Structure Composing Components.
Sample Project Ideas KD Kang. Project Idea 1: Real-time task scheduling in TinyOS EDF in TinyOS 2.x –Description is available at
7/13/2007AIIT Summer Course - D#1 Wireless Embedded Systems and Networking Lab Day 5: Part 1: TinyOS Programming on Open Source Distribution Jaein Jeong.
Programming Motes A TinyOS and TOSSIM Tutorial By: Brent Rood.
A Quick Note on TinyOS Chris Merlin Group Meeting January 21 st, 2009.
Development of a Mica2 Mote Sensor Network Cliff Macklin Bill Ehrbar December 8, 2004 University of Colorado, Colorado Springs.
1 TinyOS Mohammad Rahimi CSCI599-Spring Motivation  The new class of distributed tiny devices  The new generation of software.
TinyOS Software Engineering Sensor Networks for the Masses.
2008EECS Embedded Network Programming nesC, TinyOS, Networking, Microcontrollers Jonathan Hui University of California, Berkeley.
5/5/2003MobiSys 2003 Tutorial TinyOS Tutorial, Part II Robert Szewczyk, Joe Polastre, Phil Levis, David Culler Mobisys 2003.
TOSSIM: Visualizing the Real World Philip Levis, Nelson Lee, Dennis Chi and David Culler UC Berkeley NEST Retreat, January 2003.
NesC: 1.1 Bumps and Future Directions David Gay, Intel Research, Berkeley (and the nesC and TinyOS teams)
1 Lab 3 Objectives  Case study: “Hello world” program on motes  Write you first program on mote.
1 Software Development Infrastructure for Sensor Networks  Operating systems ( TinyOS )  Resource (device) management  Basic primitives  Protocols.
TinyOS Tutorial Jianping Wang (merge several tutorials found online)
1 Lab 5 Objectives  Use XMesh multi-hop networking service to send sensing data to a base station  Using XServe to display the sensor data message on.
Programming Abstractions in Wireless Sensor Networks Professor Jack Stankovic Department of Computer Science University of Virginia.
By: R Jayampathi Sampath
April 15, 2005TinyOS: A Component Based OSPage 1 of 27 TinyOS A Component-Based Operating System for Networked Embedded Systems Tom Bush Graduate College.
1 TinyOS Computer Network Programming Wenyuan Xu Fall 2007.
TinyOS 1/2 Onsystech Sangjae Han.
1 Lab2 Objectives  Basics of TinyOS  Basics of nesC programming language.
HW2: Q&A Oct. 02, Lab Machine TinyOS is installed in one machine (531AB). But, you have to bring your kit. There is a sign up sheet. Please sign.
Wireless Sensor Networks MOTE-KITS TinyOS Crossbow UC Berkeley.
Vishal Jain, TinyOS Design Viewpoint “TinyOS” Design Viewpoint.
HANBACK ELECTRONICS CO., LTD. 저자권 보호됨 Light Sense Lab. Read data from light(photo diode) sensor, display using oscilloscope.
Dhanshree Nimje Smita Khartad
CIS 798 Sensor Network Implementation. Goals Learning sensor network programming with Crossbow motes Implement reasonable sized sensor applications Develop.
Lab 3 Introduction to TinyOS and nesC How to debug programs at PC Examples –Blink Timer –Blink –Hellow World Reference: 1.x/doc/tutorial/lesson1.html.
Simulation of Distributed Application and Protocols using TOSSIM Valliappan Annamalai.
HANBACK ELECTRONICS CO., LTD. 저자권 보호됨 TinyOS & NesC.
Part 2 TinyOS and nesC Programming Selected slides from:
CE Operating Systems Lecture 3 Overview of OS functions and structure.
HANBACK ELECTRONICS CO., LTD. 저자권 보호됨 Wireless MAC Practice (MAC I)
@ nesC Programming KETI / Ubiquitous Computing Center Jeonghoon Kang
System Architecture Directions for Networked Sensors Jason Hill, Robert Szewczyk, Alec Woo, Seth Hollar, David Culler, Kris Pister Presenter: James.
Main Issues Three major issues that we are concerned with in sensor networks are – Clustering Routing and Security To be considered against the backdrop.
Xiong Junjie Node-level debugging based on finite state machine in wireless sensor networks.
WSN Software Platforms - concepts Vinod Kulathumani Lecture uses some slides from tutorials prepared by authors of these platforms.
Chapter 13 – I/O Systems (Pgs ). Devices  Two conflicting properties A. Growing uniformity in interfaces (both h/w and s/w): e.g., USB, TWAIN.
Lab 3, Part 2 Selected slides from: Wireless Sensor Networks Hardware/Software Tiny OS & NesC Programming borrowed from Turgay Korkmaz.
TinyOS Sandeep Gupta. Operating System (OS) What is an OS? Main functions  Process management  Memory management  Resource management Traditional OSs.
TinyOS By Valliappan Annamalai. Hardware Mica motes (Mica2 and Mica2Dot) Hardware –Radio –Microcontroller –Flash memory –ADC –Sensor Board (MTA310)
HANBACK ELECTRONICS CO., LTD. 저자권 보호됨 Lab1: LED Control ZigbeX mote has Red, Yellow, Green LED. This lab using LED control component provided by TinyOS.
Based on slides from Andreas Larsson Table from CY Chong, SP Kumar, BA Hamilton - Proceedings of the IEEE, 2003.
Blink Blink.nc configuration Blink { } implementation { components Main, BlinkM, SingleTimer, LedsC; Main.StdControl -> BlinkM.StdControl; Main.StdControl.
Feb 2007WSN Training: XMesh Enabled Sensor App1 Lab 5 Objectives  Use XMesh multi-hop networking service to send sensing data to a base station  Using.
Why does it need? [USN] ( 주 ) 한백전자 Background Wireless Sensor Network (WSN)  Relationship between Sensor and WSN Individual sensors are very limited.
TinyOS Sandeep Gupta. TinyOS basics TinyOS is  Single tasking OS  Interrupt driven Written using a Component based language A set of components put.
TinyOS and nesC. Outline ● Wireless sensor networks and TinyOS ● Networked embedded system C (nesC) – Components – Interfaces – Concurrency model – Tool.
Simulation of Distributed Application and Protocols using TOSSIM
Ad Hoc Networking using Flooding protocol
An Introduction to nesC
Embedded Operating Systems
WSN Training: TinyOS/nesC Basic Concepts TinyOS and nesC
Presentation transcript:

Programming in nesC (and TOSSIM) Professor Jack Stankovic Department of Computer Science University of Virginia

Questions How do you program these wireless sensor devices? How do you debug your code on a PC? How do you download your code? How do you debug the system? nesC TOSSIM – Lab 3 Lab 0 Message Center – Lab 2

Questions What else do you need to know? Why nesC? TinyOS Most widely used Example of systems language for embedded systems

Helpful Materials Labs and Lab materials – see class web site Handouts – read Read: The nesC Language: A Holistic Approach to Networked Embedded Systems, D. Gay, et. al., PLDI, 2003 (sections 1-4 inclusive) Google to find TinyOS tutorial

Outline Overview Main Elements and Examples Task Model and Concurrency More Coding Details Examples Message Center (Lab 2; intro in class) TOSSIM Summary

TinyOS and nesC Paradigm Component-based TinyOS, libraries, applications written in nesC Intended for embedded systems and WSN C-like syntax (new keywords) Call, signal, task, post, async, … TinyOS concurrency model (tasks and events)

TinyOS and nesC Paradigm No dynamic memory nesC bi-directional interface is an excellent fit for event driven systems Race conditions checked at compile time

Big Picture Write components; use components written by others Will need new keywords/framework for defining components Glue components together Called wiring Configuration file Bi-directional interfaces Concurrency/Execution Model Tasks Event handlers Data races checked at compile time

Big Picture Use development environment on PC and download to target system (motes) Simulator available before downloading Debug on PC Message Center tool – inject/read msgs Debug on actual platform

Big Picture nesC application Modules (implement your code) 1 or more components Wire them together Must have a MAIN component Modules (implement your code) Configurations (the wiring) Interfaces

Big Picture Provides Interfaces Interface: Commands (how to use the interface) Events (user of interface must implement) Component Uses Interfaces

Application Example SW HW RFM Radio byte i2c Temp photo Messaging Layer clocks bit byte packet Radio Packet Routing Layer sensing application application HW SW ADC messaging routing UART Packet UART byte

Example (cont.) You might only write the application component Perhaps all other components are from a library Applies to TinyOS 108 code modules in TinyOS Examples of Applications Surge 31 modules – 27 of them OS TinyDB 65 modules – 38 of them OS

Example (cont.) Note: HW components Veneer of SW exists for each HW component Hides interrupt vector set up Abstracts details of HW init and use (more details later)

Interfaces Interface: Declare commands (implementor of this interface must implement these commands) Declare events (User of this interface, i.e., a components that invokes commands, must implement these events – call back functions) Interfaces have global scope!

Interface Example Interface is a type Timer.nc * filename for a bidirectional interface interface Timer { command result_t start (char type uint32_t interval); command result_t stop(); event result_t fired(); } Interface is a type Many instances of the interface may exist A command or event in an interface is named i.f (Ex: Timer.start, Timer.fired)

Split Phase Because of the execution model, code should exist in small execution pieces Similar to asynchronous method calls Separate initiation of method call from the return of the call Call to split-phase operation returns immediately When work actually finishes the caller is notified via another method call

Specify Split-Phase Declare Interface with both Command Event (e.g., Timer.nc of previous (2) slides back) Use to avoid long delay operations (since a non-preemptive model is used)

Components and Interfaces Provides interfaces (multiple interfaces) (bi-directional) Component Uses Interfaces (multiple interfaces) (bidirectional)

Component Example -Modules Implements a component’s specification with C code: module MyCompM { provides interface X; provides interface Y; uses interface Z; } implementation { …// C code module MyCompM { provides { interface X; interface Y; } uses interface Z; implementation { …// C code specification MyCompM.nc MyCompM.nc The implementation part implements the provides interfaces and if the uses interface has an event then this module must also implement an event handler.

Interfaces Used for grouping functionality, like: split-phase operation (send, sendDone) standard control interface (init, start, stop) Describe bidirectional interaction: Interface provider must implement commands Interface user must implement events TimerM interface Clock { command result_t setRate (char interval, char scale); event result_t fired (); } Clock.nc ClockC Note: This is how you declare a split-phase operation, i.e., Command and Event declared.

Interfaces Examples of interfaces: interface StdControl { command result_t init (); command result_t start (); command result_t stop (); } interface Timer { command result_t start (char type, uint32_t interval); command result_t stop (); event result_t fired (); } StdControl.nc Timer.nc interface SendMsg { command result_t send (uint16_t addr, uint8_t len, TOS_MsgPtr p); event result_t sendDone (); } interface ReceiveMsg { event TOS_MsgPtr receive (TOS_MsgPtr m); } SendMsg.nc ReceiveMsg.nc

Interfaces Not all Interfaces are split-phase E.g., StdControl and ReceiveMsg are not interface StdControl { command result_t init (); command result_t start (); command result_t stop (); } interface ReceiveMsg { event TOS_MsgPtr receive (TOS_MsgPtr m); }

Parameterized Interfaces Note [ …] : This is not a parameter list (can have that too). module GenericCommM { provides interface SendMsg [uint8_t id]; provides interface ReceiveMsg [uint8_t id]; … } implementation {… GenericCommM.nc

Parameterized Interfaces ID = 1 ID = 2 ID = 3 Uses SendMsg Interface Uses SendMsg Interface Uses SendMsg Interface Send Msg 1 Send Msg 2 Send Msg 3 SendMsg Interface Provided by some Component Must know who to respond to All boxes are components

Parameterized Interfaces ID = 1 ID = 2 ID = 3 Uses Timer Interface Uses Timer Interface Uses Timer Interface Set timer for 200 ms Set timer for 150 ms Set timer for 75 ms Timer Interface Provided by some Component Must know who to respond to All boxes are components

Components/Interfaces Commands Events Interface1 command a command b event c Interface2 command d Wire all components that issue commands a, b or d to this component Provides Component

Configurations Wire components together Connected elements must be compatible (interface-interface, command-command, event-event) 3 wiring statements in nesC: endpoint1 = endpoint2 endpoint1 -> endpoint2 endpoint1 <- endpoint2 (equivalent: endpoint2 -> endpoint1)

Configuration - Example Blink application Wiring Example BlinkC Main configuration BlinkC { } implementation { components Main, BlinkM, ClockC, LedsC; Main.StdControl->BlinkM.StdControl; BlinkM.Clock->ClockC; BlinkM.Leds->LedsC; BlinkM BlinkC.nc ClockC LedsC ClockC is really ClockC.Clock LedsC is really LedsC.Leds

Configuration Main.StdControl -> BlinkM.StdControl Component Interface Component Interface Implementation USES PROVIDES

Equals Sign A: provides I But A does not implement I but uses what is provided by B Hence A = B B: provides I Often used for hierarchical Configuration files – see Example later

Implementation fn.nc For all source files (interfaces, modules and configurations)

Concurrency Model Underlying execution model (TinyOS) Tasks and Events Split phase operation

Tasks Tasks Deferred computation Non-preemptable by other tasks Scheduled FCFS from task queue When no tasks – CPU goes to sleep Returns void Declare tasks with task keyword Schedule tasks with post keyword

Task task void processData() { int16_t i, sum=0; atomic { for (i=0; i< size; i++) sum += (rdata[i] >> 7); } display(sum >> log2size);

Tasks FCFS Queue alert task void abc() { . post alert(); } TinyOS Next task Current task TinyOS Non-preemptive

Events Events Execution of an interrupt handler Runs to completion Can preempt tasks and can be preempted by other events Declare events with event keyword (as part of interfaces) Notify events with signal keyword

Events FCFS Queue alert P R E M T Upcalls Can post Tasks/keep Event: packet here Upcalls Event: byte Here Signal packet Can post Tasks/keep Handlers short Event: Bits Signal Byte HW interrupt/ radio Asynchronous

Commands and Events For those commands and events that can be executed by interrupt handlers – explicitly mark as async async event result_t ADC.ready (uint16_t data) { putdata(data); post processData(); return SUCCESS; }

Events Signify completion of a split-phase operation Example: packet send via send command; then communication component will signal sendDone event when transmission is complete Events from environment Message reception Clock firing

Race Conditions Solutions Access shared data exclusively within tasks Have all accesses within atomic statements X Non-preemptive Task queue x Shared data Event Handlers

Directions of Calls Event Call – use keyword signal Component Command Call – use keyword call

Big Picture HW Interrupts Invoke commands and events Components (modules) async command post task call commands signal events … command Main … Task post tasks call commands signal events Components (modules) async command command async event HW Interrupts Invoke commands and events

Components - nesC X = Y Config notation The nesC model: Interfaces: uses provides Components: modules configurations Application:= graph of components Application Component D Component A Component C Component B Component F Component E configuration configuration

Modules Call commands and Signal events module TimerM { provides interface StdControl; provides interface Timer[uint8_t id]; uses interface Clock;… } implementation { command result_t StdControl.stop() { call Clock.setRate(TOS_I1PS, TOS_S1PS); … signal xyz.fired(); TimerM.nc

Modules Task: a task is an independent locus of control defined by a function of storage class task returning void and with no arguments Posting tasks: keyword post module BlinkM {… } implementation {… task void processing () { if(state) call Leds.redOn(); else call Leds.redOff(); event result_t Timer.fired () { state = !state; post processing(); return SUCCESS; }… BlinkM.nc

Atomic Statements bool busy; // gobal .… bool available; …. available = !busy; busy = TRUE; } atomic busy = false; nesC forbids calling commands or signaling events in an atomic section

Interrupt Handling Keep interrupt handlers short May post tasks Examples Increment counter in atomic statement and then done Call LED to set light red; done Post task; done Call -> Call -> Call -> Call then return, …; bad idea

Matching SW and HW Thin veneer of code for HW devices See next slide Assign symbolic names for signals/pins Photo_PWR (to turn on power to photo sensor) Abstract away interrupt vectors HW defined Interrupt Vectors Interrupt Handler

Matching SW and HW Example LED Red LED on/off Green LED on/off Yellow LED on/off Toggle Turn on/off power LED has no interrupts User has it easy; just know interface

Components of Interest LED, Clock, UART, ADC, RFM, I2C (hardware abstraction components) Other components: Chirp, counter, blink, AM_Beacon, AM_Echo, … Find interfaces in tos/interfaces/

Application Example (revisited) RFM Radio byte i2c Temp photo Messaging Layer clocks bit byte packet Radio Packet Routing Layer sensing application application HW SW ADC messaging routing UART Packet UART byte

ADC init() get-data() Fires separate event for each data port

Programming Environment cygwin/Win2000 or gcc/Linux Wireless download of code also available mote Code download mote-PC comms programming board

Summary/Principles/Concepts Single application Wrap HW devices in thin veneer of SW Hide details Components + Glue Use only components required Even for OS Interfaces Bi-directional interfaces Tasks and Events Concurrency Split-phase Asynchronous Embedded systems language No dynamic memory Race conditions Atomic sections Pre-compiler for C

Message Center Tool for sending and receiving packets into actual system Use tool via 2 windows Learn via Lab 2

TOSSIM TinyOS Simulator (not typical) Write your actual code Versus ns2 or glomosim or … Write your actual code Compile it into TOSSIM framework Once debugged – code moved to real platform

TOSSIM Features A discrete event simulator; runs on a PC High fidelity simulations – capture TinyOS behavior at a low level Uses TinyOS’ component based architecture

TOSSIM capabilities Simulates large scale sensor networks (e.g., thousands) Simulates network at bit level (bit error per link) Simulates repeatable loss rate Simulates asymmetric links Simulates each individual ADC capture Simulates every interrupt in the system Time is kept at 4MHz granularity => 4 million ticks per second

TOSSIM non-capabilities Does not simulate single strength Does not model execution time No spin locks or task spin locks A piece of code runs instantaneously Does not model power draw Interrupts are non-preemptive Simulates the 40Kbit RFM mica networking stack Does not simulate the Mica2 ChipCon CC1000 stack

TOSSIM Radio Models Simple: every mote in one cell, bits perfectly transmitted Lossy: connectivity determined at startup Radio propagation is not modeled, rather an abstraction of it is (bit error rate) Specified in a file *.nss (use –rf=<file> option) Specified connectivity Specified bit error rate For example <mote ID>:<mote ID>:bit error rate 0:1:0.009

Radio Model my_radio_model.nss 0:1:0.001 1:0:0.002 0:2:0.001 2:0:0.9 .002 x .001 .9 2 Model an asymmetric link

Using TOSSIM Compiling TOSSIM cd apps/Blink make pc make –rf=fname pc Use: ./build/pc/main.exe [options] <num_nodes> [options] are (see manual for more): -k <kb>, -Set radio speed to <kb> Kbits/s. Valid values: 10, 25, 50. -r, specifies a radio model (simple is default) -t, -<sec> tells TOSSIM to run for a specified number of virtual seconds. <num_nodes> number of nodes to simulate

Debugging Your code …… dbg(DBG_CRC, “crc check failed”); dbg(DBG_BOOT, “Sensor initialized”);

TOSSIM Debugging Known dbg flags (system/include/dbg_modes.h) : all, boot, clock, task, sched, sensor, led, route, am, crc, packet, encode, radio, logger, adc, i2c, uart, prog, sim, queue, simradio, hardware, simmem (found in TinyOS code) For use in applications: usr1, usr2, usr3, temp Insert debug statements in source code dbg(DBG_ROUTE|DBG_ERROR, "Received control message: lose our network name!.\n");

TOSSIM Debugging Set dbg flags to get the proper debug information When simulator starts it read DBG environment variable to enable modes For example: export DBG=usr1,route Only these debug statements will be active!

Important Once you recompile with mote as target instead of pc (i.e., TOSSIM) All debug statements are removed from the executable for you!

Using Debugging Print to screen or file Use Serial Forwarder Run gdb Can inject messages to mote 0 -comm tossim-serial Can snoop all messages in network -comm tossim-radio Run gdb gdb build/pc/main.exe

TOSSIM See TOSSIM document (read when you are preparing for Lab 3) See TOSSIM paper (sections 1-3 inclusive; read now) Learn via Lab 3

Summary nesC – most widely used today for WSN - systems programming language Use naming conventions – see handout Lab 0 – mechanics of downloading, etc. Lab (Programming) Assignments 1-4 Possible Extra Credit Project