Presentation on theme: "TinyOS Operating System for Networked Sensors"— Presentation transcript:
1TinyOS Operating System for Networked Sensors Real-time and Embedded System Laboratory
2Outline Overview Main Properties Hardware Platforms Design ImplementationWireless Network Communication: Active MessagesImportant Subsystems & ToolsTinyDBTASKTOSSIMBombillaTinySecConclusions
3Overview Component-based OS for sensor Networks modularity Developed at UC Berkeley for their original sensors called MotesIts open-source approach and has achieved a big community and tenths of side projects. Also its open and promising design have helpedDeveloped in their own language NesCOptimised in terms of memory usage and energy efficiency, while supporting concurrency-intensive operations
4Main Properties Event Model Perfect solution for high concurrency and small amount of memory spaceUse CPU resources more efficientlyDivision among events (short and with preemption capabilities) and tasks (longer and deferred, but can't preempt)Two level schedulingDesigned to scale with technology trends due to its support for crossover of software components into hardware.About the use of CPU resources more efficientlySee slide 23About 2 levels of schedulingEvents are executed immediately as can preempt… they don’t need scheduler. As there is no constraint, events are managed straightAbout “Designed to scale with technology trends due to its support for crossover of software components into hardware”Means that TinyOs is component based, new support for hardware can be added with rewriting or adding new low layer components, what is really convenient for future hardware implementations
5Hardware PlatformsHardware differences between mote platforms affect software structure, networking capabilities and performanceAbout mote hardware affecting performance (ref. Tinyos-nsdi04.pdf) :The bit-level interface in rene requires the stack to handle interrupts at a high enough rate that the handler cannot encode or decode bytes; encoding/decoding is deferred to tasks. Because it has a small buffer, the encoding layer (SEC DED) must run a task every byte time. This means no other tasks can run longer than a byte time (1.8ms). A larger encoding/decoding buffer would reduce sensitivity to long-running application tasks. In mica, the addition of a byte-level hardware abstraction reduced the interrupt rate. This increased the number of cycles available for each event, allowing encoding/decoding to remain in the interrupt handler. The maximum task length increases to a packet time, approximately 25 milliseconds.Both the rene and mica2 stacks support low-power listening radio. However, it is much more efficient in the former, because the TR1000 (radio transceiver) can turn on very quickly, while the CC1000 turns on slowly. This latency determines how quickly the stack can sample the channel, and therefore how much it can reduce the cost of idle listening.
6Hardware Platforms Mica Imote BTnode Mica2 Mica2dot Spec Next Generation Sensor Networks? - All in one chip - “Smart Dust”
7DesignArchitecture of TinyOS consist of interacting components and a task scheduler3 entities exist that allow components to execute code and communicate among them:Commands and Command HandlersEvents and Event HandlersTasksAlso a fixed-size and statically allocated frame exist per each component, representing its internal state and being operated by the 3 previous entities.Components declare commands used and events signalled, creating a layers of components, where upper layers issue commands to lower layers and handle events coming from them.
8DesignIn TinyOS is talked then about bidirectional interface, referring communication between components through events and commands.
9Design TASKS Perform the primary computation work Atomic with respect to other tasks, and run to completion, but can be preempted by eventsAllow the OS to allocate a single stack assigned to the currently executing taskCall lower level commandsSignal higher level eventsSchedule other tasks within a componentSimulate concurrency using eventsAre queued in FIFO task schedulerAbout FIFO task scheduling (ref. crcpress.pdf) :Other priority-based or dead-line based scheduler can be implemented in the TinyOS frameworkThe Scheduler puts the processor to sleep when the queue is empty, although peripherals are still on and can wake up the processor
10Design COMMANDS Non-blocking requests to lower level components Deposit request parameters into a component’s frame, and post a task for later executionCan also invoke lower level commands, but cannot blockReturn status to the caller
11DesignEVENTSEvent handlers deal with hardware events (interrupts) directly or by lower layer componentsDeposit information into a frame and post tasks to the scheduler (similar to commands)Signal higher level eventsCall lower level commands
12Design Three type of components Hardware abstraction components Synthetic hardware componentsHigh-level software componentsInteresting similarities of components with hardware modules in hardware description languages (i.e. VHDL) benefits for future hardware designsAbout 3 types of components (ref. crcpress.pdf) : TinyOS distinguishes three categories of components. Hardware abstraction components map physical hardware into the component model. Mostly, this components export commands to the underlying hardware and handle hardware interrupts. Synthetic hardware components extend the functionality of hardware abstraction components by simulating the behavior of advanced hardware functions, e.g. bit-to-byte transformation functions. For future hardware releases, these components can directly cast into hardware. High level software components perform application specific tasks, e.g. control, routing, data transmission, calculation on data, and data aggregation.
14ImplementationProprietary language based on C language called NesC“A language for programming structured component-based applications, primarily intended for embedded systems such as sensor networks”Two types of components in NesC:Modules: Application code, implementing one or more interfacesConfigurations: Wires components and, on a top level, assembles applications to produce and executableTinyOS provide a wide variety of system components and some pre-built applications. Application development can start immediately.About applications implemented already in TinyOS :Basically system tests that can serve as an example for the developer.
15Implementation EXAMPLE: Blink Application Simple application that causes the red LED on the mote to turn on and off at 1HzTwo components. A module called BlinkM.nc and a configuration called Blink.ncAccess to system components (ClockC and LedsC) which access the hardwareMain is the first component executed in any TinyOS application and must be indicated in its configuration fileAbout Blink application:Is not true that BlinkM access directly ClockC, nor that ClockC access directly Hardware. Actually, BlinkM access SimpleTimer for the sake of clarity for the example, and SimpleTimer access TimerC that access ClockC (both as systems components). Then, depending the platform to compile, ClockC access final components with direct access to the clocks of the different devices.The TinyOS standard control interface. All components that require initialization or can be powered down should provide this interface. start() and stop() are synonymous with powering on and off, when appropriate.A nesC application consists of one or more components linked together to form an executable. A component provides and uses interfaces. These interfaces are the only point of access to the component and are bi-directional. An interface declares a set of functions called commands that the interface provider must implement and another set of functions called events that the interface user must implement. For a component to call the commands in an interface, it must implement the events of that interface. A single component may use or provide multiple interfaces and multiple instances of the same interface.
17Wireless Network Communication Active Messages Motivation: Existing solutions not applicable (bandwidth intensive, too complex packets, computational and energy demanding, stop & wait…)Active Messages:Simple, extensible paradigmWidely used in parallel and distributed systemsDistributed event model matching TinyOS designTiny Active Messages: Protocol center in lightweight transmission mechanism: 2-phase request-reply model (no acknowledgements) See picture on Word document
18Wireless Network Communication Active Messages Messages contain the handler ID (globally unique byte) to be executed at destination. Special handlers:Handler 0: Routing handler.Handler 255: List installed handlersMote handlers are invoked through eventsBase Station mote (node connected to PC host) has the special destination address 0x7e (126)New implementations of AM allow 2 byte destination addresses and also implement Groups. Group’s ID allow several groups of motes to share the same radio channel without interfering each other. Group’s ID is one byte long and can be specified with an environmental variable or at compile time.
19Wireless Network Communication Active Messages Data payload (up to 28 bytes) is passed to the handler as an argumentEvent-based architecture enables network communication to overlap with sensor interactionThree basic primitives are supported:Best effort message transmissionAddressing (address checking)Dispatch (Handler invocation)Sufficient for operation. Applications can build other functionality on top (encryption, flow control, fragmentation, error correction/detection… )About “Three basic primitives are supported:”Best effort message transmissionAddressing (address checking): If the message received is for meDispatch (Handler invocation): if its for me, issue an event to invoke the handler
20Wireless Network Communication Active Messages INTERESTING USABILITYRouting:Handler 0 forwards to next hopEach hop decreases N and forwards the packetLast hop (N=1) inserts destination handler (HF) into H0Hop’s addresses are stored (up to 4)BroadcastingAddress 255 allows message broadcasting2-hope messages will discover all closest neighborsReturned packets hold those neighbors addressesPermits a method of route discovery
21Wireless Network Communication Active Messages INTERESTING USABILITYRadio Reprogramming:Mica2 and Mica2dot platforms can be reprogrammed (change the running application) by radio connection using AMA Java application on the base station is used to send the program to one or several motesA special & reserved handler is used in the motes to receive AMs for reprogrammingA special module has to be wired with applications.Program is stored in external flash and motes’s IDs are in eeprom. An special boot loader, stored previously in processor’s program memory, executes to load and reboot the mote so new application will be run.
22Wireless Network Communication Active Messages SOME FIGURESPower ConsumptionThroughput: ~800 bytes/sec (~6.5 Kbps) with 4b6 encoding
23TinyOS SOME OTHER FIGURES Small Size: Concurrency: Scheduler just 178 bytesComplete applications need only around 4 Kb + application codeConcurrency:Component NameCode Size (bytes)Data Size (bytes)Multihop routerAM_dispatchAM_temperatureAM_lightAMPacketRADIO_byteRFMPhotoTemperatureUARTUART_packetI2C_bus88407814635633481031084641963141983281Processor_initTinyOS schedulerC runtime172178823016Total3450226ComponentsCPU UtilizationEnergy (nj/Bit)AM0.20%0.33Packet0.51%7.58Radio handler12.16%182.38Radio decode thread2.48%37.2RFM30.08%451.17Radio Reception-1350Idle54.75%Total100.00%Low Overhead :Cost of posting and event = cost of copying 1 byte of dataEven during periods of active communication with bite level processing, CPU is sleeping 50+% of the time
24Important Subsystems & Tools TinyDB: The TinyDB "sensor network as database" applicationBombilla (Maté): TinyOS virtual machineMatchBox: Simple mote filing systemTASK: The TASK "Tiny Application Sensor Kit" applicationTOSSIM: The TinyOS (PC) Simulation EnvironmentMIG: Message Interface GeneratorMessage Center: Easy injection of arbitrary messages into a mote networkTinySec: Secure communication on motes.
25Important Subsystems & Tools TinyDB Query process system SQL-like for extracting information from a network of TinyOS sensorsTinyDB provides an interface in the base station for query inputThe query is spread and collected back to the base stationA set of attributes can be selected for the queryTinyDB component must be installed in each node to collect those attributesAn API is provided to embed TinyDB on user’s own applications
26Important Subsystems & Tools TinyDB Example:Sensor equipped university buildingWhich classes are in use? light sensor reading from sensor’s room is above threshold l and volume sensor above vWriting an application in nesC to read network light sensors and route results to base station would be difficultWith TinyDB, we run its component on each sensor and equip them with a room number (i.e. node ID):SELECT nodeID, AVERAGE(light), AVERAGE(volume)FROM sensorsGROUP BY nodeIDHAVING AVERAGE(light) > l AND AVERAGE(volume) > vEPOCH DURATION 5min
27Important Subsystems & Tools TinyDB Classroom 1B.S. RoomClassroom 5Classroom 4Classroom 3Classroom 2221214932543554221214932543554564821510322121493254355456482About how queries are retransmitted and identifiedThe API for sending queries generates a globally unique identifier for each queryTuples include information about if they are to be aggregated to other nodes information or are collecting them. Also some counters are includedQueryNodeID Light Volume
28Important Subsystems & Tools TinyDB Components OverviewSensor Network SoftwareSensor Catalog and Schema ManagerQuery ProcessorMemory ManagerNetwork TopologyJava-based Client InterfaceNetwork InterfaceClasses to build and transmit queriesA class to receive and parse query resultsA GUI for result display, query construct and visualize dynamic network topologies…
29Important Subsystems & Tools TinyDB Status WindowQuery WindowCommand Window
30Important Subsystems & Tools TinyDB Features:Multiple Queries: Allowance of multiple queries over the same motes at the same timeTriggers: Local command execution on some result (i.e. alarm sound on temperature over t)Even-Based Queries: Queries starting on when a low-level event occurs.Queries over Flash: Creating, inserting, retrieving and deleting tables in Flash memoryPower Management and Synchronization: Each sensor is on for the same period of time of every sample period. Allow power saving and long time battery life of sensors (i.e. 60 days for sampling periods of 30 seconds)
31Important Subsystems & Tools TASK TinyDB is included into a toolkit called “Tiny Application Sensor Kit” (TASK)Apart from TinyDB, TASK offers:TASK Server: server process running on a sensor network gateway that acts as a proxy for the sensor network on the internet.TASK DBMS: A relational database that stores sensor readings, statistics… (currently only accepting PostgresSQL)Task Client Tools: including TASK Deployment Tool that helps users record sensor node metadata, TASK Configuration Tool that helps users choose data collection intervals and data filtering and aggregation criteria, and TASK Visualization Tool that helps users monitor the network health and sensor readings.TASK Field Tool: running on a PDA that help users diagnose and resolve problems in certain areas of the network in the field.
32Important Subsystems & Tools TOSSIM TinyOS simulator able to simulate thousands of nodes simultaneously, while displaying its interaction and providing run-time configurable debugging output, allowing a user to examine the execution of an application from different perspectives without needing to recompilePC application (executable) compiled directly from TinyOS with the option pcTinyViz is a Java-based GUI that allows visualization and controlling the simulation as it runs, inspecting debug messages, radio and UART packets, etc
33Important Subsystems & Tools TOSSIM TOSSIM runs originally in text mode, showing events output and debugging information that can be configured.Accepts one single parameter: number of nodes to simulate, which will run the same applicationApart from the possibility to shift debugging modes, 4 debugging modes are reserved for user-specific messages:dbg(<mode>, const char* format, ...);As TOSSIM runs natively in the PC, traditional debugging tools, such as gdb (GNU debugger), can be used. However, event based nature of TinyOS (programmed with NesC and not C) makes debugging process not standardOne significant advantage of TOSSIM is that, because it runs natively on a PC, you can use traditional debugging tools such as gdb. However, because TOSSIM is a discrete event simulation for large numbers of motes, traditional step-through debugging techniques only work on an event basis, and not cross-events.Unfortunately, gdb is generally designed for C and not nesC; the component model of nesC means that a single command can have multiple providers; referring to a specific command requires specifying the component, interface, and command. For example, to break on entry to the redOff command of the Leds interface of LedsC, one must type: gdb build/pc/main.exe // start gdb(gdb) break *LedsC$Leds$redOff Breakpoint 1 at 0x804c644: file tos/system/LedsC.td, line 97.run 1 // run CntToLedsAndRfm with one moteThe leading * is necessary so gdb can parse the function name correctly; otherwise, it looks for the function LedsC.Variables are similarly named. For example, to print the ledsOn variable of LedsC (which keeps track of on/off for the toggle commands), one types: (gdb) print LedsC$ledsOn$3 = '\0' <repeats 999 times>Actually, this isn't quite correct, as the output above shows; in TOSSIM, ledsOn isn't a single uint8_t, but an array of 1000 of them. This is how TOSSIM handles the state of many motes; it compiles fields to be arrays of n elements, where n is the maximum simulation size. Whenever a mote accesses a component's state, it indexes into the array based on its node ID. Therefore, to refer to a specific mote's state, one needs to index into the array properly: (gdb) print LedsC$ledsOn[tos_state.current_node]$2 = 0 '\0‘We've supplied a simple gdb macro named VAR that handles this for you. Copy tos/platform/pc/.gdbinit to your home directory (if there's already a .gdbinit there, just append this file). Type quit and start gdb it again. Break in LedsC$Leds$redOff as before. Now, instead of the above command line, you can type: (gdb) VAR LedsC$ledsOn $3 = 0 '\0'
34Important Subsystems & Tools TOSSIM TinyViz is a Java based GUI for graphical simulations of nodes running TinyOS applications, behaving as a front-end for the TOSSIM simulator
35Important Subsystems & Tools TOSSIM TinyViz builds its functionality with a set of plug-ins, software modules that watch for events coming from the simulation and react by drawing information on the displayMain plug-ins are provided with TinyOS installation, and the implementation is opened to user-made plug-ins that can be included later in the GUI. ImplementedDebug Messages: Generated by simulation and can be filteredSet Breakpoints: On a pattern matching bases on debug or radio messagesSent radio packets: Display only radio packets (also in debug messages)Radio links: Highlight active radio motes and sets arrows between communicating nodesSet location: Simulates node location for possible location services applications.Radio model: Sets the bit error rate according to simulated location and two radio models (empirical and fixed radius)About implemented plug-ins in TinyViz (ref. TINYOS tutorial, lesson 5) :Debug messages: Shows a window with all of the debug messages generated by the simulation. You can select debug messages just from the selected group of motes, and also highlight messages that match a certain pattern. Note that the set of debug messages you see are controlled by the value of the DBG environment variable, just as they are when running TOSSIM in a stand-alone setting. So, if you only want to see debug messages of type DBG_USR1 and DBG_AM, start up TinyViz with:DBG=usr1,am tinyviz -run build/pc/main.exe 30Set breakpoint: Allows you to set a breakpoint, which will pause the simulation when some condition is met. Right now, the possible conditions are (a) a substring match on a debug message, or (b) a match on the contents of a sent radio message. Multiple breakpoints can be set and they can be enabled or disabled by selecting them in the breakpoints list.ADC readings: Shows the most recent value of each ADC channel next to each mote.Sent radio packets: Shows a window with all sent radio packets, much like the Debug messages plugin. Note that the Debug messages plugin also shows this information.Radio links: Graphically displays radio message activity. When a mote broadcasts a message, a blue circle will be drawn around it. When a mote sends a message to another mote, a directed arrow will be drawn between the two motes. Note that this shows all message transmissions, regardless of whether they are successful; if a mote attempts to send a message but it is corrupted or lost, the arrow will still be drawn.Set location: Makes the virtual location of each mote available to that mote through the Location interface, found in apps/TestTinyViz/Location.nc. This is accomplished by setting the value of three "fake" ADC channels (one each for X, Y, and Z coordinates) on each mote, which the FakeLocation component reads to determine the mote's virtual location. This is meant to act as a stand-in for a real localization service when simulating TinyOS apps.Radio model: Sets the bit error rate between motes according to their location and various models of radio connectivity. Enabling this plugin allows you to use realistic connectivity models in your simulations. There are two built-in models: "Empirical" (based on an outdoor trace of packet connectivity with the RFM1000 radios) and "Fixed radius" (all motes within a given fixed distance of each other have perfect connectivity, and no connectivity to other motes). Setting the "scaling factor" in the control panel simply scales the distance parameter of the model. Increasing the scaling factor will decrease the connectivity range of the chosen model. By selecting a mote in the display you can see its connectivity to other motes -- the number shown next to each edge is the probability of a packet getting through. Changing the scaling factor and clicking "update model" will update the model parameters, as will moving motes around in the display.
36Important Subsystems & Tools BOMBILLA Bombilla is a bytecode interpreter running on TinyOS, composed of several components that sit on top of several system components.Bombilla is an stack-based architecture: no embedded addresses are requiredCondensed high-level assembler instructions makes programs very short:getvar 0 # Get heap variable 0pushc 1 # Push one onto operand stackadd # Add the one to the stored countercopy # Copy the new counter valuesetvar 0 # Set heap variable 0pushc 7and # Take bottom three bits of counterputled # Set the LEDs to these three bitshalt
37Important Subsystems & Tools BOMBILLA Additionally, Bombilla has an automatic network forwarding mechanism that allow programs installed in one mote spread eventually to every node of the network security problemErrors are caught at run time. When an error is triggered, system is stopped and debugging information sent through the UARTBombilla also has a 16 variable heap to provide a shared variable workspace (to be accessed only by special instructions): Event handlers implicitly lock all shared resources they use, so no “race conditions” are possibleAbout Security problem in automatic spread applications (ref. Bombilla.pdf, section 5):Capsules injected in the network with the forwarding bit set can spread without control flooding the network. The only mechanism provided now is a version number, so only capsules with a higher version number will be installed when received. Moreover, although no capsules would be installed, those ones with the forw instruction will be broadcasted, easily saturating the network.About LOCKING and SHARED VARIABLES:Although there is an implicit lock on event handlers, this automatic procedure can be relaxed by experienced programmers to allow better parallelism
38Important Subsystems & Tools BOMBILLA ArchitectureBombilla programs are broken into capsules of 24 instructions, small enough to be retransmitted in a single radio message (AM) and eliminating the need of partial capsule buffering, saving RAMTwo kinds of capsules: event handlers (in response to an event) and subrutines (called from another capsules).Each instruction is executed as a TinyOS task, allowing execution interleaving at instruction granularity.Three execution context: clock, send and receive. Each context is associated with different eventsEach context has two stacks: operand stack (instructions handling data) and return address stack (for subrutines).
39Important Subsystems & Tools BOMBILLA ArchitectureAbout BuffersStoring and dealing with individual values is useful, but often being able to handle sets of data is needed. Bombilla provides buffers, which can hold up to ten variables. Buffers are typed. An empty buffer has no type, and takes on the type of the first variable put in it. For example, if the first variable is a light reading, then the buffer will become a light reading buffer. Attempting to put a variable of another type (e.g. a value) into the buffer will result in an error. Bombilla provides two buffers, which can be pushed onto the operand stack with bpush0 and bpush1. Variables can be placed in the buffers with the add instruction; this polymorphism of the add instruction leads to a more concise instruction set.About Once contextThere is an additional context, the “once” context. Unlike other contexts, which run their capsules many times, this context only runs its capsule once, when it is installed; this allows a user to initialize state, adjust constants, or perform other operations that only need a single execution.
40Important Subsystems & Tools TinySec Link layer encryption mechanism for motes running TinyOS:Access control and confidentiality: Only authorized nodes can participate in the networkIntegrity: Against man-in-the-middle attacksEase of use: Just an interface changeEach node participating in the communication has the same key specified at compile time. That key is used for data encryption and verification, applied to every AM leaving the nodeAn script is used to able TinySec on motesGenericComm (TinyOS radio stack) is replaced with SecureGenericComm, which enables authenticity. To use encryption, application must use specific sendMsg commands, exported also by SecureGenericComm
41Conclusions AND FINALLY… TinyOS is a highly modular software environment tailored to the requirements of sensor networks needed of an efficient concurrency managementIts design makes possible an easy evolution to support new hardware features and architectures coming with new timesIts flexibility and popularity makes from TinyOS a safe solution to invest in. New features are constantly developed and new versions of the OS are being released every month.Only certain limitations, such a simplistic Scheduling or lack of memory protection, exist. However, TinyOS, as the most popular (and open source) OS for sensor networks, assures a future fix of virtually any issue due to its extensive communicity.AND FINALLY…