Unit IV — Case Study of RTOS
“RT Linux
“ MicroC/OS-II
«Embedded Linux
“Tiny OS
“Basic Concepts of Android OS.Introduction
Kernel of an RTOS
+ Used for real-time programming features to meet hard and soft real time constraints.
+ Provides for preemption points at kernel, user controlled dynamic priority changes, fixed memory
blocks, asynchronous IOs, user processes in kernel space and other functions for a system.
‘Complex multitasking embedded system design requirements are
_ Integrated Development Environment,
~ Multiple task functions in Embedded C or Embedded C++,
~ Real time clock— hardware and sofiware timers,
_ Scheduler,
— Device drivers and device manager,
— Functions for inter inter-process communications using the signals, event flag group, semaphore-
handling functions, functions for the queues, mailboxes, pipe, and sockets.
_ Additional functions for example, TCP/IP or USB port, other networking functions.
— Error handling functions and Exception handling functions, and
Testing and system debugging software for testing RTOS as well as developed embedded application.
RTOS features in general have the following features:
Basic kernel functions and scheduling: Preemptive or Preemptive plus time slicing
~ Support to Limited Number of tasks and threads
~ Task priorities and Inter Service Threads priorities definitions
~ Priority Inheritance feature or option of priority ceiling feature
— Task synchronization and IPC functions
— Support to task and threads running in kernel space
_ IDE consisting of editor, platform builder, GUI and graphics software, compiler, debugging and host
target support tools
_ Device Imaging tool and device drivers
~ Clock, time and timer functions,
— Support to POSIX,
— Asynchronous IOs,
— Fixed memory blocks allocation and deallocation system,
_ Support to different file systems and flash memory systems
_ TCP/IP protocols, network and buses protocols,
— Development environment with Java
Componentization (reusable modules for different functions), which leads to small footprint (small of
size of RTOS codes placed in ROM image)
_ Support to number of processor architectures, such as INTEL, ARM, Philips
Types of RTOSes
Following are the types of RTOSes
In-House Developed RTOSes: In-house RTOS has the codes written for the specific need based, and
application or product and customizes the in-house design needs. Generally either a small level application
developer uses the in-house RTOS or a big research and development company uses the codes built by in-
house group of engineers and system integrators.Broad based Commercial RTOSes:
A broad-based commercial RTOS package offers the following advantages.
- Provides an advantage of availability of off the self thoroughly tested and debugged RTOS functions
_ Provides several development tools
_ Testing and debugging tools
_ Support to many processor architectures like ARM as well as x86, MIPS and SuperH.
_ Support to GUIs
~ Support to many devices, graphics, network connectivity protocols and file systems
~ Support to device software optimization (DSO)
— Provides error and exceptional handling functions can be ported directly as these are already well
tested by thousands of users
_ Simplifies the coding process greatly for a developer
— Helps in building a product fast
~ Aids in building robust and bug-free software by thorough testing and simulation before locating the
codes into the hardware
_ Saves large amount of RTOS, tools and inhouse documentation development time
_ Saving of time results in little time to market an innovative and new product.
_ Saves the maintenance costs.
~ Saves the costs of keeping in-hose engineers
General Purposes OSes with RTOS: Embedded Linux or Windows XP is general purpose OS. They are
‘not componentized. Footprint (the code that goes as ROM image) is not reducible. The tasks are not
assignable priorities. However, they offer powerful GUIs, rich multimedia interfaces and have low cost.
The general purpose OSes can be used in combination with the RTOS functions. For example, Linux
2.6.24 and RTLinux are real time kernels over the Linux kernel. Other example is ‘Windows XP Embedded”
for x86 architecture
Special Focus RTOSes:Used with specific processors like ARM or 8051 or DSP, for example, OSEK for
‘automotives or Symbian OS for Mobile phones.
Common options available for
selecting an RTOS
‘Some Options for
An RTOS
Own Lnux OSI VWorks Windows,
RTOS Based ce,
for RTOS Windows
Small FUNCTIONS Mobi
Scale Red Hat
Embedded COS or
System RT Linux
‘Linux 2.6.24an RTOS
i T T T T T T T
Kemel | Service Device Timeand Emer Task ‘ISRand IST Memory
(Scheduler) | and System Driver, Delay Handing State Functons Functions
Clock Network Functions Function Switching ©
Functions Stack and Functions P
Send and Watchdog ae
yC/OS-II Features
Jean J. Labrosse designed it in 1992.j1C/OS-II name derives from Micro-Controller Operating
System, Also known as MUCOS, UCOS,
Basic Feature
_ Scalable OS — only needed OS functions become part of the application codes
— Configuration file includes the user definitions for needed functions
_ Multitasking preemptive scheduler
_ Elegant code
_Is said to offer best high quality/performance ratio
~ Ithas a pre-certifiable software component for safety critical systems, including avionics system clock
A. DO-178B and EUROCAE ED-12B, medical FDA 510(k), and IEC 61058 standard for
transportation and nuclear systems, respectively
_ Source code has been certified by Department of Defense, USA for use in Avionics and in medical
applications.
-Applications: Automotive, avionics, consumer electronics, medical devices, military, aerospace,
networking, and systems-on-a-chip.
MUCOS real time kernel additional support
_ 1C/BuildingBlocks [an embedded system building blocks (software components) for hardware
peripherals, for example clock (1C/CIk) and LCD (\wC/LCD)]
_HKC/FL (an embedded flesh memory loader)_HCIES (an embedded memory file system)
~ #C/GUI (an embedded GUI platform),
~ uC /Probe (a real time monitoring tool),
—HC/TCP-IP (an embedded TCP/IP stack),
7 C/CAN (an embedded Controller Area Network bus)
—HC/MOD (an embedded Modbus ) and
THC/USB device and C/USB host (an embedded USB devices framework).
Source Files:
L_Processer-dependent source files: Two header files at master are (i) 0s_cpu.h is processor definition
header file (ii) the kernel building configuration file is os_cfg.h
2.Processor-independent source files: Two files, MUCOS header and C files are ucos_ii.h and
008 ii
MUCOS Naming Basics
_ OS ot OS_prefix denotes that the function or variable is a MUCOS operating system function or variable
— For examples, OSTaskCreate () —aMUCOS function that creates a task,
__OS_NO_ERR—a MUCOS macro that returns true in case no error is reported from a function
_ OS_MAX_TASKS— user definable constant for specifying maximum number of tasks in user application
MUCOS Basic Functions
+ System Level - OS initiate, start, system timer set, ISR enter and exit
+ Task Service Functions ~ create, run, suspend, resume, ..
+ Task delay
+ Memory allocation, partitioning ..
+ IPCs — Semaphore, Queue and Mailbox
+ Same Semaphore function usable as event flag, resource key and counting semaphore
+ Mailbox one message pointer per mailbox
+ Queue permit array of message-pointers
Summary of Commonly Used pC/OS-II Functions
and Data Structures
Data Structures
OS_EVENT:
s structure is used in the following functions: OSQCreate(), OSQPend(), OSQPost(), OSSemCreate(),
‘OSSemPend(),OSSemPost(). All of these functions make use of queues to either protect resources or pass
messages between tasks. A pointer to the created structure is returned by the two create functions. Once
these queues have been created treat the returned pointers asthe head of the queue and always pass the
pointer to this structure to the Pend and Post functions as the pevent argument. Traversal is not necessary.
‘See below for further information regarding the individual functions. Data structure located in file
src/uC/ucos_ii.n
typedef struct {
INT8U _OSEvent Type; /* Type of event control block (see
0S_EVENT_TYPE_?7?) 7
INT8O OsEventGrps /* Group corresponding to
tasks waiting for event to occur */INTI6U _OSEventcnt; /* Semaphore Count (not
used if other EVENT type)
void *0SEventtr; J+ Pointer to message or
queue structure
INT@U OSEventTb1[0S_EVENT_TBL_SIZE]; /* List of tasks waiting
for event to occur af
char OSEventName [OS_EVENT_NAME_S1ZE]; /* Compile time directive
currently has OS_EVENT_NAME SIZE = 32 */
) OS_EVENT;
fidefine OS_EVENT_TYPE_UNUSED ° /* All possible values for OSEventType in
OS EVENT stzuct
define OS_EVENT_TYPE MBOX
define OS_EVENT_TYPE_Q
define OS_EVENT TYPE SEM
fidefine OS_EVENT TYPE MUTEX
define 03_EVENT_TYPE_FLAG
OS_STK:
Each task has stack entries of this type. The data structure is located in file sre/uC/os_epu.h
typedef unsigned short 03_sTK; /* Bach stack entry is 16-bit wide
”
OS_STK_DATA:
A variable of type OS_STK_DATA is filled in when calling OSTaskStkChk() to get the statistics about the
stack of each task. Further information regarding the OSTaskChkTask function is located below. The
OS_STK_DATA data structure is located in file sre/uC/ucos_ii.h
typedef struct {
INT32U OSFree; /* Number of free bytes on the stack for a
specific task */
INT32U OSUsed; /* Number of bytes used on the stack for a
specific task*/
) OS_STR_DATA;
OS_TCB:
A variable of type OS_TCB is filled in when calling OSTaskQuery() to get information about a task. Further
information regarding OSTaskQuery is located below. The OS_TCB data structure is located in file
ste/uC/ucos_iish
typedef struct os_tcb{
oS_sTK *ostcastketr; //Stack Pointer
void *OSTCBExtPtr; //TCB extension pointer
08_sTK *OSTCBStkBottom: //Ptz to bottom of stack
INT320 OSTCBStkSize; //Size of task stack (#elements)
INT160 ostcropt; 7/Task options
struct 0s_tch *OSTCBNext; //eointer to next TCE
struct os_tch *0STCBPrev; //eointer to previous TCB
0S_EVENT sosTCBEventPtr; 7/Pointer to ECB
void *OsTCEMsg: (/Message received
OS_FLAG_NODE *OSTCBF_lagNode; //Pointer to event flag node
0S_FLAGS OSTCBFlagsRdy //event flags that made task ready
INT160 ostcEDly; (Mor ticks to delay task or, timeout
INT8U ostcEsta (Task status
NTU OsTCEPrio; //task Priority (0 = highest)anteu osteex;
mrev ostcey;
mrey ostcenitx:
awreu ostcenity;
BOOLEAN ostcepelreq: //elag to tell task to delete itself
yos_vea;
Global Variables
Most of the global variables for uC/OS-II are located in file sre/uC/ucos i
Reading from them is necessary for some exercises in the labs.
hh, Do not modify these globals.
OS_EXT INT8S oscPUUsage; /* Percentage of CPU used
/
Vector Table Entries
Initialize vector table entry #0 with the pointer of the context switching function. This function will be called
‘on every context switch. Initialize the table before doing anything else. Without the context switching vector
(TRAP # 0) pointing to the correct function uC/OS-II will not function correctly. The context switching
function OSCtxSw() is located in file src/uC/os_cpu_a.s This is given to you. DO NOT modify the code
that moves the Trap location into the vector table.
*((int *)0x80) = (int)osctxsw; /* set up vector to Context Switch (TRAP #0) */
Initialization Functions
OSInitQ)
Function [arenes Returns Notes
Prototype
‘void ‘none nothing |Call this function first inside your begin() function. Initializes
‘OSInit(void); ‘uC/OS-II and must be called before calling OSStart()
Location:
sre/uC/os_core.c
Example:
begin (void) /* SYSTEM ENTRY POINT */
fi
*((int *)0x80) = (int)osctxsw; /* set up vector to Context Switch (TRAP #0) */
ostnit ();
osstart (); Pe away: wags 1%
OSStart()Function [Arguments |Returns Notes
Prototype
void hnone nothing |OSStart begins the multitasking. Call this as a part of your
(OSStan(void); initialization function but make sure that you have called OSInit()
first.
‘Location:
‘sre/uC/os,_core.c
Example:
begin (void) /* SYSTEM ENTRY POINT +/
‘
+((int *)0x80) = (intyoscexsw; /* set up vector to Context switch (TRAP #0) */
ostnit();
Osstart(); /* away we go! */
)
OsStatinito,
Function {Arguments [Returns Notes
Prototype
‘void ‘none Inothing |If CPU stats are required, this function must be called. It must be
(OSStatInit(void); called from the first and only task created. This first and only task
may,in turn, create other tasks once OSStatInit has been called,
Location:
\sre/uC/os_core.c
Example:
begin (void) /* SYSTEM ENTRY POINT
q
*((int *)0x80) = (intyosctxsw; /* set up vector to Context switch (TRAP #0) */
ostnit yy:
TaskCreate("StartTask", StartTask, StartTask_ID) ;
osstart (0+ 7* away we go! */
void StartTask(void *data)
{
Scopetnit () /* Initialize oscilloscope triggering routine */
Tickinit Q); /* Start 08 ticker, see os/os_cpu_a.s */
osstatinit(); /* Initialize statistics task */
OsTaskCreateExt(...)+ 7* all clear to call tasks now */
OsTaskcreatezxt(...)+
OsTaskDel(OS_PRIO_SELF); /* This task only runs once */
Task FunctionsOSTaskCreateExt()
Function Prototype Arguments Returns Notes
INT8U task One of the following ‘Stack must be declared
OSTaskCreateExt Pointer to task’s code that must _ error codes: as type OS_STK
(void(*task)(void*pd), [be declared as void Task (void
void *pdata, +) OS_NO_ERR At some point during the
(OS_STK *ptos, Funetion was successful execution of the task one
INTSU prio, pdata in creating the task _of the services offered by
INTI6U id, Pointer to data that is passed to uC/OS-II must be called
\OS_STK *pbos, task when it is created OS_PRIO_EXIST ‘to wait for time to expire,
INT32U stk_size, A task already exists ‘suspend the task or wait
\void “pext, ptos with that priority. In uC for an event like a
INTIGU opt ); Pointer to the top of the task’s each task must have a mailbox or semaphore.
stack. For stacks that grow unique priority ‘Otherwise the task may
Location: down in memory ptos needs to never cede the
‘sre/uC/os_task.c
point to the highest valid
memory location on the stack.
prio
Unique priority to assign to this
task. The lower the number the
higher the priority.
id
‘Task’s ID number which is not
currently used. Set this to the
priority of the task
phos
Pointer to the bottom of the
task's stack. For stacks that
grow downward in memory
pbos must point to the lowest
valid stack location.
stk_size
Number of 16 bit entries
available on the stack. See
typedef of OS_STK in
sre/uC/os_epu.h and above
ext
Pointer to a user supplied
memory location used as TCP
extension. User defined location
or data structure.
‘opt
Options for the task created.
Lower 8 bits are reserved for
OS_PRIO_INVALID
iprio is higher than
OS_LOWEST_PRIO,
‘currently set to 63
OS_NO_MORE_TCB
uC has run out of
OS_TCBs to assign
;processeor and other
tasks with lower
priorities may never get a
time slice. uC/OS-IL is
‘not a round robin OS.
‘Consequently, all task
‘must eventually cede for
all task to get servicing.
‘Don't assign user tasks
priorities 0, 1,2, 3,
OS_LOWEST_PRIO-3,
OS_LOWEST_PRIO-2,
OS_LOWEST_PRIO-1,
or OS_LOWEST_PRIO.
These are reserved by
uC/OS-II, The other 56
application tasks are
therefore available.uC/OS-II but applications may
use the upper 8 bits for
application specific options
Possible uC/OS-II predefined
options are
OS_TASK_OPT_STK_CHK
Specifies whether stack
checking is allowed for the task
OS_TASK_OPT_STK_CLR-
Specifies whether the stack
need to be cleared
OS_TASK_OPT_SAVE_FP
N/A we have no floating point
registers on our CPU32
Example:
fidefine TASK_OPT
0$_TASK_OPT_STK_CHK + OS_TASK_OPT_STK_CLR
void TaskCreate(char *TaskDesc, void *TaskFunc, INT8U TaskID)
‘
INTSU err;
err=OSTaskCreateExt (TaskFunc,
(void *)0,
STaskStack[TaskID] [TASK_STACK_SIZE-1],
TaskID+5,
TaskID,
STaskStack[TaskID] [0],
TASK _STACK SIZE,
staskData[TaskID},
TASK_OPT) +
Af (Jere)
strcpy (TaskData[TaskID] .TaskName, TaskDesc) ;
else
disp_err(err);
)
OSTaskDel)
Function ‘Arguments Returns Notes
Prototype
INTSU prio OS_NO_ERR Specify the priority of the task to
OSTaskDel__priority number Call was successful bbe deleted or pass in
\(INTSU prio) ; of the task to be OS_PRIO_SELF if priority of task
deleted. OS_TASK_DEL_IDLE is unknown, This task's code is not
Location: This value is returned if you actually removed but the task is
sre/uC/os_task.c
attempt to delete the idle task, this
is not permitted
OS_TASK_DEL_ERR
‘Task to be deleted does not exist.
OS_PRIO_INVALID
prio is higher than
OS_LOWEST_PRIO.
placed in the dormant state and can
be recreated and made active by
calling OSTaskCreate or
(OSTaskCreateExt.
‘Be careful when deleting a task that
[owns associated resources. If a task
owns resources like mailboxes,
semaphores ete. call
10Example:
(OSTaskDelReq() instead to deal
OS_TASK_DEL_ISR ‘with those issues safely.
This value is returned if you
attempt to delete a task from an
ISR.
void StartTask (void *data)
‘
Scopetnit (); /* Initialize oscilloscope triggering routine */
TickInit (); /* Start OS ticker, see src/uC/os_cpu_a.s */
osstatinit () 7 /* Initialize statistics task */
LEDQueue = OSQCreate (LEDQueueTbl, 10);
OstaskDel (0S_PRIO_SELF) ; /* We don't want the Start ask to run
more than once */
)
OSTaskStkChk()
{Function Prototype | ‘Arguments Returns Notes
INTSU prio (OS_NO_ERR Execution time for
‘OSTaskStkChk [priority number of the Call was successful task depends on the size
(INTSU prio, task about which you of the stack for each
(OS_STK DATA _ want stack information. OS_PRIO_INVALID task and is, therefore,
*pdata); If the value prio is higher than nondeterministic.
OS_PRIO_SELFis __OS_LOWEST_PRIO or not equal
Location: passed then the stack of to OS_PRIO_SELF To calculate the total
‘sre/uC/os_task.c the calling task is stack size used add
checked. OS_TASK_NOT_EXIST OSFree and .OSUsed
‘Specified task does not exist together. Currently, all
pdata Of the stacks in the labs
pointer to a variable of OS _TASK_OPT_ERR are the same size (= 512
type OS_STK_DATA this value is returned if the task was bytes).
that is used by the created by OSTaskCreate or if
function (OS_TASK_OPT_STK_CHK was Don't call this function
not specified when the inside an ISR due to its
(OSTaskCreateExt call was used. _nondeterministic nature
and possible length of
Example:
time for completion.
0S_STK_DATA StackData;
BU
= OSTaskStkChk (OS_PRIO_SELF, StackData) ;
M1OSTaskQuery()
Function ‘Arguments Returns Notes
Prototype
INTSU prio (0S_NO_ERR You must allocate an
‘OSTaskQuery priority number of the task Call was successful (OS_TCB structure before
(INTSU prio, [about which you want task calling this function, and
‘OS_TCB information. If the value (OS_PRIO_ERR passing the pointer in as a
*pdata); OS_PRIO_SELF is passed Attempt to obtain parameter. Your copy
then the stack of the calling information from an invalid obtains a snapshot of the
‘Location: task is checked, task desired task's control block.
‘sre/uC/os_q.c
pdata (OS_PRIO_INVALID DO NOT modify any of the
pointer to a structure of type _prio is higher than fields in the OS_TCB
(OS_TCB, which contains a OS_LOWEST_PRIO or not |control blocks. Reading
‘copy of the task’s control block [equal to OS_PRIO_SELF them is sufficient for the
labs in CMPE401.
Example:
0s_TcB task data;
InTev err
err = OStaskQuery (0S_PRIO_SELF, étask_data) ;
Queue Functions
OSQCreate()
Funetion | Arguments Returns Notes
Prototype
(OS_EVENT * start 'A pointer to the event [Always create queues before using them.
OSQCreate base address _control block allocated to
(void **start, of storage area the queue is returned if Generally, queues are created for intertask
INTIOU size); the call succeeds. If it communication, One task posts a message and
size fails a NULL pointer is _ another task retrieves it. Otherwise race
‘Location: number of _ returned. ‘conditions could result and cause many
\sre/uC/os_q.c elements in ‘potential problems if tasks attempt to
the storage simultaneously access common resources.
area
Example:
begin (void)
i
*((int *)0x80) = (intyosctxsw; /* set up vector to Context Switch (TRAP
40) */
ostnit();
TaskCreate ("StartTask", StartTask, StartTask_ID);
osstart ();
)
void StartTask (void *data)
‘
12Scopernit ();
TickInit()7
FxQueueA = OSQCreate (TxQueueTbA, FIFO_SIZE);
TxQueueB = OSQCreate (TxQueueTb1B, FIFO_SIZE);
OstaskDel (0S_PRIO_SELF) ; /* This task only runs once */
)
OSQPendd,
Function ‘Arguments Returns Notes
Prototype
void * pevent If successful OSQPend Always create
‘OSQPend Pointer to queue from which the message is returns a message sent by a |queues before
(OS_EVENT tobe recieved. This is the same pointer that /task and *err contains using them and
*pevent, ‘was returned when the queue was created OS_NO_ERR. If don't call this
INTI6U using OSQCreate() unsuccessful a NULL function from
‘timeout, INTSU pointer is returned and *err inside an ISR
* er); timeout ‘contains one of the error
Pass in 0 if you want to wait forever for a codes as specified in the Messages are
‘Location: message. Pass a value in ticks (0 - 65535) arguments field. placed in the
‘sre/uC/os_q.c to give up on receiving the message after ‘queue by one
the period has lapsed. The function will task and
return and the task will resume once the retreived by
number of ticks has expired. ‘another.
err Call this
OS_NO_ERR function to
Message was received retrieve
possible
OS_TIMEOUT ‘messages.
Message was not received withing the
specified timeout. If multiple
tasks are
OS_ERR_EVENT_TYPE waiting fora
event is not pointing to a message queue message the
highest priority
OS_ERR_PEVENT_NULL task is
pevent is a NULL pointer resumed.
OS_ERR_PEND_ISR
‘This function was called from an ISR and
uC/OS-II must suspend the task. To avoid
this don't call this function from an ISR
Example:
LedQueueData = *(LED_DATA *)0SQPend(LEDQueue, 0, ferr); /* this will block
until a queue entry is available */
if (err)
disp_err(err);
13OSQPost()
Function ‘Arguments Returns | Notes
Prototype
INTSU pevent OS_NO_ERR ‘Always create Queues
|OSQPost Pointer to the queue into which Message was deposited in the _ before using them and
(OS_EVENT the message is deposited. Use queue. Jnever pass in NULL
*pevent, void the pointer that was returned [pointers as arguments,
*msg) ; when the queue was created OS_Q FULL |
using OSQCreate() ‘No room in the queue. |Use this function to
Location: ‘send a message to
srejuC/os.q.c msg
NULL pointer.
Example:
Pointer- sized variable that is
user defined. Don't post a
message queue.
OS_ERR_PEVI
msg is a NULL
void LedBufferPost (char num, char state)
‘
INTaU err;
if (LedBufferIndex >=10)
LedBuf ferIndex=0;
LedBuffer (LedBuf fer Index] .Ledvum
LedBuf fer (LedBufferIndex].State = state
err = OSQPost (LEDQueue, (void *) 6LedBuffer (LedBufferindex++]) ;
)
Semaphore Functions
OsSemCreate()
OS_ERR_EVENT TYPE
pevent is not pointing to a
pevent is a NULL pointer.
OS_ERR_POST_NULL_PTR
another task via a
previously created
queue.
ENT_NULL If muktiple tasks are
[waiting for a message
the highest priority
task is resumed.
pointer,
be from 0 - 65536.
Pass in 0 to indicate
that the resource is
not available.
‘Location:
sre/uC/os_sem.c
succeeds. If it fails
OSSemCreate returns a
NULL pointer
Function Arguments Returns Notes
Prototype
OS_EVENT* value (OSSemCreate returns [Always create semaphores before
(OSSemCreate [Initial value of the the created event control_|them.
\(INTIOU value); |semaphore that can block if the function
‘When creating semaphores the value
indicates how many tasks can obtain the
semaphore concurrently. Pass in 1 if the
semaphore is protecting a single resource
(Ge. a memory location). If there is more
than one resource available (ie. a block
of structures that can be assigned) then
pass in that number.
14Example:
OS_EVENT *TxSemA, *TxSemB, *TxBufferLock;
void StartTask (void *data)
‘
)
OSSemPend()
Function
Prototype
‘void
OSSemPend
(OS_EVENT
*“pevent,
INTI6U
‘timeout,
INTSU *ern)
Location:
‘sre/uC/os_sem.c
Scopetnit ();
TickInit ();
‘TxSemA = OSSemCreate (0) ;
TxSemB = OSSemCreate (0) ;
TxBufferlock = OSSemCreate (1);
Duartinit();
ostask0el (OS_PRIO_SELF) + /* This task only
Arguments Returns
pevent nothing
Pointer to the semaphore. This was returned when
the semaphore was created with OSSemCreate()
timeout
Pass in 0 if you want to wait forever for a message.
Pass a value in ticks (0 - 65535) to give up on
receiving the message after the period has lapsed.
‘The function will return and the task will resume
once the number of ticks has expired.
err
OS_NO_ERR
‘Semaphore is available
OS_TIMEOUT
‘Semaphore was not obtained withing the specified
timeout.
OS_ERR_EVENT TYPE
ppevent is not pointing to a semaphore
OS_ERR_PEVENT NULL
pevent is a NULL pointer
OS_ERR_PEND_ISR
‘This function was called from an ISR and uC/OS-
{II must suspend the task. To avoid this don't call
this function from an ISR.
runs once */
Notes
‘Always create semaphores
‘before using them.
‘Call this function when a
‘task needs to use a shared
resource safely, is waiting
for an event,or needs to
synchronize its activities
‘with an ISR or a task.
Note that this call blocks
while waiting for the
‘semaphore to be free. Don't
use this function from an
ISR use the non-blocking
‘OSSemAccept instead()
15Example:
void TxTask1 (void *data)
(
char byte;
char err;
while (1)
4
byte=0x41;
/* send the uppercase alphabet to TxA */
OSSemPend(TxBufferLock, 0, gerr) ;
while (byte <= 0x5a)
‘TxBufferPost (0, byte++)
‘TxBufferPost (0, CR);
TuButferzost (0, LE);
OSSemPost (TxBufferLock) ;
OSTimeDly (64) +
OSSemPost()
Function ‘Arguments Returns Notes
Prototype
INT8U pevent (OS_NO_ERR, ‘Always create semaphores
OSSemPost_ _Pointer to the ‘Semaphore has been signalled before using them.
(OS_EVENT semaphore. This was__or released.
*pevent); returned when the (Calling this function will
semaphore was created OS_SEM_OVF signal, or release the
Location: with OSSemCreate() Semaphore counts has semaphore so that another task
‘sre/uC/os_sem.c ‘overflowed (> 65535). ‘can obtain it. If the value is 0
OS_ERR_EVENT_TYPE
event is not pointing to a
semaphore
OS_ERR_PEVENT_NULL
ipevent is a NULL pointer
lor greater the value is
incremented and the function
returns to the caller.
Example:
void TxTask1 (void *data)
‘
char byte;
char err;
while (1)
byte=0x41;
/* send the uppercase alphabet to TxA */
OSSemPend(TxBufferLock, 0, éerr) ;
while (byte <= 0x5A)
‘TxBufferPost (0, bytet+)
‘TxBufferPost (0, CR);
TxBufferPost (0, LF);
OSSemPost (TxBufferLock) ;
ostimeDly (64) 7
16Time Functions
OSTimeDIy()
Function ‘Arguments Returns Notes
Prototype
void OSTimeDly [ticks |nothing |Use this function to reschedule a task
(INT16U ticks) ; Number of clock ticks to delay the current for a later time. Calling the function
task. (0- 65,535) (see with all parameters set to zero simply
‘Location: OS_TICKS_PER_SEC in configuration returns to the caller immediately.
src/uC/os_time.c file src/uC/os_cfg.h)
Example:
while (1)
(
J+ one second = 64 ticks*/
OstimeDly (64) >
)
OSTimeDlyHMSMQ
Function Prototype Arguments Returns Notes
void hours (0S_NO_ERR Use this function to
OSTimeDlyHMSM_ Number of hours of delay {Call was successful ‘reschedule the task
(INT8U hours, (0-255) for a later time.
INT8U minutes, OS_TIME_INVALID_MINUTES Calling the function
INTSU seconds, minutes ‘Minutes argument is greater than 59 |with all parameters
INT8U milli) ; Number of minutes of ‘set to zero simply
delay (0 - 59) (OS_TIME_INVALID_SECONDS returns to the caller
‘Seconds argument is greater than 59 immediately.
Location: seconds
sre/uC/os_time.e Number of seconds of || OS_TIME_INVALID_MILLI
delay (0 - 59) ‘Milliseconds argument is greater
than 999
milli
Number of milliseconds of |OS_TIME_ZERO_DLY
delay (0 - 999). |All arguments are given as zero
milliseconds are rounded
to nearest number of ticks
so be careful. Be aware of
tick rate when only using
milliseconds. If the
number of milliseconds
passed in is smaller that
one tick the delay may not
‘occur at all.
7Example:
while (1)
(
LEDValue = *(char *)O0SQPend(LEDQueue, 0, gerr);
if (err)
disp_err(err)+
urrent |= LEDValue;
LED = led_current;
(OSTimeD1yHMSM(0,0,0,50) 7
led_current &= ~LEDValue;
*LED = led current;
Embedded Linux
What is the difference between RTLinux and Linux
Desktop linux - a linux distribution installed on your desktop machine and intended for day-to day use, like
running an application at work, browsing, reading e-mail, writing documents, watching movies ete
Embedded linux - a linux distribution for embedded devices that control for example home appliances such
‘as DVDs, microwave ovens, washing machines - this linux has a very small footprint, since it has to run
inside a microcontroller with low resources (such as ARM, typically speeds of MHz or tens of MHz,
memory 4-8-16 MB) an itis reduced to the minimum components needed to do the job.
RTLinux - Real Time linux - as above, but with real-time constraints - the designer guarantees maximum.
response times for any operation, RT linux is used to control industrial machinery, in automotive
applications etc., where you must guarantee time responses and stability in order not to break expensive
machinery and potentially endanger human lives.
Embedded Linux system:
‘* An embedded system running the Linux kernel
‘© Userspace tools & configuration likely to be very different from desktop (uClibe instead of glibe,
BusyBox instead of coreutils, etc.)
¢ Embedded Linux development distribution:
© Includes all the tools and packages required for developing software for embedded Linux systems.
¢ Embedded Linux target distribution: Includes binaries and related packages to be used directly in
embedded Linux system.
Support for many embedded applications: Database (SQL Lite, Metalite), webserver (Boa, thttpd)
Graphics (PEG, Nano )
‘Types of embedded Linux systems
Embedded Linux systems are generally classified by criteria that would provide information about the
structure of the system. Thus it may be classified primarily on the basis of size and timing constraints.
18Size:
Linux features a micro-kernel architecture which actually consumes very little memory of about 100 KB
which combined with the networking stack and a few basic utilities can fit in quite nicely in 500 K of
‘memory and can be adapted to work with very little RAM and ROM (as low as 256KB ROM and 512KB
RAM). A few examples of small footprint Embedded Linux are ETLinux, LEM, uClinux, uLinux,
ThinLinux etc. The physical size of an embedded system determines the capabilities offered by the
hardware. There are three broad categories of the embedded LINUX on the basis of size: small, medium and
large.
‘Smalll Systems:
© Low powered CPU
* >4MB of ROM (Normally NOR Flash-based)
© 8to 16MBRAM
‘Medium-Size Systems:
Medium powered CPU
> 32 MB RAM (NOR Flash-based mainly, sometimes NAND Flash based)
64-128 MB RAM
(optional) NAND Flash -based secondary memory removable memory eards
Large-Size systems:
© powerful CPU/multiple CPUs
permanent storage
* large RAM
Different types of Embedded Linux versions
There are already many examples of Embedded Linux systems; it’s safe to say that some form of Linux can
run on just about any computer that executes code. The ELKS (Embeddable Linux Kernel Subset) project,
for example, plans to put Linux onto a Palm Pilot. Here are a couple of the more well-known small footprint
Embedded Linux versions:
ET Linux -- a complete Linux distribution designed to run on small industrial computers, especially PC/104
modules.
LEM -- a small (<8 MB) multi-user, networked Linux version that runs on 386s.
LOAE -- "Linux On A Floppy” distribution that runs on 386s.
uClinux -- Linux for systems without MMUs. Currently supports Motorola 68K, MCF5206, and MCF5207
ColdFire microprocessors.
uLinux -- tiny Linux distribution that runs on 386s.
‘ThinLinux -- a minimized Linux distribution for dedicated camera servers, X-10 controllers, MP3 players,
‘and other such embedded applications.
19Software and hardware requirements
Several user-interface tools and programs enhance the versatility of the Linux basic kernel. It's helpful to
Jook at Linux as a continuum in this context, ranging from a stripped-down micro-kernel with memory
management, task switching and timer services to a full-blown server supporting a complete range of file
system and network services.
A minimal Embedded Linux system needs just three essential elements:
«Aboot utility
+ The Linux micro-kernel, composed of memory management, process management and timing
+ An initialization process
To doing anything useful while remaining minimal, you also need to add:
+ Drivers for hardware
+ One or more application processes to provide the needed functionality
As additional requirements become necessary, you might also want:
+ A file system (perhaps in ROM or RAM)
«TCP/IP network stack
+ A disk for storing semi-transient data and swap capability
+ A32-bit internal CPU (required by all complete Linux systems)
Few applications areas :
Embedded Systems running through Linux
Smartphones, Tablets
* Development boards (PCBs)
+ Routers
= Robotics
20Kernel Subsystems:
1) Process management ~ Schedule all the processes and control multitasking
2) Memory Management ~ Manages the physical memory and provides memory mapping, shared virtual
memory, swapping ete
3) File system Management ~ Manages the file system including device files
4) Inter-Process Communication — Manages and control the communication between various processes
5) Network Interface ~ Provides network access to the Linux machine via protocols like TCP, UDP,
IPV4, IPV6 etc
6) Device driver — 1t forms a medium for the communication between various processes with the actual
hardware.
Linux Devices
Char device
_ Character and block devices.
_ char device— parallel port, LCD matrix display, or serial port or keypad or mouse.
— Character access — byte-by-byte and analogous to the access from and to a printer device.
Block device
+ block device—a file system (disk).
+ Linux permits a block device to read and write byte-by-byte like a char device or read and write block-wise
like a block device. A part of the block can be accessed
Net device
_ Annet device is a device that handles network interface device (card or adapter) using a line protocols, for
‘example tty or PPP or SLIP. A network interface receives or sends packets using a protocol and sockets,
and the kernel uses the modules related to packet transmission,
Registering and De-registering and related functions of Linux Modules
Action
* module initialization, handling the errors, prevention of unauthorized port accesses,
uusage-counts, root level security and clean up.
+ A module creates by compiling without main ()
+ A module is an object file.
+ For example, object modulel.o creates from modulel.c file by command $ gee ~c
{flags} modulel.c
init_module() + Called before the module is inserted into the kernel
+The function returns 0 if initialization succeeds and ~ve value if does not.
+ The function registers a handler for something with the kernel
+ Alternatively it replaces one of the kernel functions by overloading.
21insmod + Inserts module into the Linux Kernel. The object file modulel.o, inserts by command $
insmod modulel.o.
rmmod + A module file modulel_o is deleted from the kernel by command S rmmod
module!
cleanup + A kemel level void function, which performs the action on an rmmod call from the
execution of the module. The cleanup_module() is called just before the module is
removed. The cleanup_module() function negates whatever init_module() did and the
module unloads safely
Registering modules
‘register capability “A Kernel level function Tor registering
wnregister capability ‘A Kernel level function Tor deregistering
‘egister_symtab ‘Asymbol table function support, which exists as an alternative to declaring functions
and variables static
#include
finclude
#include
MODULE_LICENSE ("GPL");
static int init minimal_init (void)
i
return 0;
,
static void _exit minimal_cleanup(void)
i
,
module_init (minimal_init);
module exit (minimal_cleanup) +
IPC functions
+ Linux/ipe.h included to support IPCs
+ signals on an event— Linux header file Linux/signal.h, included to support
+ multithreading — Linux/pthread.h included
+ mutex and semaphores — Linux/sem.h included
+ Message queues — Linux/msg.h
Creating a POSIX thread.
1) Pthreads are created using pthread_create().
#include
int pthread_create (pthread t *thread_id, const pthread_attr_t ‘*attributes,
oid *(*thread_function) (void *), void arguments) ;
This function creates a new thread. pthread_t is an opaque type which acts as a handle for the new thread.
attributes is another opaque data type which allows you to fine tune various parameters, to use the defaults
pass NULL. thread_function is the function the new thread is executing, the thread will terminate when this
2function terminates, or it is explicitly killed. Arguments is a void * pointer which is passed as the only
‘argument to the thread_function,
2) Pthreads terminate when the function returns, or the thread can call pthread_exit () which terminates
the calling thread explicitly.
Int pthread_exit (void *status);
status is the return value of the thread, (note a thread_function returns a void *, so calling return(void *) is
the equivalent of this function.
3) One Thread can wait on the termination of another by using pthread_join()
Int pthread join (pthread t thread, void **status ptr);
‘The exit status is returned in status_ptr.
4) A thread can get its own thread id, by calling pthread_se1f ()
pthread_t pthread self ()7
5) Two thread id's can be compared using pthread_equal ()
Int pthread (pthread t tl, pthread _t t2);
Returns zero if the threads are different threads, non-zero otherwise.
Semaphores
sem_open( )function creates a new named semaphore or opens an existing named semaphore. After the
semaphore has been opened, it can be operated on using sem posi ) and sem wait( ). When a process has
finished using the semaphore, it can use sem _close( ) to close the semaphore, When all processes have
finished using the semaphore, it can be removed from the system using sem wnlink( ).
Mutexes
Mutexes have two basic operations, lock and unlock. If a mutex is unlocked and a thread calls lock, the
‘mutex locks and the thread continues. If however the mutex is locked, the thread blocks until the thread
‘holding’ the lock calls unlock.
There are 5 basic functions dealing with mutexes.
1) Note that you pass a pointer to the mutex, and that to use the default attributes just pass Nox for the
second parameter.
Int pthread _mutex_init (pthread mutex t *mut, const pthread_mutexattr_t tattr);
2) Locks the mutex :
Int pthread _mutex_lock (pthread mutex_t *mut);3)Unlocks the mutex
Int pthread_mutex_unlock (pthread mutex_t *mut);
4) Either acquires the lock if it is available, or returns EBUSY.
Int pthread_mutex_trylock (pthread_mutex_t *mut);
the mutex.
‘5)Deallocates any memory or other resources associated
Int pthread _mutex destroy (pthread mutex_t *mut);
A short example
Consider the problem we had before, now lets use mutexes:
‘THREAD 1 THREAD 2
pthread_mutex_lock (smut);
pthread_mutex_lock (smut);
a = data; 7* blocked */
att: 7+ blocked */
data 7+ blocked */
pthread mutex_unlock (amut); /* blocked */
b= data;
>:
data = b:
pthread _mutex_unlock (smut) ;
[data is fine. The data race is gone.]
Message Queue
‘The POSIX message queue API is as follows:
Funetion Summary
‘mq_open() Initialize a named queue
mq_close( close a message queue
‘mg_getattrt get the current attributes of a message queue
‘mq_notifvl) notify the calling process when the queue becomes nonempty
ma_opent open or create a message queue
mq _receive() _receive a message froma queue
‘mg_send{ put a message into a message queue
mq_setatt set the flags for a message queue
mg_unlink’) unlink (ie. delete) a message queue
24RT Linux
+ For real time tasks and predictable hard real time behaviour, an extension of Linux is a POSIX hard real-
time environment using a real time core.
+ The core is called RTLinuxFree and RTLinuxPro , freeware and commercial software respectively. V.
Yodaiken developed RTLinux, later FSM Labs commercialized RTLinuxPro and now Wind River has
acquired it.
+ Relatively simple modifications, which converts the existing Linux kernel into a hard real-time
environment,
+ Deterministic interrupt-latency ISRs execute at RTLinux core and other in-deterministic processing tasks
are transferred to Linux.
+ The forwarded Linux functions are placed in FIFO with sharing of memory between RTLinux threads as
highest priority and Linux functions running as low priority threads.
RTLinux Core for hard and soft real-time environment
1 a 3 4 5
Deterministic | [Primitive tasks | [Realtime task | [ FIFO connects | { Non-real-time
interrupt: with only with no realtime task | | processes of
latency ISRs__| | statically address space | | with Linux ‘applications
execute at allocated protection. processes, fun as the
RiLinux core. | | memory. nd fun with Shared memory | | Linux
Other in- No virtual disabling of| perform processes
deterministic | | memory Interrupts, Synchronization
processing allocation betwoen the
tasks Prionty hhard real time
transferred to | | allocation to tasks and the
Linux RT threads limited size
FIFO queues
RT Linux functions, Running RT Thread period definition, Real Time thread functions, s
Running RT Thread scheduling specifications
Figuret: RT Linux basic features
Running the task for hard real time performance has the following configuration:
_ Run the primitive tasks with only statically allocated memory.
~The dynamic memory allocation or virtual memory allocation introduces unpredictable allocation and
load timings
_ Run the real time task with no address space protection.
— The memory address protection involves additional checks, which also introduce the unpredictable
allocation and load timings
_ Run with disabling of interrupts so that other interrupts don’t introduce the unpredictability.
— Runa simple fixed priority scheduler.
— Run with disabling of interrupts so that other interrupts don’t introduce the unpredictability.
_ Runa simple fixed priority scheduler.
— Applications can be configured to run differently.
—RTLinux allows flexibility in defining realtime task behaviour, synchronization and communication
_RTLinux kernel designed with modules, which can be replaced to make behavior flexible wherever
possible
_ Applications run as the Linux processes.Programming with RTLinux
_ include rtlLmk ——/* Include RTLinux make file. The rt.mk file is an include file which contains all the
flags needed to compile the code. */
_all: modulel.o —_ /* Object file at modulel.o */
_ clean: rm-f.0 _/* Remove using function rm object files inserted before this file */
_modulel.0: modulel.c _/* module!.0 is object file of source file modulel.c */
_ S(cc) ${include} ${cflags}-c modulel.c __ /* Compile, include, Cflags C module modulel.¢ */
Functions in RTLinux
* The init_module() which is called when the module is inserted into the kernel. It should
return 0 on success and a negative value on failure.
+ The cleanup_module() which is called just before the module is removed
+ This command creates a module file named module.o, which can be inserted into the
kernel by using the ‘insmod’ command :
$ inanod module.o
+ Similarly, for removing the module, use the ‘rmmod’ command :
$ xmmod module
Creating RTLinux Threads
A realtime application is usually composed of several “threads” of execution. Threads are light-weight
processes which share a common address space. In RTLinux, all threads share the Linux kernel address
space. The advantage of using threads is that switching between threads is quite inexpensive when
compared with context switch.
RT thread functions
1) The init_module() invokes pthread_create(). This is for creating a new thread that executes concurrently
with the calling thread. This function must only be called from the Linux kernel thread (i.e., using
init_module())
int pthread_create(pthread_t * thread,
pthread_attr_t * attr,
void * (*thread code) (void *),
void * arg);
The new thread created is of type pthread_t, defined in the header pthread.h. This thread executes the
function thread_code(), passing it arg as its argument. The attr argument specifies thread attributes to be
applied to the new thread. If attr is NULL, default attributes are used.
So here, thread_code() is invoked with no argument. thread_code has three components - initialization, run-
time and termination,
2) In the initialization phase, is the call to pthread_make_periodic_np(.
int pthread make periodic _np(pthread t thread,
hrtime = start_time,
26hrtime_t period) ;
pthread_make_periodic_np marks the thread as ready for execution. The thread will start its execution
at start_time and will run at intervals specified by period given in nanoseconds.
3) gethrtime returns the time in nanoseconds since the system bootup.
hrtime_t gethrtime (void) ;
This time is never reset or adjusted. gethrtime always gives monotonically increasing values. hrtime_t is a
64-bit signed integer.
4) The only way to stop the program is by removing it from the kernel with the rmmod command. This
invokes the cleanup_module(), which calls pthread_delete_np() to cancel the thread and deallocate its
resources.
An example program
‘The best way to understand the working of a thread is to trace a real-time program. For example, the
program shown below will execute once every second, and during each iteration it will print ‘Hello World’
‘The Program code (file - hello.c) :
include
finclude
finclude
pthread_t thread;
void * thread_code (void)
i
pthread_make_periodic_np(pthread_self(), gethrtime(), 1000000000) ;
while (1)
‘
pthread_wai
rti_printt
Mp 7
Hello World\n");
}
return 0;
>
int init_module (void)
r
return pthread_create(sthread, NULL, thread_code, NULL);
,
void cleanup_module (void)
(
pthread_delete_np (thread) ;
,
Real-time FIFO Functions
Realtime FIFOs are First-In-First-Out queues that can be read from and written to by Linux processes
and RTLinux threads, FIFOs are uni-directional — you can use a pair of FIFOs for bi-directional data
exchange.
27To use the FIFOs, the systenvrtl posixio.o and fifos/rtl fifo.o Linux modules must be loaded in the
kemel, RT-FIFOs are Linux character devices with the major number of 150. Device entries in /dev are
created during system installation. The device file names are /dev/rtfO, /dev/rtfl, etc., through /dev/rtf63 (the
‘maximum number of RT-FIFOs in the system is configurable during system compilation).
Before a realtime FIFO can be used, it must be initialized: #include int rtf_create(unsigned int fifo, int
size); int rtf_destroy(unsigned int fifo); rtf create allocates the buffer of the specified size for the fifo buffer.
‘The fifo argument corresponds to the minor number of the device. rtf destroy deallocates the FIFO.
After the FIFO is created, the following calls can be used to access it from RTLinux threads: open(2) ,
read(2) , write(2) and close(2) .
Function Description
Tif create create a real-time fifo
rif-create_handler Tnstall a handler for real-time fifo data
if-create_rt_handler install a handler for real-time fifo data
Tif destroy Temove a real-time fifo created with rtf create
Ti flush empty a real-time FIFO
rif-get ead data from a real-time fifo
Tif link_user_jootl install an ioctl handler for a real-time FIFO
Vi put ‘write data to a real-time fifo
Tif make_ser_pair Thake a pair of RT-FIFOs act like a bidirectional FIFO
7il_allow interrupts ‘control the CPU interrupt state
il free_irg install and remove real-time interrupt handlers
Vil free_soft_irg install and remove software interrupt handlers
ril_get_soft_irg install and remove software interrupt handlers
vil_request_irg install and remove real-time interrupt handlers
28Tiny OS
Introduction
Most widely used operating system for sensor networks
* Sensor-actuator networks
+ Embedded robotics
* Developed at UC, Berkeley
+ tis written in the programming language nesC, as a set of cooperating tasks and processes.
Why TinyOS?
+ Traditional OSes are not suitable for networked sensors
Characteristics of networked sensors
‘= Small physical size & low power consumption
= Software must make efficient use of processor & memory, enable low power communication
= Concurrency intensive
‘= Simultaneous sensor readings, incoming data from other nodes
Many low-level events, interleaved / high-level processing
Limited physical parallelism (few controllers, limited capability)
* Diversity in design & usage
* Software modularity — application specific
‘TinyOS
TinyOS is a lightweight operating system specifically designed for low-power wireless sensors.
TinyOS differs from most other operating systems in that its design focuses on ultra low-power operation.
Rather than a full-fledged processor, TinyOS is designed for the small, low-power microcontrollers motes
have. Furthermore, TinyOS has very aggressive systems and mechanisms for saving power.
TinyOS makes building sensor network applications easier. It provides a set of important services
and abstractions, such as sensing, communication, storage, and timers. It defines a concurrent execution
model, bso developers can build applications out of reusable services and components without having to
worry about unforeseen interactions. TinyOS runs on over a dozen generic platforms, most of which easily
support adding new sensors. Furthermore, TinyOS’s structure makes it reasonably easy to port to new
platforms.
TinyOS applications and systems, as well as the OS itself, are written in the nesC language. nesC is
aC dialect with features to reduce RAM and code size, enable significant optimizations, and help prevent
Jow-level bugs like race conditions,
29‘What TinyOS provides
At a high level, TinyOS provides three things to make writing systems and applications easier:
+ a component model, which defines how you write small, reusable pieces of code and compose them
into larger abstractions,
+a concurrent execution model, which defines how components interleave their computations as well
as how interrupt and non-interrupt code interact,
+ application programming interfaces (APIs), services, component libraries and an overall component
structure that simplify writing new applications and services
‘Roplication
Tow) (ees) we) =i)
Figure: Example application architecture. Application code uses a timer to act periodically, sensors to
collect data, and a routing layer to deliver data to a sink.
Sensor Node Architecture
RFM Hx2000 670m Sm RFM RX2010
916.5 MHz Laser Dicde 916.5 MH
4K Flad
The component model is grounded in nesC. It allows you to write pieces of reusable code which
explicitly declare their dependencies. For example, a generic user button component that tells you when a
button is pressed sits on top of an interrupt handler. The component model allows the button implementation
to be independent of which interrupt that is — e.g., so it can be used on many different hardware platforms
— without requiring complex callbacks or magic function naming conventions.
The concurrent execution model enables TinyOS to support many components needing to act at the
‘same time while requiring little RAM. First, every /O call in TinyOS is split-phase: rather than block until
completion, a request returns immediately and the caller gets a callback when the I/O completes. Since the
stack isn't tied up waiting for /O calls to complete, TinyOS only needs one stack, and doesn’t have threads.
Any component can post a task, which TinyOS will run at some later time. Because low-power devices must
spend most of their time asleep, they have low CPU utilization and so in practice tasks tend to run very soon
30after they are posted (within a few milliseconds). Furthermore, because tasks can’t preempt each other, task
code doesn’t need to worry about data races
Finally, TinyOS itself has a set of APIs for common functionality, such as sending packets, reading
sensors, and responding to events, TinyOS’s Hardware Abstraction Architecture (HAA), which defines how
to build up from low-level hardware (e.g. a radio chip) to a hardware-independent abstraction (e.g. sending
packets),
TinyOS itself is continually evolving. Within the TinyOS community, “Working Groups” form to
tackle engineering and design issues within the OS, improving existing services and adding new ones
Networked, Embedded Sensors
‘TinyOS is designed to run on small, wireless sensors. Networks of these sensors have the potential to
revolutionize a wide range of disciplines, fields, and technologies. Recent example uses of these devices
include: Golden Gate Bridge Safety. High-speed accelerometers collect synchonized data on the movement
of and oscillations within the structure of San Francisco’s Golden Gate Bridge. This data allows the
maintainers of the bridge to easily observe the structural health of the bridge in response to events such as
high winds or traffic, as well as quickly assess possible damage after an earthquake .Being wireless avoids
the need for installing and maintaining miles of wires.
‘Volcanic Monitoring. Accelerometers and microphones observe seismic events on the Reventador and
Tungurahua volcanoes in Ecuador. Nodes locally compare when they observe events to determine their
location, and report aggregate data to a camp several kilometers away using a long-range wireless link.
‘Small, wireless nodes allow geologists and geophysicsts to install dense, remote scientific instruments ,
obtaining data that answers otherwise questions about unapproachable environments.
Datacenter Provisioning. Data centers and enterprise computing systems require huge amounts of
energy, to the point at which they are placed in regions that have low power costs. Approximately 50% of
the energy in these systems goes into cooling, in part due to highly conservative cooling systems. By
installing wireless sensors across machine racks, the data center can automatically sense what areas need
cooling and can adjust which computers do work and generate heat [12]. Dynamically adapting these factors
can greatly reduce power consumption, making the IT infrastructure more efficient and reducing
environmental impact.
While these three application domains are only a small slice of where networks of sensors are used,
they show the key differences between these networks and most other computing systems. First, these
“sensor networks” need to operate unattended for long periods of time. Second, they gather data from and
respond to an unpredictable environment. Finally, for reasons of cost, deployment simplicity, and
robustness, they are wireless. Together, these three issues — longevity, embedment, and wireless
communication ~ cause sensor networks to use different approaches than traditional, wired, and human-
centric or machine-centrie systems.
[sss] FRe=e |
—" 9-2
paten of seneors ‘ata sink
Figure 2: A typical sensor network architecture. Patches of ultra-low power sensors, running
nesC/TinyOS, communicate to gateway nodes through data sinks. These gateways connect to the larger Internet.
31The sheer diversity of sensor network applications means that there are many network architectures,
but a dominant portion of deployments tend to follow a common one, shown in Figure 2. Of ultra-low power
sensors self-organize to form an ad-hoc routing network to one or more data sink nodes.
These sensor sinks are attached to gateways, which are typically a few orders of magnitude more
powerful than the sensors: gateways run an embedded form of Linux, Windows, or other multitasking
‘operating system. Gateways have an Internet connection, either through a cell phone network, long-distance
wireless, or even just wired Ethernet.
Energy concerns dominate sensor hardware and software design. These nodes need to be wireless,
small, low-cost, and operate unattended for long periods. While itis often possible to provide large power
resources, such as large solar panels, periodic battery replacement, or wall power, to small number of
‘gateways, doing so to every one of hundreds of sensors is infeasible.
Anatomy of a Sensor Node (Mote)
Since energy consumption determines sensor node lifetime, sensor nodes, commonly referred to as
motes, tend to have very limited computational and communication resources. Instead of a full-fledged 32-
bit or 64-bit CPU with megabytes or gigabytes of RAM, they have 8-bit or 16-bit microcontrollers with a
few kilobytes of RAM. Rather than gigahertz, these microcontrollers run at 1-10 megahertz. Their low-
power radios can send tens to hundreds of kilobits per second, rather than 802.11"s tens of megabits. As a
result, software needs to be very efficient, both in terms of CPU cycles and in terms of memory use.
Cross-platform applications
Fig, TinyOS Hardware Abstraction Architecture (HAA)
Names and Program Structure
Program structure is the most essential and obvious difference between C and nesC. C programs are
composed of variables, types and functions defined in files that are compiled separately and then linked
32together. nesC programs are built out of components that are connected (“wired”) by explicit program
statements; the nesC compiler connects and compiles these components as a single unit, To illustrate and
explain these differences in how programs are built, we compare and contrast C and nesC implementations
of two very simple “hello world”-like mote applications, Powerup (boot and turn on a LED) and Blink (boot
and repeatedly blink a LED),
HelloWorld!
‘The closest mote equivalent to the classic “HelloWorld!” program is the “Powerup” application that simply
turn on one of the motes LEDs at boot, then goes to sleep.
AC implementation of Powerup is fairly simple:
include "note.h"
Ant main()
ed0_on()
sleep (0;
,
Listing .1: Powerup in C
‘The Powerup application is compiled and linked with a “mote” library which provides functions to
perform hardware initialization (mote init), LED control (led0 on) and put the mote in to a low-power sleep
mode (sleep), The “mote h” header file simply provides declarations of these and other basic functions. The
usual C main function is called automatically when the mote boots.
The nesC implementation of Powerup is split into two parts. The first, the PowerupC module, contains
the executable logic of Powerup (what there is of it...)
module Fowerupc (
uses interface Boo
uses interface Led:
)
implementation {
event void Boot-booted() {
call Leds. 1ed00n();
i
)
Listing .2: PowerupC module in nesC
This code says that PowerupC interacts with the rest of the system via two interfaces, Boot and Leds,
and provides an implementation for the booted event of the Boot interface that calls the led0On2 command
of the Leds interface. Comparing with the C code, we can see that the booted event implementation takes the
place of the main function, and the call to the led0On command the place of the call to the led0 on library
function.
This code shows two of the major differences between nesC and C: where C programs are composed
of functions, nesC programs are built out of components that implement a particular service (in the case of
PowerupC, turning a LED on at boot-time). Furthermore, C functions typically interact by calling each other
directly, while the interactions between components are specified by interfaces: the interface’s user makes
requests (calls commands) on the interface’s provider, the provider makes callbacks (signals events) to the
interface’s user. Commands and events themselves are like regular functions (they can contain arbitrary C
code); calling a command or signaling an event is just a function call. PowerupC is a user of both Boot
and Leds; the booted event is a callback signaled when the system boots, while the led0On is a command
33requesting that LED 0 be tumed on.
nesC interfaces are similar to Java interfaces, with the addition of a command or event keyword to
distinguish requests from callbacks:
interface Boot {
event void booted ()
)
interface Leds (
command void led00n() ;
command void led0Off () +
command void led0Toggle() :
Listing 3: Simple nesC interfaces
Ca) interface Ce)
The second part of Powerup, the PowerupAppC configuration, specifies how PowerupC is connected to
‘TinyOS's services:
configuration PowerupAppc { }
implementation (
components MainC, LedsC, PowerupC;
Mainc.Boot -> PowerupC. Boot:
PowerupC.Leds -> LedsC.Leds;
)
Listing .4: PowerupAppC configuration in nesC
Powerupe
fs
Mac Leds
Figure 2: Wiring Diagram for Powerup application
= |---| > I
nese Native
‘compiler compiler
Figure 3: The nesC compilation model. The nesC compiler loads and reads in nesC components,
which it compiles to a C file. This C file is passed to a native C compiler, which generates a mote binary
34This says that the PowerupAppC application is built out of three components (modules or
configurations), MainC (system boot), LedsC (LED control), and PowerupC (our powerup module).
PowerupAppC explicitly specifies the connections (or wiring) between the interfaces provided and used by
these components. When MainC has finished booting the system it signals the booted event of its Boot
interface, which is connected by the wiring in PowerupAppC to the booted event in PowerupC. This event
then calls the led0On command of its Leds interface, which is again connected (wired) by PowerupAppC to
the Leds interface provided by LedsC. Thus the call turns on LED 0. The resulting component diagram is
shown in Figure 2 — this diagram was generated automatically from PowerupAppC by nesdoc, nesC’s
documentation generation tool.
Essential Differences: Components, Interfaces and Wiring
The three essential differences between C and nesC — components, interfaces and wiring — all
relate to naming and organizing a program’s elements (variables, functions, types, etc). In C, programs are
broken into separate files which are connected via a global namespace: a symbolX declared in one file is
connected by the linker to a symbol X defined in another file. For instance, if £4 1e1 . contains
extern void g(void); /* declaration of g */
Ant main() /* definition of main */
(
a0: 907
)
and £ile2.c contains:
void q(void)
‘
printf ("hello world!");
i
then compiling and linking £i1e1.c and £i1¢2.c connects the calls to g () in main to the definition
of g in £1 1¢2 . c. The resulting program prints “hello world!” twice.
nesC’s components provide a more systematic approach for organizing a program’s elements. A
component (module or configuration) groups related functionality (a timer, a sensor, system boot) into a
single unit, in a way that is very similar to a class in an object-oriented language. For instance, TinyOS
represents its system services as separate components such as LedsC (LED control, seen above),
ActiveMessageC (sending and receiving radio messages), etc.
Interfaces bring further structure to components: components are normally specified in terms of the
set of interfaces (Leds, Boot, SplitControl, AMSend) that they provide and use, rather than directly in terms
of the actual operations. Interfaces simplify and clarify code because, in practice, interactions between
components follow standard patterns: many components want to control LEDs or send radio messages,
many services need to be started or stopped, ete.
Rather than connect declarations to definitions with the same name, nesC programs use wiring to
specify how components interact: PowerupAppC wired PowerupC’s Leds interface to that provided by the
LedsC component, but a two-line change could switch that wiring to the NoLedsC component (which just
does nothing):
components PowerupC, NoLeds¢;
PowerupC.LedsC -> NoLedsC.Leds;
without affecting any other parts of the program that wish to use LedsC.
35#include “note.h"
timer_t mytimer;
void Dlink timer fired(veid)
(
leds0_toggie()
)
int main()
(
mote_init()
timer_start periodic («mytimer, 250, blink timer_fired);
sleep()
)
Listing 5: Powerup with blinking LED in C
In this example, the Blink application declares a global mytimer variable to hold timer state, and calls
timer start periodic to set up a periodic 250ms timer. Every time the timer fires, the timer implementation
performs a callback to the blink timer fired function specified when the timer was set up. This function
simply calls a library function that toggles LED 0 on or off.
The nesC version of Blink is similar to the C version, but uses interfaces and wiring to specify the
connection between the timer and the application:
module BLinke (
uses interface Boot;
uses interface Timer;
uses interface Leds;
)
implementation (
event void Boot booted() |
eall Timer.startPeriodic (250) ;
)
event void Timer.fired() {
eall Leds. led0roggle():
)
)
Listing .6: Powerup with blinking LED in nesC (slightly simplified)
The BlinkC module starts the periodic 250ms timer when it boots. The connection between the startPeriodic
‘command that starts the timer and the fired event which blinks the LED is implicitly specified by having the
command and event in the same interface:
interface Timer (
command void startPeriodic(uint32_t interval);
event void fired();
)
Finally, this Timer must be connected to a component that provides an actual timer. BlinkAppC wires
BlinkC. Timer to a newly allocated timer MyTimer:
configuration BlinkAPPC ( }
implementation (
components MainC, LedsC, new TimerC() as MyTimer, BlinkC;
BlinkC.Boot -> Mainc.Boot:
BlinkC.leds -> LedsC.Leds;
BlinkC.Timer -> MyTimer.Timer;
)
Listing .7: Powerup with blinking LED configuration (slightly simplified)
36The -> and <- operators
‘The -> operators connect providers and users, binding callers and callees Let’s return to the
PowerupToggle application and step through how its wiring works. The module PowerupToggleC_uses the
Leds interface. The configuration PowerupToggleAppC wires PowerupToggleC.Leds to LedsC.Leds:
configuration ZowerupToggleappc ()
implementation (
components NainC, LedsC, PowerupTogglec;
PowerupToggleC.Boot. -> Main. Boot;
PowerupToggleC.Leds -> LedsC. Leds;
)
Listing .8: The PowerupToggleAppC configuration revisited
Leds
LedsC provides an abstraction of 3 LEDs. While some platforms have more or fewer than 3, the
Leds interface has 3 for historical reasons. Also, breaking up the LEDs into 3 instances of the same interface
would be a lot of extra wiring. In addition to LedsC, there is also a NoLedsC, which can be dropped in as a
null replacement: calls to NoLedsC do nothing.
configuration Ledsc (
provides interface Leds;
)
configuration NoLedsc (
provides interface Leds;
Printf
Sometimes, when debugging, it can very useful to have a mote send simple text messages. TinyOS
has a printf ~ like the C standard library function ~ library for this purpose. You can use printf in your
components, and the printf library will send appropriate packets over the serial port. You must start the
printf library via PrintfC’s SplitControl start.
configuration Printéc (
provides (
interface SplitControl as PrintfControl;
interface PrintfFlush;
)
i}
Example: Blink Configuration
configuration Blink {
)
implementation {
components Main, BlinkM, SingleTimer, LedsC;
Main.StdControl -> SingleTimer.stdControl;
Main.StdControl -> BlinkM.StdControl;
37BlinkM.Timer -> SingleTimer.Timer;
BlinkM.Leds -> LedsC;
)
Example: Blink Module
module 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 1000ms
return call Timer.start (TIMER REPEAT, 1000);
)
command result_t StdControl.stop() {
return call Timer.stop();
)
event result_t Timer. fired()
(
call Leds. yellowtoggle ()
return SUCCESS;
)
)
Difference in how programs are structured in C, C++ and nesC
In G, the typical high-level programming unit is the file, with an associated header file that specified and
documents the file’s behavior. The linker builds applications out of files by matching global names; where
this is not sufficient to express program structure (e.g. for callbacks), the programmer can use function
pointers to delay the decision of which function is called at what point.
C++ provides explicit language mechanisms for structuring programs: classes are typically used to
‘group related functionality, and programs are built out of interacting objects (class instances). An abstract
lass can be used to define common class specification patterns (like sending a message); classes that wish
to follow this pattern then inherit from the abstract class and implement its methods—Java’s interfaces
providesimilar functionality. Like in C, the linker builds applications by matching class and function names.
Finally, virtual methods provide a more convenient and more structured way than function pointers for
delaying beyond link-time decisions about what code to execute.
In nesC, programs are built out of a set of cooperating components. Each component uses interfaces
to specify the services it provides and uses; the programmer uses wiring to build an application out of
components by writing wiring statements, each of which connects an interface used by one component to
an interface provided by another. Making these wiring statements explicit instead of relying on implicit
name matching eliminates the requirement to use dynamic mechanisms (function pointers, virtual methods)
to express concepts such as callbacks from a service to a client.
38structural element
‘program unit
‘unit specification
ie lass ‘ompR
‘beader file class declaration component specification
specification pattem | — abstract class interface
‘unit composition | name matching name matching wiring
delayed composition | function pointer virtual method wiring
Table 1: Program Structure in C, C++ and nesC
Android OS
Introduction:
Android is a Linux based operating system it is designed primarily for touch screen mobile devices
such as smart phones and tablet computers. The operating system has developed a lot in last 15 years
starting from black and white phones to recent smart phones or mini computers. One of the most widely
used mobile OS these days is android. ‘The android is software that was founded in Palo Alto of California
in 2003.
The android is a powerful operating system and it supports large number of applications in Smart
phones. These applications are more comfortable and advanced for the users. The hardware that supports
android software is based on ARM architecture platform. The android is an open source operating system
means that it’s free and any one can use it, The android has got millions of apps available that can help you
‘managing your life one or other way and it is available low cost in market at that reasons android is very
popular.
‘The android development supports with the full java programming language. Even other packages that are
API and JSE are not supported. The first version 1.0 of android development kit (SDK) was released in 2008
‘and latest updated version is jelly bean.
Android Versions
Alll the versions of the Android are appears in Alphabetical Order. The version history is given below :
A: Alpha (1.1)
B: Beta (1.2)
39History of Android
> Android mobile operating system began with the release of the Android beta in
November 2007. The first commercial version, Android 1.0, was released in September
2008. Since then it has worked on Alphabetically literally!
A\pna
Beta
Cupcake (1.5)
Donut (1.6)
Eetair (2.0-2.1)
Froyo (2.2-2.2.3)
Gingerbread (2.
3.7)
Honeycomb (3.0-3.2.6)
Ice Cream Sandwich (4.0-4.0.4)
Jelly Bean (4.1-4.3.1)
\t (4.4-4.4.4)
Lollipop (5.0-5.1.1)
Marshmallow (6.0-6.0.1)
Cupcake Ice Cream Sandwich —_KitKat
icerrrke Support for saving attachments for MMS
nent Marquee in layouts,
API changes
errr
Nook Bluetooth A2DP and AVRCP:
. Uploading videos to YouTube and pictures to Picasa
enn
ern
Gees)
aaah ‘Multi touch software keyboard
. ‘Support for Extra Large screen sizes and resolution
Optimized tablet support with a new user interface
3D desktop
Video chat and Gtalk support
Fig. : Flow Chart Showing Various Updates In Original Version of Android
fon Aone Cenee
ey Py Cee
De
Peer ry
Ptr
ANDROID[~ 7]
SYMBIAN [= |
ome | Webkt See ee
iPhone OS
Cees
coe Cee Star Sey ey
ety St cry
6S
@
e
°
=
a
H
3
=
s
Fig: Various Mobile Operating System Available In Markets
Features of Android
As Android is open source and freely available to manufacturers for customization, there are no fixed
hardware and sofiware configurations. However, Android itself supports the following features:
41> Storage — Uses SQLite, a lightweight relational database, for data storage.
> Connectivity — Supports GSM/EDGE, IDEN, CDMA, EV-DO, UMTS, Bluetooth (includes A2DP and
AVRCP), WiFi, LTE, and WiMAX.
> Messaging — Supports both SMS and MMS.
> Web browser — Based on the open-source WebKit, together with Chrome’s V8 JavaScript engine
> Media support — Includes support for the following media: H.263, H.264 (in 3GP or MP4 container),
MPEG-4 SP, AMR, AMR-WB (in 3GP container), AAC, HE-AAC (in MP4 or 3GP container), MP3,
MIDI, Ogg Vorbis, WAV, JPEG, PNG, GIF, and BMP
> Hardware support — Accelerometer Sensor, Camera, Digital Compass, Proximity Sensor, and GPS
> Multi-touch — Supports multi-touch screens
> Multi-tasking — Supports multi-tasking applications
> Flash support — Android 2.3 supports Flash 10.1.
> Tethering — Supports sharing of Internet connections as a wired/wireless hotspot
Architecture of Android
In order to understand how Android works, take a look at Figure 1-1, which shows the various layers
that makes up the Android operating system (OS).
Home} (_comacts [rome ) [Browser ( )
a
(Pecos waraar ] (Teepron wanaer) [eswucemanmper ) ( tocton venaer )(Nostcaton wane)
Cans
(orteueeoe
ta = wm
Oisplay Driver Binder (PC) Driver
iN
g
lI
i
‘The Android OS is roughly divided into five sections in four main layers:
> Linux kernel — This is the kernel on which Android is based. This layer contains all the low level
device drivers for the various hardware components of an Android device.
> Libraries — These contain all the code that provides the main features of an Android OS. For example,
the SQLite library provides database support so that an application can use it for
data storage. The WebKit library provides functionalities for web browsing.
42> Android runtime — At the same layer as the libraries, the Android runtime provides a set of core
libraries that enable developers to write Android apps using the Java programming language. The Android
runtime also includes the Dalvik virtual machine, which enables every Android application to run in its own
process, with its own instance of the Dalvik virtual machine (Android applications are compiled into the
Dalvik executables). Dalvik is a specialized virtual machine designed specifically for Android and optimized
for battery-powered mobile devices with limited memory and CPU.
> Application framework — Exposes the various capabilities of the Android OS to application developers
so that they can make use of them in their applications.
> Applications — At this top layer, you will find applications that ship with the Android device (such as
Phone, Contacts, Browser, etc.), as well as applications that you download and install from the Android
Market. Any applications that you write are located at this layer.
The Required Tools
For Android development, we can use a Mac, a Windows PC, or a Linux machine. All the tools
needed are free and can be downloaded from the Web.
Eclipse
‘The first step towards developing any applications is obtaining the integrated development
environment (IDE). In the case of Android, the recommended IDE is Eclipse, a multi-language software
development environment featuring an extensible plug-in system. It can be used to develop various types of
applications, using languages such as Java, Ada, C, C++, COBOL, Python, ete.
For Android development, you should download the Eclipse IDE for Java EE Developers
(www. eclipse .org/downloads/packages/eclipse-ide-java-eedevelopers/heliosst1). Six editions are available:
Windows (32 and 64-bit), Mac OS X (Cocoa 32 and 64), and Linux (32 and 64-bit), Simply select the
relevant one for your operating system
Once the Eclipse IDE is downloaded, unzip its content (the eclipse folder) into a folder, say
C:\Android\.
Android SDK
The next important piece of software you need to download is, of course, the Android SDK. The
Android SDK contains a debugger, libraries, an emulator, documentation, sample code, and tutorials.
‘We can download the Android SDK from http:/developer.android,com/sdk/ index.html.
Once the SDK is downloaded, unzip its content (the android-sdk-windows folder) into the
C:\Android\ folder, or whatever name you have given to the folder you just created.
Android Development Tools (ADT)
The Android Development Tools (ADT) plug-in for Eclipse is an extension to the Eclipse IDE that
supports the creation and debugging of Android applications. Using the ADT, you will be able to do
the following in Eclipse:
> Create new Android application projects.
B> Access the tools for accessing your Android emulators and devices.
> Compile and debug Android applications.
> Export Android applications into Android Packages (APK).
> Create digital certificates for code-signing your APK.
To install the ADT, first launch Eclipse by double-clicking on the eclipse.exe file located in the eclipse
folder.
Anatomy of an Android Application
First, note the various files that make up an Android project in the Package Explorer in Eclipse .The
various folders and their files are as follows:
> sre — Contains the .java source files for your project.
> Android 2.3 library — This item contains one file, android jar, which contains all the class libraries
needed for an Android application.
> gen — Contains the R.java file, a compiler-generated file that references all the resources found in
your project.
> assets — This folder contains all the assets used by your application, such as HTML, text files,
databases, etc.
> res — This folder contains all the resources used in your application. It also contains a few other
subfolders: drawable-, layout, and values,
> AndroidManifest.xml — This is the manifest file for your Android application. Here you specify the
permissions needed by your application, as well as other features (such as intent-filters, receivers, etc.).
‘The main.xml file defines the user interface for your activity. Observe the following in bold:
The @string in this case refers to the strings.xml file located in the res/values folder. Hence, @string/hello
refers to the hello string defined in the strings xml file, which is “Hello World,
MainActivity!”:
He1loWorld
It is recommended that you store all the string constants in your application in this strings.xml file and
reference these strings using the @string identifier. That way, if you ever need to localize your application to
another language, all you need to do is replace the strings stored in the strings.xml file with the targeted
language and recompile your application.
‘Observe the content of the AndroidManifest.xml file:
<2xml_version="1.0" encoding="ut£-8"2>
The AndroidMani fest . xml file contains detailed information about the application:
> It defines the package name of the application as net . learn2deve lop. HelloWorld.
> The version code of the application is 1. This value is used to identify the version number of
your application. It can be used to programmatically determine whether an application needs
to be upgraded.
> The version name of the application is 1.0. This string value is mainly used for display to the
user. You should use the format: .. for this value.
> The application uses the image named icon. png located in the drawable folder.
> The name of this application is the string named app_name defined in the strings .xm1 file.
> There is one activity in the application represented by the MainActivity. java file. The label
displayed for this activity is the same as the application name.
> Within the definition for this activity, there is an element named :
«The action for the intent filter is named android. intent .act ion. MAIN to indicate that
this activity serves as the entry point for the application.
# The category for the intent-filter is named android . intent . category. LAUNCHER to
indicate that the application can be launched from the device’s Launcher icon
> Finally, the android:minSdkVers ion attribute of the element specifies the
minimum version of the OS on which the application will run.
‘As you add more fi les and folders to your project, Eclipse will automatically generate the content of
R.java, which at the moment contains the following:
package net. learn2develop.HelloWorld;
public final class R {
public static final class attr {
)
public static final class drawable {
public static final int icon=0x7£020000;
public static final class layout (
public static final int main=0x7£030000;
45public static final class string {
public static final int app_name=0x7£040001;
public static final int hello=0x7£040000;
)
)
Finally, the code that connects the activity to the UI (main . xm1) is the setContentView () method,
which is in the Mainactivity. java file:
package net. learn2develop.HelloWorld;
import android. app.Activity;
import android.os.Bundle;
public class MainActivity extends Activity (
7** Called when the activity is first created. */
@override
public void onCreate (Bundle savedInstancestate) {
super .onCreate (savedInstanceState) ;
setContentView(R. layout. main) ;
)
Here, R. layout .main refers to the main.xml file located in the res/ layout folder. As you add
additional XML files to the res / layout folder, the filenames will automatically be generated in the
R.java file. The onCreate () method is one of many methods that are fired when an activity is
loaded.
Activity Class
The Activity base class defines a series of events that governs the life cycle of an activity. The
Activity class defines the following events:
> onCreate () — Called when the activity is first created
> onStart () —Called when the activity becomes visible to the user
> onResume () — Called when the activity starts interacting with the user
> onPause () — Called when the current activity is being paused and the previous activity is
being resumed
> onStop () — Called when the activity is no longer visible to the user
> onDestroy () — Called before the activity is destroyed by the system (either manually or by
the system to conserve memory)
> onRestart () —Called when the activity has been stopped and
Application:
Displaying Notifications on the Status Bar
s restarting again,
For messages that are important, you should use a more persistent method. In this case, you should use the
Wot ificationManager to display a persistent message at the top of the device, commonly known as the
status bar (sometimes also referred to as the notification bar).1. Using Eclipse, create a new Android project and name it Notifications.
2. Add a new class file named NotificationView. java to the sxc folder of the project . In addition,
add anew notification. xm] file to the res/layout folder as well.
Populate the not ification. xm] file as follows:
://schemas .android.com/apk/res/android”
net learn2develop Notifications”
versionCode="1"
android: versionName="1.0">
Add the following statements in bold to the main . xm1 file’
context — Application context
> request code — Request code for the intent
> intent — The intent for launching the target activity
> flags — The flags in which the activity is to be launched
‘You then obtain an instance of the Not if icat ionManager class and create an instance of the
Notification class:
NotificationManager nm = (NotificationManager)
getSystemService (NOTIFICATION_SERVICE) ;
Notification notif = new Notification(
R.drawable. icon,
“Reminder: Meeting starts in 5 minutes”,
System. currentTimeMillis()) ;
The Notification class enables you to specify the notification’s main information when the notification
first appears on the status bar. The second argument to the Not i f icat ion constructor sets the “ticker tex”
‘on the status bar.
2 FSR tn WD
lent Netficaton
50Next, you set the details of the notification using the set LatestEvent Info () method:
CharSequence from = “system Alarm”;
CharSequence message = "Meeting with customer at 3pm...”;
notif.setLatestEventinfo(this, from, message, pendingintent) ;
//---100ms delay, vibrate for 250ms, pause for 100 ms and
// then vibrate for 500ns
notif.vibrate = new long[] { 100, 250, 100, 500);
‘The preceding also sets the notification to vibrate the phone. Finally, to display the notification you use
the notify () method:
nm.notify(notificationID, notif) ;
When the user clicks on the notification, the NotificationView activity is launched. Here, you dismiss
the notification by using the cance () method of the Not i ficat ionManager object and passing it
the ID of the notification (passed in via the Intent object):
//~--lock up the notification manager service---
NotificationManager nm = (NotificationManager)
‘getSystemService (NOTIFICATION SERVICE) ;
/J~--cancel the notification that we started
nm.cancel (get Intent () .getExtras() .getInt ("notificationID”)) ;