Вы находитесь на странице: 1из 10

HILAC: A framework for Hardware In the Loop

simulation and multi-platform Automatic Code


Generation of WSN Applications
Mohammad Mostazur Rahman Mozumdar

, Luciano Lavagno

, Laura Vanzago

, Alberto L. Sangiovanni-Vincentelli

University of California, Berkeley,


Electrical Engineering & Computer Sciences, 545H Cory Hall, 94720, CA, USA
Email: {mozumdar, alberto}@eecs.berkeley.edu

Dept of Electronics, Politecnico di Torino, Italy


Corso Duca Abruzzi 24, 10129
Email: luciano.lavagno@polito.it

STMicroelectronics
Milan, Italy
Email:laura.vanzago@st.com
AbstractHardware and software platforms for Wireless Sen-
sor Networks (WSNs) are almost as diverse as their application
areas, with very limited standardization. Moreover, heteroge-
neous programming abstractions put high barrier in application
development and there is hardly any support for application
debugging, except for a few blinking LEDs. Similar problems
have been solved in application domains that have similar cost
constraints, such as automotive, by the use of model-based design.
We address the lack of model-based design tools for the WSN
domain by providing a framework (based on Simulink, Stateow
and Stateow Coder) in which an application developer can
model a WSN application by using Stateow constructs and then
use a single model to perform multi-platform Hardware-In-the-
Loop (HIL) simulation and platform-specic application code
generation.
I. INTRODUCTION
Platforms for Wireless Sensor Networks (WSNs), including
processors, sensors, radios, power supplies, operating systems
and protocol stacks, are almost as diverse as their applica-
tion areas, with only a few standards (such as ZigBee [22],
6LoWPAN [11], etc) that address mostly the lower levels of
the radio protocol stack, and not the application API. Further
more most of the available sensor nodes on the market (such as
Mica [21], Tmote Sky [18], MotionBee [20]) only provide a
few on-board blinking leds for debugging. Although WSNs
have experienced great advancements in last decade, still
application development in this domain is quite challenging.
There is a lack of tools that can provide modeling, Hardware-
In-the-Loop (HIL) simulation and automatic code generation
for multiple platforms from a single high level abstraction. Just
like other embedded systems, WSN applications need to be
veried functionally before being implemented on the actual
platform in order to discover as many bugs as possible at a
high level, where xing them has a lower cost.
The available functional analysis packages, such as
TOSSIM [13] for debugging of TinyOS application, OmNet
and NS, fall into two main categories. One is very platform-
and OS-specic (such as TOSSIM), while the other includes
generic network simulators (such as OmNet, NS, etc). Both
have signicant drawbacks when it comes to complex appli-
cation development. The rst group makes it very expensive to
port an application to a different platform (e.g. from TinyOS
[14] to a ZigBee compliant platform). The second group
still leaves a lot of detailed platform-dependent code to be
developed and debugged. Integrated use of a network simulator
followed by a platform simulator is the most commonly used
path, but still requires one to port code between a number of
environments. Moreover, in case a bug is found at the end,
one has to resort to low level debugging, which is extremely
time-consuming and has to manually maintain the consistency
between the various code levels.
EmStar [9] tries to address this last problem by executing
the application in a simulation-like environment, but using
real-world I/O. It connects the simulation to the sensors
and radios of a real-deployed sensor network and thus helps
bridge the distance between simulation and the physical world.
However, it still does not address the issue of multi-platform
code development.
Our contribution is aimed at easing platform independent
WSN application development without compromising on the
efciency of the nal implementation. We propose a model
based framework (HILAC) built primarily on top of the Math-
Works tool chain. Application developers are able to model
applications using Stateow/Simulink [23] and perform HIL
simulation by interacting with the real sensor node. To remove
platform dependency from Stateow/Simulink modeling, we
developed a set of generic interfaces (for sending/receiving
packets and also for acquiring data from different sensors) and
an event mechanism, which ultimately allows developers to
978-1-4244-5841-7/10/$26.00 2010 IEEE 88 SIES 2010

WSN
aIgorthm
nItIaIIzatIon
phase
ContentIon
phase
TermInatIon?
xchange
phase
nd
o
Yes
CoordInator
nd evIce
Ember ZgBee
PIatform
TnyOS
PIatform
Code generaton for target pIatform
or
H smuIaton over seraI cabIe
AIgorthm modeIed n StatefIow {PC)
SIngIe modeI used Ior
anImated StateChart
debuggIng (II phase) and
code generatIon Ior TInyOs
and mber ZIgee
Fig. 1. A high level view of platform independent HIL simulation and code generation
specify applications in Stateow having no detailed knowledge
of target software systems. After HIL simulation, HILAC can
generate the complete application code for ZigBee and TinyOS
based platforms from a single Stateow application model. In
this paper we used the ZigBee stack provided by Ember [7] as
an example of target for code generation that is very different
from TinyOS. Adding more supported platform is quite fast
and requires writing some library software and changing some
scripts.
A high level view of the framework is shown in gure 1.
The WSN algorithm is modeled in Stateow and this single
model is used for multi-platform HIL simulation and also for
code generation. The application developer can thus use the
broad variety of debugging and analysis tools provided by
MathWorks, such as animated state chart displays, scopes,
plots, as well as exploit a large number of available pre-
designed Simulink blocks.
Our proposed framework is a substantial extension of the
work described in [2] where we proposed a framework for
modeling, simulation and automatic code generation for mul-
tiple WSN platforms based on MathWorks tools. One of the
obvious extensions of this work would be to support HIL
simulation and also to generate code from the same high level
model (for TinyOS and ZigBee stack). In [2], we required to
manually change the Stateow model to prepare it for the code
generation phase. In our new framework, we solve this issue
and propose a more automated solution (using the techniques
described in [3]) and model a realistic application.
In [12], the authors proposed a HIL simulation tool for
TinyOS called TOSHILT. They argued that HIL testing can
reveal design aws and software bugs that become evident
only when the code is executed on the target WSN platform. In
[6], a graphical development and simulation environment for
TinyOS-based applications, called Viptos, is described. Viptos
provides graphical development and interrupt-level simulation
of actual TinyOS programs, with packet-level simulation of the
network. It also allows the developer to use other models of
computation available in Ptolemy II [5] for modeling various
parts of the system. To model an algorithm using Viptos, the
users are bound to code it for TinyOS, which implies that the
user should have sufcient knowledge of TinyOS. In [15], the
authors propose a gdb based source level debugger only for
TinyOS.
In the macro/functional programming model, users do not
handle each individual node, but rather handle the network
application as a whole. Hence application developers specify
tasks at a higher level, hiding embedded system details and
node communication protocols. Macro/functional program-
ming based modeling approaches are described in EnviroTrack
[1], Kairos [10], Regiment [16] and aTaG [4]. All these
approaches suffer from a basic problem: non transparency.
The code that ends up being executed is very far from the
source. On the other hand, our approach handles node level
programming using a platform independent abstraction which
allows the developer to design and debug the behavior of the
application more precisely.
In all the approaches above, the authors attempted to address
scenarios like high level application modeling, HIL simulation,
debugging or code generation separately mostly for a specic
platform. But none of them is capable of performing appli-
cation modeling, HIL simulation and code generation from a
single high level abstraction that serves for multiple platforms.
978-1-4244-5841-7/10/$26.00 2010 IEEE 89 SIES 2010

WSN Appcaton
Functona Anayss by HlL smuaton
and animated state chart
debugging
No
Patform Independent Appcaton
Modeng usng Statefow
Need more
refnement?
Yes
System Target fes
for TinyOS
Generated Appcaton Code (TinyOS)
Statefow Coder
System Target fes
for Ember ZigBee
Generated Appcaton Code (Ember ZigBee)
Refned Statefow Mode
Modeling +
HlL Simulation
Automatic
Code
Generation
ANSI C code of WSN Appcaton
Sensor Node
(stub)
Sensor readng and
send/receve packets
Fig. 2. Design ow of platform independent Hardware-In-the-Loop simula-
tion and code generation for WSN applications
To the best of our knowledge, this is the rst time that a
framework of this sort has been developed and tested.
II. PLATFORM INDEPENDENT MODELING FRAMEWORK
The complete framework for platform independent applica-
tion modeling, hardware-in-the-loop simulation and automatic
code generation for multiple platforms is depicted in gure 1
while gure 2 shows the design ow based on it. The WSN
algorithm (application or middleware) is initially modeled as
a Stateow block. While modeling, the application developer
uses Stateow constructs (such as states, transition diagrams,
events, etc.) which are independent of the specic APIs and
programming languages (such as TinyOS or implementation
of ZigBee stack), and uses a set of library functions to interact
with sensors. The radio and the sensors physically reside on
the node, and are transparently accessed
either as prerecorded matlab streams of data, in the initial
phases of design,
or using a serial cable connection to the physical node,
when hardware-in-the-loop simulation is used.
This algorithm block is connected to other Stateow /
Simulink blocks that generate events from other software
or hardware components of the platform (such as CLK for
periodic scheduling and PKT for radio data reception). In
order to transparently support HIL simulation, these events
can come both from Simulink models or from the actual
node over a serial connection. The Stateow model can be
rened repeatedly, in order to tune the functionalities and
performance of the algorithm as shown in gure 2. At the end
of development, the same model also serves as an input for the
code generation phase. The rst step is to generate platform
independent ANSI C code from the Stateow algorithm model
using Stateow Coder. The next step is to adapt the generated
ANSI C code to the target platform. Target Language Compiler
(TLC) [24] scripts are used for this purpose. TLC provides
mechanisms to generate platform specic code by extracting
sections (such as includes, denes, functions, etc) from ANSI
C code and by adding custom code for the target platform.
Here the library functions that were used in the functional
simulation or during the HIL phase are replaced with platform
dependent implementations. By using TLC scripts (which are
also called System Target Files), the application developer now
can generate automatically for example a TinyOS application
(composed of .nc, .h and makeles) or an Ember ZigBee
application (composed of .c, .h and conguration les), and
then can compile and execute these applications for the target
platform without any modication.
Note that in this scenario we distinguish two roles, in
general belonging to different companies:
Application developers, who know the requirements of
the application domain and can ignore the details of the
various platforms.
Platform developers, who write libraries of code and the
corresponding TLC script for a specic node hardware,
protocol stack and OS.
This follows the platform-based design methodology [8]
[17]. In this work, we effectively create a Stateow and
Simulink -based system platform for WSN applications that
is more abstract and thus leads to more reusable applications,
than TinyOS or specic commercial custom platforms (e.g.
Ember ZigBee). This reusability does not incur almost any
penalty in terms of code size or execution time, essentially
thanks to the use of TLC scripts to rewrite and customize the
automatically generated code.
III. HARDWARE IN THE LOOP SIMULATION
Fig. 3. Setup for HIL simulation
Figure 3 depicts the setup for HIL simulation. It includes
mainly two entities: the stub code executed on the node
978-1-4244-5841-7/10/$26.00 2010 IEEE 90 SIES 2010
and the Simulink / Stateow block accessing this stub via
a serial (e.g. RS-232 or usb) cable. The stub contains basic
platform-dependent code to join or interact with a ZigBee or
TinyOS network, without any application-specic part. When
the stub receives a packet from the network, it stores the
packet locally and at the next request from the Stateow model
residing on the developer workstation (in PC), it transfers
the packet payload over the serial cable. In the same way,
when the stub receives a packet payload from the Stateow
model, it constructs the actual packet and transmits it to
the network. On the PC side, a Stateow block implements
the WSN algorithm and interacts with the stub for reading
sensors and also for sending or receiving packets to/from
the network. Other Simulink / Stateow blocks modeling, for
example, sensors, actuators, and radio power control support
smooth separation between the application model and HIL
components. In the following, we will use as an example of
three axis accelerometer provided by a hardware platform from
STMicroelectronics [20]. We will use it for HIL simulation
in two examples platforms that are very different from each
other: TinyOS and the ZigBee compliant Ember stack. But
the same methodology can be used to extend the framework
to any number and kind of WSN platforms.
A. Node Stub
In our example, we will perform HIL simulation with two
different platforms, hence we implemented two different stubs,
one for TinyOS and one for a ZigBee compliant platform. Each
stub contains device drivers and other basic software to support
the underlying platform. In addition, it includes a simple serial
protocol implementation that is used to communicate with the
Stateow blocks on the PC. This protocol is used for reading
data from sensors and also for sending or receiving packets
to/from the network respectively.
1) Stub Implementation on the TinyOS platform: The pro-
gramming model of TinyOS is based on components. In
TinyOS, a conceptual entity is represented by two types
of components : Module and Conguration. A component
implements interfaces. The interface declares the signature of
the commands and events which must be implemented by the
provider and user of the interface respectively. TinyOS uses
a split-phase asynchronous API calling mechanism. TinyOS
applications are written in nesC, which is an extension of the
C language.
A skeleton of the stub implementation in TinyOS is shown
in example 1. The main interfaces are listed below:-
SerialFrameComm: implements a byte transfer-level se-
rial protocol between the stub and the Stateow model.
LIS3LHiddenInit, LIS3LgetX, LIS3LgetY, LIS3LgetZ: ac-
quire data from a three axis accelerometer.
AMPacket, AMSend, SplitControl, Receive: send or re-
ceive packets to/from the network.
The SerialFrameComm.dataReceived event handler is called
when the stub receives a single byte from the serial line.
To maintain smooth communication, the serial protocol is
implemented using several transactions, all initiated by the
master (the PC). This is similar to the USB protocol, but can
be implemented on top of any serial connection (USB, RS-
232, etc.). The protocol uses the following byte coding for
interacting with the Stateow model on the PC:
SENDPKT (50): When the stub receives this value at
the starting of a new transaction, it knows that it is
going to receive a packet payload from the PC. The
next byte should be the length of the payload followed
by consecutive bytes of the payload. After receiving a
complete packet, it constructs the physical packet and
broadcasts it to the network.
GETPKTCNT (60): After receiving this value from the
PC, the stub sends a byte which contains the number of
currently stored received packets.
GETPKT (61): After receiving this value, the stub trans-
fers the received packet to PC. Afterwards, it removes the
packet payload from the queue. When the stub receives
a packet from the network, the stub stores it in the local
queue and then transfers it to the PC by using transactions
GETPKTCNT and GETPKT.
GETACCELXAXIS (75): After receiving this value from
the PC, the stub calls LIS3LgetX.get to read the X
axis value of the three axis accelerometer. This is an
async command whose result is returned by calling
the LIS3LgetX.getDone event handler. Inside this event
handler, the stub transfers two consecutive bytes of the
result to the PC. Note how a split-phase call (get/getDone)
on the TinyOS side is viewed as an asynchronous call
on the Stateow side, where the application receives the
result as a callback also when the target is a ZigBee node
(the converse is also possible, i.e. a synchronous call in
StateFlow being handled transparently as split-phase in
TinyOS). The application programmer can thus ignore the
tasking model and other architecture details of the target
platform. Our HIL and code generation framework takes
care of generating the most efcient implementation.
GETACCELYAXIS (76) and GETACCELZAXIS (77) per-
form the same for the Y and Z axis.
Example 1: Skeleton of the stub implementation in TinyOS
module StubNodeTinyOsM
{
uses interface SerialFrameComm;
...
}
implementation
{ ....
// Sending X axis value of the accelerometer to PC
event void LIS3LgetX.getDone(uint16_t xAxisValue, error_t success){
call SerialFrameComm.putData((uint8_t)xAxisValue);
call SerialFrameComm.putData(xAxisValue>>8);
return;
}
// Sending Y axis value of the accelerometer to PC
event void LIS3LgetY.getDone(uint16_t yAxisValue, error_t success){
//Similar as LIS3LgetX.getDone implementation
}
// Sending Z axis value of the accelerometer to PC
event void LIS3LgetZ.getDone(uint16_t zAxisValue, error_t success){
//Similar as LIS3LgetX.getDone implementation
}
// Impl of Serial protocol SENDPKT,GETPKTCNT,GETPKT,GETACCELXAXIS,..
async event void SerialFrameComm.dataReceived(uint8_t data){
.....
switch(data){
case 50: //process SENDPKT command of serial protocol
break;
......
}
return;
}
..........
978-1-4244-5841-7/10/$26.00 2010 IEEE 91 SIES 2010
}
2) Stub implementation on the Ember platform: ZigBee
is a specication that enables reliable, low power, wirelessly
networked, monitoring and control products based on an open
global standard. It includes mechanisms for forming and
joining a network, a CSMA mechanism to wait for a clear
channel, as well as retries and acknowledgment of messages
for reliable communication between adjacent devices. The
ZigBee specication supports networks with one coordinator,
multiple routers, and multiple end devices within a single
network. Details of the ZigBee specication can be found in
[22].
ZigBee is different from TinyOS, in that it species only
the protocol, not the concrete API, nor the scheduling and
inter-task communication model. Several implementations of
the ZigBee stack are available on the market (e.g. from
Texas Instruments, Ember Corporation, Freescale, etc.). We
will describe our stub implementation by using the Ember
stack [7]. The stub implementation for HIL simulation is an
end device type, so it joins a ZigBee network formed by the
coordinator. A skeleton of the stub implementation is shown
in example 2.
Example 2: Skeleton of the stub implementation in the Ember ZigBee stack
#include ....
// Global and ZigBee specific variables
EmberEndpointDescription PGM .....
// Entry point of an Ember ZigBee application
int main(void)
{ halInit(); // Initialize the hardware abstraction layer
INTERRUPTS_ON(); // Allow interrupts
emberInit(...); // Initialize the Ember ZigBee stack
setLis3lParameters(); // Initialize accelerometer parameters
while(TRUE) { // Main application loop
halResetWatchdog();
emberTick();
processSerialInput(); // Implementation of Serial protocol
applicationTick(); // WSN application code
}
}
// Read X axis: high byte<<8 + low byte
int16u getAccXAxisValue(void){
return (halCommonSpiReadWrite(0xa9) << 8) + halCommonSpiReadWrite(0xa8);
}
int16u getAccYAxisValue(void){ ..... }
int16u getAccZAxisValue(void){ ..... }
// Implementation of serial protocol
void processSerialInput(void){
....
// similiar as TinyOS implementation
if( emberSerialReadByte(APP_SERIAL, &cmd) == 0) {
switch (cmd){
case 50: //process SENDPKT command of serial protocol
break;
}
}
}
The main source le of an Ember ZigBee application
must begin by dening some parameters involving endpoints,
callbacks and global variables. Just like C, an application starts
from main. Inside the main procedure, it needs to initialize
the Hardware Abstraction Layer (HAL), turn on interrupts and
then initialize the radio and stack. After stack initialization, the
application enters into an event loop. In this loop, the network
state is checked once per cycle.
The serial protocol for HIL simulation is implemented
inside the processSerialInput procedure, which is quite similar
to the implementation in TinyOS. Inside the event loop, pro-
cessSerialInput is called at each cycle to check the data from
the serial line. If there is any, then the ZigBee stub responds
based on the same protocol as in the TinyOS case. In the
Ember ZigBee implementation, when a node receives a packet,
then emberIncomingMessageHandler is called. After receiving
a packet from the network, the stub stores the packet payload
(and then transfers it to the PC with transactions GETPKTCNT
and GETPKT). When a packet payload is received from the PC
(during SENDPKT), the stub constructs a ZigBee packet and
broadcast it to the network by calling emberSendBroadcast. To
access sensor data from accelerometer, the stub uses APIs like
getAccXAxisValue, getAccYAxisValue and getAccZAxisValue
during transactions GETACCELXAXIS, GETACCELYAXIS and
GETACCELZAXIS.
B. HIL simulation framework in Simulink/Stateow
Fig. 4. Top view of the HIL framework in Simulink/Stateow
The user level view of the HIL framework on the Simulink
/ Stateow side is shown in gure 4. In this section we will
explain the mechanisms of HIL simulation and in the next
section we will describe a realistic application that has been
modeled using the platform APIs provided by this framework.
Here we will show how to use both a Stateow event (for
asynchronous packet reception) and a Stateow function call
(for polled sensor reading) to transfer data from the stub node
to the application modeled in Stateow. A Simulink pulse
generator is used to generate the periodic CLK event, which
is sent to both serial port packet reader and wsn application
(shown in gure 4). The serial port packet reader repeatedly
checks with the stub node whether a packet has been received
from the radio ( by using transaction GETPKTCNT ). If so, it
reads the packet from the stub by using transaction GETPKT
and generates a packet event (PKT) to the WSN application
block.
wsn application is a Stateow block which implements the
algorithm that will be used for HIL simulation and also for
code generation. It takes two input events CLK and PKT. Here,
we will describe the main points at which Stateow interacts
with the stub (for reading sensor data and sending packets to
the network) and the matlab base workspace (for accessing
packet payloads after receiving the PKT event). We developed
several embedded matlab function such as:
978-1-4244-5841-7/10/$26.00 2010 IEEE 92 SIES 2010
getAccXAxisValue, getAccYAxisValue and getAccZAxis-
Value : To read the X, Y and Z axis values of the
accelerometer mounted on the hardware node, via the
stub.
sendPacket: To send a packet payload to the stub, which
will broadcast it to the network.
getPacketPayload: To get the received packet payload
from the matlab base workspace (where it is stored by
serial port packet reader).
{//For other sensors}
[sensorCode == ACCELEROMETER]
[channel==ZAXIS]
{//perform computation with data}
[channel==XAXIS]
{//perform computation with data}
[channel==YAXIS]
{//perform computation with data}
Function sensorReading(sensorCode,channel,value)
Fig. 5. Stateow function sensorReading - used to return sensor reading to
the Stateow application model
A template implementation of the getAccXAxisValue is
listed in example 3. Here, after establishing the connection
with the COM port, it sends GETACCELXAXIS over the serial
port to read the X axis value of the accelerometer and then
waits for two byte results. After receiving the results, it calls
Stateow function sensorReading (shown in gure 5), which
is the entry point for all sensors that return back results to
Stateow. By doing this, we create a uniform abstraction
mechanism for both synchronous and asynchronous sensor
reading, both for TinyOS and Ember ZigBee. Acquiring data
from the accelerometer is done asynchronously in TinyOS
and synchronously in Ember ZigBee. But from the application
viewpoint we are accessing sensors asynchronously for both
platforms. We divided the access into:
a down call (for example, getAccXAxisValue) to request
data from sensor and
an up call (sensorReading) which returns the sensor data.
The same methodology can be used for all sensors that
return values. This will make code generation most convenient
for both synchronous and asynchronous sensor reading (as
explained in detail in section 5). As an alternative, such
asynchronous readings could also be implemented as Stateow
events, if the Stateow machine needs to respond immediately,
rather than at the next CLK event. When the wsn application
needs to send a packet it calls sendPacket. The sendPacket
function takes the payload of the packet as an input and
sends it to the stub by using transaction SENDPKT. When
wsn application receives PKT event, it calls getPacketPayload
which transfers the packet of the payload from the mat-
lab workspace (stored by serial port packet reader) to the
wsn application block.
Example 3: Skeleton of getAccXAxisValue implementation in embedded
matlab
function getAccXAxisValue
s = serial(COMXX); % COM port where stub is connected
....
xAxisReading=zeros(2,1,uint8);
protocolDataToStub=75; % GETACCELXAXIS, Read X axis value from accelerometer
fwrite(s,protocolDataToStub); % Sending request to the stub node
for nByte=1:2
xAxisReading(nByte)=fscanf(s,%u); % Data sent by the stub node
end
....
sensorCode=ACCELEROMETER;
channel=XAXIS;
% Call back to Stateflow model
sensorReading(sensorCode,channel,bitshift(xAxisReading(2),8)+ xAxisReading(1));
end
IV. A REALISTIC APPLICATION EXAMPLE
To validate our HIL simulation and code generation frame-
work, we used a realistic application that consists of a virtual
machine oriented to data processing in body sensor networks
which is very similar to SPINE [19] (Signal Processing In
Node Environment). A SPINE node is able to perform some
computations (such as max, min, median, etc.) based on
collected data sets from sensors. The parameters of these com-
putations (called features) such as sampling rate, window,
shift of data set, etc. can be tuned and the features can be
activated or deactivated depending on the application demands.
Parameter tuning and de/activation of features can be done at
run time. One of the prominent applications of SPINE is to
detect body movements, hence a three axis accelerometer is
used in our SPINE implementation. Our simplied version
of SPINE in Stateow contains 3 parallel state machines and
23 Stateow functions, which implement the following main
functionalities :-
Scheduler: It manages the active tasks of the system. A
task is composed of : reading a specic sensor at specied
interval (sampling rate), storing the sensor readings into a
circular buffer and then calculating features (for example
max, median, etc.) using the stored data based on given
window/shift value. After computing a feature, it sends
the result to the base station.
Circular buffer: It is used to store sensor readings in
multiple circular buffers called segments. Each segment
is used to store sensor readings from a specic sensor
and channel (for example x, y or z axis values of the
accelerometer).
Packet processor: It decodes incoming conguration
packets that are sent by the base station to congure
activities of the sensor node.
Features: Our simplied SPINE can perform some com-
putations (such as max, min, median, etc.) on the data
sets stored in circular buffers.
The parallel state machines (taskProcessingEngine, pktPro-
cessingEngine and scheduler) process events like CLK, PKT
(external) and TASK (internal). A snapshot of these state
machines is shown in gure 6. Initially, these three state
machines start in parallel and after initialization wait for
incoming events to be processed immediately. The base station
activates tasks by sending several conguration packets. When
pktProcessingEngine receives a PKT event (generated by
978-1-4244-5841-7/10/$26.00 2010 IEEE 93 SIES 2010
function taskEvent()
{TASK}
function pktEvent()
{PKT}
function clkEvent()
{CLK}
InitTaskProcessingEngine/
.
waitingForTaskEvent/
processTASK/
processingTask(getCurrentActiveTask());
TASK
InitProcessingEngine/
initCircularBuffer();
waitingForPacketEvent/
processPKT/
getPktData(packetBuffer);
parsePktData();
PKT
initTimer/
resetTimer();
waitingForTimerEvent/
processCLK/
increaseSystemTick();
updateTasks();
CLK
taskProcessingEngine/ pktProcessingEngine/ scheduler/
Fig. 6. Three parallel state machines of SPINE
serial port packet reader), it immediately calls getPktData
which copies the packet payload into a local buffer (pack-
etBuffer). Afterwards, it calls parsePktData (shown in gure
7) which processes different types of conguration packets.
[pktType==03]
{setupSampTimeSensor()}
[pktType==05]
{setupParamsForSensor()}
[pktType==07]
{setupFeature()}
[pktType==09]
{startSpineApp()}
Function parsePktData
{ pktType = packetBuffer[0] & 0x1F; }
Fig. 7. Stateow function parsePktData - used to parse conguration packets
sent by the base station
In our simple SPINE implementation, we process four
different types of packets that are used to congure the basic
SPINE virtual machine:
Packet Type 3: It contains data that are used to congure
the sampling time of individual sensors.
Packet Type 5: It contains general information to setup
features such as window (number of samples needed to
compute a feature for the rst time) and shift (number of
samples needed to compute a feature after the rst time).
Packet Type 7: It contains data about the features (max,
mean, etc.) that need to be activated or deactivated. It
also contains information on which sensor and channel
(x-axis, y-axis, etc ) must be used for these features.
Packet Type 9: This packet is used to start/stop all the
tasks managed by the SPINE engine.
For example, The Stateow function setupSampTimeSensor
parses packet type 3. It extracts the sampling scale (millisec-
ond, second or minute) from the payload data. Afterwards,
it extracts the sensor code and sampling coefcients and
then calculates the sampling time for that sensor and inserts
it in the active sensor list. Similarly, setupParamsForSensor
extracts the window and shift value for each active sensor, and
setupFeature selects the features that need to be calculated.
The setupFeature function also assigns which portion of the
circular buffer will be used for each specic feature. Finally,
the startSpineApp function adds all the features as active tasks
in the scheduler.
The scheduler, after initialization, waits for the CLK event.
At each CLK event, it increments the system timer count
and then calls updateTasks. Inside updateTasks, it checks the
sampling time for each active task. When a task needs to
acquire data from a sensor, it is activated by generating a
TASK event for the taskProcessingEngine.
{// Other Sensors}
[sensorCode==10]
{//accelerometer}
[channel==2]
{// get acc value of z-axis
getAccZAxisValue();}
[channel==1]
{// get acc value of y-axis
getAccYAxisValue();}
[channel==0]
{// get acc value of x-axis
getAccXAxisValue();}
Function acquireSensorData (taskID,sensorCode,channel)
Fig. 8. Stateow function acquireSensorData - used to read sensor data from
different sensors
The taskProcessingEngine waits for TASK events to process
the active task by calling the processingTask function. Inside
processingTask, it decides whether the type of the task is an
alarm or a feature. If it is a feature, it calls acquireSensorData
(shown in gure 8) to collect data from sensors. The acquire-
SensorData function uses system platform calls (implemented
as matlab function for HIL simulation or C function calls
for code generation) to read sensor data from the stub over
the serial cable. After reading sensor values, these functions
call sensorReading (shown in gure 5) which stores the
acquired sensor data into the specied segment of the circular
buffer. When adequate data sets are available in the circular
buffer, the state machine computes the specied feature (max,
mean, etc.) of each active task. It then constructs a payload
978-1-4244-5841-7/10/$26.00 2010 IEEE 94 SIES 2010
with the feature result and sends it to the stub by using the
sendPacket Stateow function. After receiving the payload, the
stub constructs a platform-specic packet and broadcasts it to
the network.
The intrinsic motivation behind modeling SPINE in Staow
is to elaborate some essences of model based design such as
simplicity, platform independent application modeling, graphi-
cal debugging (built in feature of the Stateow) and afterwards
platform dependent code generation.
V. MULTI-PLATFORM CODE GENERATION

StatefIow
Coder
Target anguage
CompIer {TC)
ANS C code
Ember ZgBee Code
TnyOS Code
TC scrpt{ZgBee)
StatefIow modeI of WSN appIcaton
TC scrpt{TnyOS)
Fig. 9. Multi-platform code generation from Stateow
As mentioned above the WSN algorithm is modeled inside
wsn application. Hence we need to generate platform specic
code only for this block by following some steps. The whole
ow is depicted in gure 9. At rst we have to create a custom
Stateow target for ANSI C code generation which will
automatically generate code for the wsn application block.
The computational bodies of the Ember functions, as well
as those of the TinyOS tasks and event handlers are essentially
written in C. So the code generated from Stateow coder can
be directly ported to Ember and TinyOS with almost no modi-
cation. Like stubs for HIL simulation, we developed platform
base code for TinyOS and Ember platforms that will interact
with the ANSI C code generated from the Stateow model of
the application. This code also contains platform specic im-
plementation of all down calls (sendPacket, getPacketPayload,
getAccXAxisValue , etc.). Passing events (such as CLK, PKT,
etc.) from platform base code to generated ANSI C, is more
complex and is done as follows. Besides algorithm modeling,
we also implemented three event functions pktEvent, clkEvent
and taskEvent. These functions are not used for HIL simulation
but play the vital role of entry points for up call events in
the generated code (shown in gure 10). So, when we need to
pass a PKT event, we just call the procedure pktEvent from the
platform base code, which in turn calls the generated code of
the wsn application block with the corresponding PKT event.
In the following subsections, we will describe how the down
calls from Stateow code and up calls from the platform base
code have been glued with each other for both platforms.
A. TinyOS platform
Skeletons of the TinyOS specic base code are shown in
example 4. To send the CLK event to the application, we used
a periodic timer (Timer0 in the example). Since this le will
be automatically generated by TLC scripts, we can decide the
duration of the CLK pulse at code generation time. On each
occurrence of the periodic timer, the clkEvent procedure (up-
call to the wsn application) will be called. In TinyOS, the
driver implementation of the STM three axis accelerometer is
done asynchronously (split-phase). The wsn application code
calls getAccXAxisValue (down-call) to read the x-axis value of
the accelerometer. Inside this function we call LIS3LgetX.get
which returns immediately. Afterwards, when the value is read
from the accelerometer, the driver calls LIS3LgetX.getDone
with the sensor value. Inside this function, we call sensorRead-
ing (up-call with values) which provides the sensor reading to
wsn application. On the other hand, synchronous reading is
fairly easy because we can call sensorReading inside the same
procedure just after getting the values from sensors.
When a TinyOS node receives a packet, it calls the
Receive.receive event with the payload of the packet. In-
side this event handler, we store the packet locally and
then call pktEvent (up call) which will provide the PKT
event to the wsn application. After receiving the PKT event,
wsn application calls getPktData (down call) which copies
the stored payload to the internal data structures of the
wsn application.
Example 4: Skeleton of platform base code in TinyOS
module wsn_applicationM
{ ...}
implementation
{
......
event void Boot.booted(){
.....
call Timer0.startPeriodic( 10 ); //CLK pulse in every 10ms
}
event void Timer0.fired() {
clkEvent(); //Up Call: Sending CLK event to the wsn_application
}
event void LIS3LgetX.getDone(uint16_t xAxisValue, error_t success){
//Up Call: Returning X-axis value of the ACCELEROMETER to the wsn_application
sensorReading(accelerometer,xaixs,xAxisValue);
return;
}
// Down Call: To read the X-axis value of accelerometer
void getAccXAxisValue() @C() @spontaneous() {
call LIS3LgetX.get ();
}
// Down Call: Construct packet with payload and broadcast it.
void sendPacket(char* payload) @C() @spontaneous(){
...
}
event message_t* Receive.receive(message_t* msg, void* payload, uint8_t len) {
// Store packet payload locally
pktEvent(); // Up Call: Send PKT event to wsn_application
....
}
// Down Call: To get the payload of the packet
void getPktData(char* payload) @C() @spontaneous() {...}
}
B. Ember platform
A skeleton of the Ember specic base code is shown
in example 5. Inside applicationTick, we generate the CLK
event for wsn application by calling clkEvent. The function
applicationTick is part of the Ember event loop, where at
rst we check whether the node has already joined in the
network or not. If so, in a periodic manner it calls the clkEvent
procedure (sending the CLK event to the wsn application).
978-1-4244-5841-7/10/$26.00 2010 IEEE 95 SIES 2010
function pktEvent()
{PKT}
void pktEvent(void)
{
unit8_T b_previousEvent;
b_previousEvent = _EventWsnApp;
_EventWsnApp = event_PKT; // PKT event
wsn_application(); //ANSI C code of the algorithm
_EventWsnApp= b_previousEvent;
}
void clkEvent(void)
{
unit8_T b_previousEvent;
b_previousEvent = _EventWsnApp;
_EventWsnApp = event_CLK; // CLK event
wsn_application(); //ANSI C code of the algorithm
_EventWsnApp= b_previousEvent;
}
void processTask(void)
{
unit8_T b_previousEvent;
b_previousEvent = _EventWsnApp;
_EventWsnApp = event_TASK; // TASK event
wsn_application(); //ANSI C code of the algorithm
_EventWsnApp = b_previousEvent;
}
function clkEvent()
{CLK}
function taskEvent()
{TASK}
Stateflow
ANSI C
Fig. 10. ANSI C code for three Stateow event function
To read accelerometer sensor data from wsn application, just
like in TinyOS, the generated application code calls the same
generic functions (such as getAccXAxisValue, etc.). Unlike
TinyOS, the driver implementation of the accelerometer is
synchronous, so inside the same function the sensor data
are read from the accelerometer and then the sensorReading
function is called to return data to the wsn application. ember-
IncomingMessageHandler is called when the node receives a
packet for a specic cluster. It stores the packet payload into a
local buffer and calls pktEvent, which signals packet arrival to
wsn application (PKT event). The wsn application then calls
getPktData immediately to get the payload.
Example 5: Skeleton of platform base code in Ember ZigBee
#include ....
// Global and ZigBee specific variables
int main(void){
// Initialize the Ember ZigBee stack
// Main application loop
}
static void applicationTick(void) {
.....
if (emberNetworkState() == EMBER_JOINED_NETWORK ){
if((timeDiff> tickRate))
clkEvent();//Up Call: Sending CLK event to the wsn_application
}
}
// When a packet is received this event handler is called
void emberIncomingMessageHandler(...,EmberMessageBuffer message){
// Store packet payload locally
pktEvent(); // Up Call: Send PKT event to wsn_application
}
// Down Call: To get the payload of the packet
void getPktData(char* payload){....}
// Down Call: Construct packet with payload and broadcast it.
void sendPacket(char payload) { ...
emberSendBroadcast(EMBER_BROADCAST_ADDRESS,...;
}
// Down Call: To read the X-axis value of accelerometer
void getAccXAxisValue(void){
xAxisValue=(((halCommonSpiReadWrite(0xhh) << 8)+halCommonSpiReadWrite(0xll));
//Up Call: Returning X-axis value of the ACCELEROMETER to the wsn_application
return sensorReading(accelerometer,xaixs,xAxisValue);
}
.....
C. Platform specic code generation by TLC scripts
The approach that we explained in the sections above is
automated by appropriate TLC scripts. The application code
for TinyOS and Ember ZigBee platforms looks very different,
so the TLC script performs the following tasks to generate
platform specic code:
Copy into the target les the platform specic application
independent base code including a type conversion header
le that will convert all C types to platform specic
types and platform specic implementations of the library
functions.
Generate platform specic application les by taking
different sections (such as includes, denes, functions,
etc) from the C code generated from Stateow.
Generate make or conguration les for each platform.
VI. EXPERIMENTAL RESULTS

StateIIow ImpIementatIon oI SI
SeraI connecton
jAVA G! to conIIgure and receIve data Irom SI
WreIess Ink
Automatc code generaton
ase statIon
Sensor node
Fig. 11. Running automatically generated code directly in sensor node and
interacting from JAVA GUI in PC
We tested the generated code by using a simple network
setup which contains one base station and a sensor node (both
for TinyOS and ember ZigBee system). We also developed
a JAVA based GUI which is capable of interacting with base
stations implemented for both platforms (TinyOS and Ember).
When the base station node receives data from the GUI, it
constructs a packet and sends it to the network. In the same
way, when it receives a packet from the network, it sends it
to the GUI by the connection link (either USB or RS-232). In
the GUI, we developed options to send different conguration
packets and also representing data that are collected from the
sensor node. The whole testing ow is shown in gure 11.
The generated code of the SPINE node behaves exactly in the
same manner as in the HIL simulation.
A. Comparison between manual and automatically generated
code
By using Stateow Coder, we generated ANSI C code for
SPINE. Then by executing TLC scripts we added platform
dependent code both for TinyOS and for Ember separately.
Table 1 denotes the code size comparison for both platforms.
To get an estimate of code size increase due to automation, we
also implemented manually the same functionalities of SPINE
978-1-4244-5841-7/10/$26.00 2010 IEEE 96 SIES 2010
TABLE I
CODE SIZE COMPARISON BETWEEN TINYOS AND EMBER ZIGBEE FOR SPINE
Software System Memory Platform base code with libs Manual Impl. Automatic Increment
no application code (bytes) (bytes) (bytes)
TinyOS
ROM 9366 19850 20814 9.19%
RAM 840 1355 1380 4.8%
Ember ZigBee
ROM 80101 90714 92187 13.97%
RAM 2736 3171 3220 11.26%
both in TinyOS and also in Ember ZigBee. In table 1, the
increment of code size is evaluated by using equation 1. In
the equation, (AG-EA) represents the size of automatically
generated code and (MW-EA) represents the size of manually
written code. Code size increments due to the automation
process vary from 4% to 13% for both platforms.
Increment =
((AG EA) (MW EA)) 100
MW EA
(1)
AG = Automatically Generated
MW = Manually Written
EA = Empty Application
The advantage of using our framework, as opposed to
manual writing of WSN application code, is that after the
framework succeeded generating correct target on both plat-
forms, it took only two weeks for one person to implement the
fully complex application (SPINE) described in section 4. As
a reference, the manual code development of SPINE only for
TinyOS took around 6 man-months
2
. In other words, with our
framework we could truly concentrate on spending the time
modeling and simulating at the functional level, and then code
generation, compilation and execution for two very different
platforms was automated and extremely fast.
VII. CONCLUSIONS
We described an extensible framework for modeling, HIL
simulation and multi-platform code generation for sensor
network algorithms based on MathWorks tools. The reason for
choosing the MathWorks tools over, for example, TOSSIM,
NS, OmNet, is that they are well known and already pro-
vide rich libraries for digital signal processing and control
algorithm behavior simulation. They also provide extensible
mechanisms for efcient code generation and platform-specic
re-targeting. A possible extension of this work would be to
provide more library functions for other sensors and extending
the framework for simulating a more detailed channel model
fully inside Simulink.
ACKNOWLEDGMENT
The authors would like to thank Marco Sgroi, Roberta
Giannantonio and Fabio Bellifemine from Telecom Italia Labs
for their support and assistance for modeling SPINE in the
proposed framework. This work is funded by a fellowship
from ISSNAF (the Italian Scientists and Scholars in North
2
Our platform independent implementation of the virtual machine is a
subset of SPINE covering around 60% of its functionalities.
America Foundation) sponsored by the Italian ministry for the
environment, the land and the sea.
REFERENCES
[1] Abdelzaher, T., Blum, B., Cao, Q., Chen, Y., and et al. Envirotrack:
Towards an environmental computing paradigm for distributed sensor
networks. In ICDCS 04, pp. 582 589.
[2] Mozumdar, M.M.R., Gregoretti, F., Lavagno, L., Vanzago, L. and Olivieri,
L. A framework for modeling, simulation and automatic code generation
of sensor network application. In Proc. of SECON, pages 515522, San
Francisco, California (USA), 2008.
[3] Mozumdar, M.M.R., Lavagno, L. and Vanzago, L. A comparison of
software platforms for wireless sensor networks: MANTIS, TinyOS, and
ZigBee. In ACM Transactions on Embedded Computing Systems, Vol 8,
Num 8, pages 123, 2009.
[4] BAKSHI, A., PRASANNA, V. K., REICH, J., AND LARNER, D. The
abstract task graph: a methodology for architecture-independent program-
ming of networked sensor systems. In EESR 05, pp. 1924.
[5] BALDWIN, P., KOHLI, S., LEE, E. A., LIU, X., AND ZHAO, Y. Modeling
of sensor nets in ptolemy ii. In IPSN 04, pp. 359368.
[6] CHEONG, E., LEE, E. A., AND ZHAO, Y. Viptos: a graphical de-
velopment and simulation environment for tinyos-based wireless sensor
networks. In SenSys 05, pp. 302302.
[7] EMBER. Zigbee Wireless Semiconductor Solutions by Ember.
http://www.ember.com.
[8] FERRARI, A., AND SANGIOVANNI-VINCENTELLI, A. System design:
Traditional concepts and new paradigms. In In International Conference
on Computer Design (1999), pp. 212.
[9] GIROD, L., RAMANATHAN, N., ELSON, J., STATHOPOULOS, T.,
LUKAC, M., AND ESTRIN, D. Emstar: A software environment for
developing and deploying wireless sensor networks. In USENIX 04,
pp. 283296.
[10] GUMMADI, R., GNAWALI, O., AND GOVINDAN, R. Macro-
programming wireless sensor networks using kairos. In DCOSS 05.
[11] IETF. IPv6 over Low power WPAN.
http://www.ietf.org/html.charters/6lowpan-charter.html.
[12] JIA, D., KROGH, B., AND WONG, C. Toshilt:middleware for hardware-
in-the-loop testing of wireless sensor networks. In IPSN05.
[13] LEVIS, P., LEE, N., WELSH, M., AND CULLER, D. Tossim: accurate
and scalable simulation of entire tinyos applications. In SenSys 03,
pp. 126137.
[14] LEVIS, P., MADDEN, S., GAY, D., AND ET AL. TinyOS: An Operating
System for Sensor Networks. Ambient Intelligence edited by W. Weber,
J.Rabaey, and E. Aarts, Springer-Verlag, 2004.
[15] YANG, J., SOFFA, M. L., SELAVO, L., AND WHITEHOUSE, K. Clair-
voyant: a comprehensive source-level debugger for wireless sensor net-
works. In SenSys 07, pp. 189203.
[16] NEWTON, R., MORRISETT, G., AND WELSH, M. The regiment
macroprogramming system. In IPSN 07, pp. 489498.
[17] SANGIOVANNI-VINCENTELLI, AND ET AL. Platform-based design and
software design methodology for embedded systems. IEEE Des. Test,
2333.
[18] SENTILLA. Pervasive Computing Solutions. http://www.sentilla.com.
[19] SPINE. Signal Processing In Node Environment. http://spine.tilab.com/.
[20] STMICROELECTRONICS. MotionBee wireless sensors.
http://www.st.com.
[21] CROSSBOW TECHNOLOGY Inertial Systems. http://www.xbow.com.
[22] ZIGBEE. ZigBee Alliance. http://www.zigbee.org/.
[23] MATHWORKS. MATLAB and Simulink for Technical Computing.
http://www.mathworks.com.
[24] RTW. Real-Time Workshop - Generate C code from Simulink models
and MATLAB code. http://www.mathworks.com/products/rtw/.
978-1-4244-5841-7/10/$26.00 2010 IEEE 97 SIES 2010

Вам также может понравиться