Cc47-Matlab Code
Cc47-Matlab Code
Cc47-Matlab Code
By
AlWaleed Ahmed Bahar
July 2008
Dedication
To my friend Mos’ab Ibn Ouf soul, may his soul rest in peace .
i
Acknowledgment
Firstly and finally, all praise and gratefulness is due to Allah for his
uncountable blessings , he would never be thanked enough
I would like to thank my Supervisor Dr. Hamid A. Ali for his advice and
guidance through the whole project
I would like to give my gratitude to everyone helped or even offered his help
during the work
(specially Mozaffar Omar)
My very sincere thanks to my whole 03 batch mates for the wonderful five
years
ii
Abstract
iii
اﻟﻤﺴﺘﺨﻠﺺ
ﺗﻘﺪم اﻟﻴﺮاﻋﺎت اﻟﻤﻀﻴﺔ ) (firefliesواﺣﺪة ﻣﻦ أروع اﻟﻈﻮاهﺮ اﻟﻄﺒﻴﻌﻴﺔ اﻟﻤﺘﻤﺜﻠﺔ ﻓﻲ ﻋﻤﻠﻴﺔ اﻟﺘﺰاﻣﻦ اﻟﺘﻠﻘﺎﺋﻲ .ﻋﻨﺪ
اﻟﻔﺠﺮ ،ﺗﺘﺠﻤﻊ هﺬﻩ اﻟﺤﺸﺮات ﻋﻠﻰ اﻷﺷﺠﺎر و ﺗﺒﺎﺷﺮ ﻋﻤﻠﻴﺔ اﻟﺘﺰاﻣﻦ ﺗﺪرﻳﺠﻴﺎ دون اﻻﺳﺘﻨﺎد إﻟﻰ وﺣﺪة ﻣﺮآﺰﻳﺔ.
هﺬﻩ اﻟﻈﺎهﺮة ﻇﻠﺖ ﻣﺤﻞ اهﺘﻤﺎم اﻟﻌﻠﻤﺎء ﻟﻔﺘﺮة ﻃﻮﻳﻠﺔ ﻣﻦ أﺟﻞ ﺗﻔﺴﻴﺮ ﺣﺪوﺛﻬﺎ و ﺗﺤﻠﻴﻠﻬﺎ رﻳﺎﺿﻴﺎ.
ﻗﺪﻣﺖ ﻣﺆﺧﺮا ﺧﻮارزﻣﻴﺔ ﻣﺴﺘﻠﻬﻤﺔ ﻣﻦ هﺬﻩ اﻟﻈﺎهﺮة ﺗﻌﺮف ﺑـ Reachback Firefly Algorithmﺗﻘﻮم ﻋﻠﻰ
اﻟﻨﻤﻮذج اﻟﺮﻳﺎﺿﻲ اﻟﻤﻔﺴﺮ ﻟﺘﻠﻚ اﻟﻈﺎهﺮة .اﺳﺘﺨﺪﻣﺖ هﺬﻩ اﻟﺨﻮارزﻣﻴﺔ آﻄﺮﻳﻘﺔ ﺟﺪﻳﺪة ﻟﺘﺤﻘﻴﻖ ﻣﻔﻬﻮم اﻟﺘﺰاﻣﻨﻴﺔ ﻓﻲ
ﺷﺒﻜﺎت اﻟﻤﺠﺴﺎت اﻟﻼ ﺳﻠﻜﻴﺔ و ﻣﻦ ﺛﻢ ﺗﻤﺖ ﻣﻘﺎرﻧﺘﻬﺎ ﻣﻊ ﺧﻮارزﻣﻴﺎت و ﺑﺮوﺗﻮآﻮﻻت اﻟﺘﺰاﻣﻦ اﻟﻤﺴﺘﺨﺪﻣﺔ.
ﻟﺪراﺳﺔ إﻣﻜﺎﻧﻴﺔ ﺗﻄﺒﻴﻖ اﻟﺨﻮارزﻣﻴﺔ اﻟﻤﻘﺘﺮﺣﺔ ،ﺗﻤﺖ ﻣﺤﺎآﺎﺗﻬﺎ ﺑﺎﺳﺨﺪام ﺑﺮﻧﺎﻣﺞ ﻣﺤﺎآﻲ ﻟﺒﻴﺌﺔ ﺷﺒﻜﺎت اﻟﻤﺠﺴﺎت
اﻟﻼﺳﻠﻜﻴﺔ ﻣﺒﺮﻣﺞ ﺑﺎﺳﺘﺨﺪام ال MATLABﻳﺘﻴﺢ ﺧﻴﺎرات ﻣﺘﻌﺪدة ﻟﻠﺒﺎراﻣﻴﺘﺮات و اﻟﺒﻨﻴﺎت.
Table of Contents
Chapter 1: Introduction 1
1.1 Motivation and Objectives 2
1.2 Thesis Layout 2
Chapter 2: Ad-hoc Wireless Network 3
2.1 Ad hoc computer network 3
2.2 Wireless Ad-hoc networks 3
2.2.1 Applications 4
2.3 Wireless sensor network 4
2.3.1 Applications 5
2.3.2 Characteristics 5
2.4 Energy Awareness 6
Chapter 3: Synchronization in WSN 7
3.1 Synchronization in Networks 7
3.1.1 Synchronization Definition 7
3.1.2 Synchronization in Telecommunications 7
3.1.3 Synchronization in Networks 7
3.1.4 Synchronicity and Synchronization 8
3.2 Synchronization in WSN 8
3.2.1 Approaches to Time Synchronization 8
3.2.1 Approaches to Time Synchronization 9
3.2.3 Comparing the Algorithms 10
3.3 Medium Access Control (MAC) Layer 10
Chapter 4: Fireflies Synchronization 11
4.1 Phenomena of self-organization 11
4.2 Mathematical Model (MaS Model) 12
4.3 Pulse-Coupled Oscillators 14
Chapter 5: The Reachback Firefly Algorithm (RFA) 15
5.1 From Theory to Practice 15
5.2 Reachback Firefly Algorithm 16
5.3 The Algorithm Explanation 17
5.3.1 Preemptive Message Staggering 19
5.3.2 Simplified Firing Function 19
Chapter 6: Simulation 20
6.1 Prowler: Probabilistic Wireless Network Simulator 20
6.2 Network topology and parameters 21
6.2.1 Network topology 21
6.2.2 Simulation Parameters 22
6.3 Firefly Algorithm Implementation 24
6.3.2 Parameters Setting 24
6.3.3 Simulation Results 25
6.4 Performance Optimization 26
6.4.1 Broadcasting Performance 27
6.4.2 Connection Links Formation 28
6.5 Analysis and Comments 29
6.5.1 Results Analysis 30
6.5.2 Simulator limitations 31
6.5.3 MATLAB Limitations 31
Chapter 7: Conclusion 32
7.1 Conclusion 32
7.2 Future Work 32
References 33
APPENDIX A : MATLAB CODE 34
List of Figures
List of Tables
1 Introduction
Since technology improvements in the last decade have made smaller and more
inexpensive sensor nodes possible, sensor networks have become a big research field. In
the beginning such a network was composed of small numbers of sensor nodes whereas
these nodes were wired to a central processing unit. Nowadays sensor networks are
mostly built-on wireless technology with a big number of sensing nodes with local
processing. Hence, that progress enabled the use of sensor networks in a variety of
applications. For example, the monitoring of a phenomenon could be a difficult challenge
if the exact location where to place a sensing element is not known. Alternatively,
distributed sensing allows a closer placement to the phenomenon and therefore a better
Signal-to-noise Ratio (SNR).
However, in most cases the environment where such sensing nodes are in use is harsh and
usually does not provide an infrastructure. Such a malicious environment challenges
some design constraints like robustness, low power consumption, physical size, network
discovery, lifetime and many others that vary from sensor to sensor. Thus, the sensors
must rely on local, finite, and relatively small energy sources.
In order to be economically feasible, the devices generally must have a lifetime on the
order of months to years. The major sources of energy waste are packet collisions,
overhearing, control packet overhead, and idle listening whereas in many MAC-protocols
such as IEEE 802.11 more than 50% are spent on idle listening. Several approaches have
been proposed to improve energy efficiency focusing mostly on clustering mechanisms,
routing algorithms, energy dissipation schemes, sleeping schedules, and so on.
Still a maximized network lifetime requires the use of a well-structured design
methodology and must consider the tradeoffs between energy consumption, system
performance, and operational fidelity.
-1-
Chapter 1 Introduction
-2-
Chapter 2 Ad-hoc Wireless Network
-3-
Chapter 2 Ad-hoc Wireless Network
2.2.1 Applications
The decentralized nature of wireless ad hoc networks makes them suitable for a
variety of applications where central nodes can't be relied on, and may improve the
scalability of wireless ad hoc networks compared to wireless managed networks,
though theoretical and practical limits to the overall capacity of such networks have
been identified. Minimal configuration and quick deployment make ad hoc networks
suitable for emergency situations like natural disasters or military conflicts. The
presence of a dynamic and adaptive routing protocol will enable ad hoc networks to
be formed quickly.
Wireless ad hoc networks can be further classified by their application:
• mobile ad hoc networks
• wireless mesh networks
• wireless sensor networks
The last type is concerned in this project.
-4-
Chapter 2 Ad-hoc Wireless Network
2.3.1 Applications
The applications for WSNs are many and varied, but typically involve some kind of
monitoring, tracking, and controlling. Specific applications for WSNs include habitat
monitoring, object tracking, nuclear reactor control, fire detection, and traffic
monitoring. In a typical application, a WSN is scattered in a region where it is meant
to collect data through its sensor nodes.
2.3.2 Characteristics
Sensor nodes can be imagined as small computers, extremely basic in terms of their
interfaces and their components. They usually consist of a processing unit with
limited computational power and limited memory, sensors (including specific
conditioning circuitry), a communication device (usually radio transceivers or
alternatively optical), and a power source usually in the form of a battery.
-5-
Chapter 2 Ad-hoc Wireless Network
Energy is the scarcest resource of WSN nodes, and it determines the lifetime of the
networks. WSNs are meant to be deployed in large numbers in various environments,
including remote and hostile regions, with ad-hoc communications as key. Sometimes
often more than 50 percent of energy is used for idle listening. Data transmission is
also a large energy consuming operation. For this reason, algorithmic research in
WSN mostly focuses on the study and design of energy aware algorithms for idle
listening and data transmission from the sensor nodes to the base stations. Data
transmission is usually multi-hop (from node to node, towards the base stations), due
to the polynomial growth in the energy-cost of radio transmission with respect to the
transmission distance. In order to reduce power consumption caused by idle listening,
it is necessary to turn off the transceiver module as much as possible. To achieve that
purpose, this project produces a mechanism based on biologically inspired
synchronization approach.
-6-
Chapter 3 Synchronization in WSN
3 Synchronization in WSN
-7-
Chapter 3 Synchronization in WSN
-8-
Chapter 3 Synchronization in WSN
for the wireless sensor network domain are the Reference Broadcast Synchronization
(RBS) algorithm and the Timing-sync Protocol for Sensor Networks (TPSN) .
In the RBS, a reference message is broadcasted. The receivers record their local time
when receiving the reference broadcast and exchange the recorded times with each
other. The main advantage of RBS is that it eliminates transmitter-side non-
determinism. The disadvantage of the approach is that additional message exchange
is necessary to communicate the local time-stamps between the nodes. To our best
knowledge the algorithm has not been extended to large multi-hop networks. The
TPSN algorithm first creates a spanning tree of the network and then performs
pairwise synchronization along the edges. Each node gets synchronized by
exchanging two synchronization messages with its reference node one level higher in
the hierarchy. The TPSN achieves two times better performance than RBS by time-
stamping the radio messages in the MAC layer of the radio stack and by relying on a
two-way message exchange. The shortcoming of TPSN is that it does not estimate the
clock drift of nodes, which limits its accuracy, and does not handle dynamic topology
changes.
To overcome the inadequacies of the previous protocols, a very well designed
protocol know as Flooding Time Synchronization Protocol is produced and so soon
became highly employed to achieve synchronization.
-9-
Chapter 3 Synchronization in WSN
network - a single, dynamically (re)elected node - maintains the global time and all
other nodes synchronize their clocks to that of the root. The nodes form an ad-hoc
structure to transfer the global time from the root to all the nodes. This is robust
against node and link failures and dynamic topology changes.
- 10 -
Chapter 4 FireFlies Synchronization
4 Fireflies Synchronization
In certain parts of South-East Asia alongside riverbanks, male fireflies gather on trees
at dawn, and start emitting flashes regularly. Over time synchronization emerges from
a random situation, which makes it seem as though the whole tree is flashing in
perfect synchrony. This phenomenon forms an amazing spectacle, and has intrigued
scientists for several hundred years. Over the years, two fundamental questions have
been studied: Why do fireflies synchronize? And how do they synchronize? The first
question led to many discussions among biologists.
In all species of fireflies, emissions of light serves as a means of communication that
helps female fireflies distinguish males of its own species: the response of male
fireflies to emissions from females is different in each species. However it is not
clear why in certain species of fireflies, males synchronize Several hypothesis exist:
Either it could accentuate the males rhythm or serve as a noise-reduction mechanism
that helps them identify females. This phenomenon could also enable small groups of
males to attract more females, and act as a cooperative scheme.
- 11 -
Chapter 4 FireFlies Synchronization
to the blinking of his eyelids. Others argued that synchrony was provoked by a single
stimulus received by all fireflies on the tree. However the presence of a leading firefly
or a single external factor is easily dismissed by the fact that not all fireflies can see
each other and fireflies gather on trees and progressively synchronize. The lack of a
proper explanation until the 1960s is mostly due to a lack of experimental data.
Among early hypotheses, Richmond stated in 1930 what came very close to the actual
process: “Suppose that in each insect there is equipment that functions thus: when the
normal time to flash is nearly attained, incident light on the insect hastens the
occurrence of the event. In other words, if one of the insects is almost ready to flash
and sees other insects flash, then it flashes sooner than otherwise. On the foregoing
hypothesis, it follows that there may be a tendency for the insects to fall in step and
flash synchronously.” This statement identifies that synchronization among fireflies is
a self-organized process, and fireflies influence each other: they emit flashes
periodically, and in return are receptive to the flashes of other males.
The internal clock of a firefly, which dictates when a flash is emitted, is modeled as
an oscillator, and the phase of this oscillator is modified upon reception of an external
flash. In general this type of oscillator is termed relaxation oscillators, which are not
represented by a typical sinusoidal form but rather by a series of pulses.
Different models inspired by such a biological synchronization were proposed in the
last decades. The most important one are the phase-advance respectively the phase-
delay model from Buck, the Pulse-coupled Biological Oscillators (PCO) model from
Mirollo and Strogatz (also called MaS model), and the RFA model. Other models are
similar, but make different assumptions on the coupling strength and the propagation
delay in wireless communication.
In the Mirollo and Strogatz (MaS) model, a node acts as an oscillator with a fixed
time period T. Each node has an internal time or phase t, which starts at zero and
increments at a constant rate until t = T. At this point the node “fires” (in the case of
firefly, flashes) and resets t = 0. Nodes may start at different times, therefore their
internal time (phase) t is not synchronized.
- 12 -
Chapter 4 FireFlies Synchronization
In the absence of any input from neighbors, a node B simply fires whenever t = T. If
B observes a neighbor firing, then B reacts by adjusting its phase forward, thus
shortening its own time to fire (Figure 4.1(a,b)). The amount of adjustment is
determined by the function f(t), which is called the firing function, and the parameter,
which is a small constant < 1. Suppose node B observes a neighbor fire at t = t'. In
response, node B instantaneously jumps to a new internal time t = t'' , where
t'' = f −1 ( f (t') + ε) (4.1)
However if t'' > T, then t = T and the node immediately fires and resets t = 0. In a
biological sense, f (t) can be thought of as the charge of a capacitor within the neuron
or firefly, which receives a boost of ε whenever a firing event is observed.
Algorithmically, the effect is that a node instantaneously increments its phase by
Δ (t') = (t'' − t') , when it observes a firing event at t = t'.
The seminal result by Mirollo and Strogatz is that if the function f is smooth,
monotonically increasing, and concave down, then a set of n nodes will always
converge to the same phase (i.e. achieve synchronicity), for any n and any initial
starting times . The simple requirements on f ensure that a node reacts more strongly
to events that occur later in its time period. One of the limitations of their proof was
that it only held for the case where all n nodes could observe each others firing
(all-to-all topology).
- 13 -
Chapter 4 FireFlies Synchronization
β = exp(b· ε)−1
exp(b)−1
where b is the dissipation factor. Both factors α and β determine the coupling between
oscillators and are identical for all. The threshold Φth is normalized to 1.
Interestingly the synchronization scheme relies on the instant of arrival of a pulse, and
receivers adjusting their phases when detecting this pulse. Interference in the typical
way is not observed, and two pulses emitted simultaneously can superimpose
constructively. This helps a faraway receiver to detect the superimposed pulses, and to
synchronize with the rest of the network.
- 14 -
Chapter 5 The Reachback Firefly Algorithm
- 15 -
Chapter 5 The Reachback Firefly Algorithm
varying levels of message loss. At the same time, real biological systems are known to
have such variations. Therefore not all of the theoretical assumptions may be important in
practice.
- 16 -
Chapter 5 The Reachback Firefly Algorithm
of a node reaches the end, it computes the new start phase based on the content of the
queue. The computation is the same as in the MaS model. As a result, a node seems to
react instantaneously, but to the data from the last period. The algorithm for calculating
the starting phase is showed below.
In order to make it easier to understand the algorithm working scheme, an the following
example illustrates how does it work through figure 5.1 .
Example: We first show how the M&S model works, i.e. when messages are received
instantaneously and the node reacts instantaneously. We then illustrate the reachback
- 17 -
Chapter 5 The Reachback Firefly Algorithm
response using the same example. Let the time period T = 100 time units. Let node B
start at internal time t = 0 and increment t every unit time. Suppose firing events arrive at
absolute times 30, 40 and 70.Let Δ(t) be some jump function; here we simply pick jump
values for illustration purposes. In the M&S model, the node reacts as each event arrives,
by causing an instantaneous jump in its internal time. Δ(t) represents the instantaneous
jump at internal time t. When node B observes a firing at time t = 30, it computes an
instantaneous jump of Δ(30) = 5, and sets t = 30 + Δ(30) =35. Ten more time units from
this point on it observes another event. While this event occurred 40 units of time since
the beginning of the cycle, the node perceives it as having happened at internal time t
=45. The node again computes an instantaneous jump in internal time t = 45+ Δ(45) = 55.
After 30 more time units the node B observes another firing event. At this point t = 85
and the node computes an instantaneous jump to t = 85 + Δ(85) = 95. After 5 more time
units, t = 100 and node B fires. It is also possible for the computed t to be larger than 100
(e.g. if Δ(85) = 20 then t = 85 + 20 = 105), in which case the node sets t = 100,
immediately fires, and resets t = 0. The overall effect is that node B advances its phase
(or shortens its time to fire) by 25 time units. It then continues to fire with the default
time period of T = 100. Now we use the same example to illustrate the reachback
response. As before, let node B start with t = 0 and increment t every time unit. When
node B receives a message, it uses the time-stamping information to determine when that
message would have been received had there been no delay. It then places this
information in a queue and continues. When t = 100, node B fires, resets t = 0, and then
looks at the queue. In this example, the queue contains three events at times 30, 40 and
70. Using the same method described for M&S, the node computes how much it would
have advanced its phase. Since all of the information already exists, it can compute the
result in one shot. As in the previous case, the result is that the phase is advanced by 25
time units. Node B applies this effect by instantaneously jumping from t = 0 to t = 25. It
then proceeds as before, firing by default at t = 100 if no events are received. The
difference between the reachback scheme and the original M&S method is that the first
firing event occurs at different absolute times (100 vs 75). This influences neighboring
nodes’ behavior and one must prove that the new scheme will still converge.
- 18 -
Chapter 5 The Reachback Firefly Algorithm
- 19 -
Chapter 6 Simulation
6 Simulation
In order to simulate our algorithm, a MATLAB based wireless sensor network
simulator called PROWLER is used.
‐ 20 ‐
Chapter 6 Simulation
Algorith
Nodes
Radio Channel
mode
Display Features
Events Monitor
Simulation
Control
The network topology chosen for this experiment is a mesh topology, also known as
peer-to-peer topology, improves reliability and scalability by multipath routing and
therefore can be ad-hoc, self-organizing, and self-healing. Moreover, messages can
also be routed through multiple hops which make this topology appropriate for
wireless sensor networks. Other applications that benefit from this may be industrial
control and monitoring, or asset and inventory tracking.
‐ 21 ‐
Chapter 6 Simulation
This topology is represented by a grid of nodes in two dimensions (Fig 6.2). One of
the motes initiates the transmission, and all the receiving motes retransmit the first
received message with a probability of p (probabilistic flood). The transmission signal
strength s can be set within a range. (The values p and s are the same on each mote.)
The goal is to compare the performance of the FTSP protocol to our firefly
synchronization method.
Probability of retransmitting P: takes value between 0.1 and 1 and determine the
probability of retransmitting the packet by any receiving node.
Signal Strength S: The ideal received signal strength is P_rec_id=P_transmit*f(x)
f(x) is the ideal propagation function. The ideal propagation function
defines the signal strength vs. the distance between the transmitter and
‐ 22 ‐
Chapter 6 Simulation
‐ 23 ‐
Chapter 6 Simulation
Parameter Value
P 0.5
S 1
starting node 1
x_number 10
y_number 10
distance 1
s_alph 0.45
s_beta 0.02
p_error 0.05
min_waiting_time 200
rand_waiting_time 128
min_backoff_time 100
var_backoff_time 30
packet_length 960
‐ 24 ‐
Chapter 6 Simulation
‐ 25 ‐
Chapter 6 Simulation
‐ 26 ‐
Chapter 6 Simulation
This experiment is a broadcast in a network of 100 nodes (10 x10 grid). One of the
nodes initiates the transmission, and all the receiving nodes retransmit the first
received message with a probability of p. The transmission signal strength s can be set
within a range. (The values p and s are the same on each mote.).
The goal is to maximize the overall performance of the network by finding the
optimal p and s parameters. The performance metric is composed from the number of
receiving nodes in the network (the more nodes receive the better) and the consumed
power (the less power is used the better):
where the first term is the error when not all the motes receive the message, while
the second is the estimation of the total consumed power, and :
The exhaustive search method was used to find the minimum of the error surface.
The surface was evaluated in 10x12 points in the regions of P = [0.1, 1], S = [0.1, 3];
in each point 10 experiments were run. The generated error surface is shown in figure
(6.5). The best performance was found when P = 0.3 and S = 1.0.
Some of the other points at the bottom of the canyon-shaped surface would give
almost equally good results, while outside that region the performance drastically
decreases.
‐ 27 ‐
Chapter 6 Simulation
E1= T + M λ (6.2)
The cost function E1 was calculated with 50 motes placed in a 5 x 10 grid. Twelve
experiments were made for different values of P in the range, P = [0.01, 0.9]. The
results are shown in Figure (6.6). Where the upper curve shows the mean run time (T),
the second plot is the mean total message number (M) and the third one is for the error
surface (E1).
‐ 28 ‐
Chapter 6 Simulation
The results showed that the optimum value was P = 0.1. With this setting the
algorithm connects the nodes in approximately four seconds by sending 350 messages
on average.
‐ 29 ‐
Chapter 6 Simulation
Before analyzing the results, one more calculation should be done to proceed with the
whole view. This was done using equation (6.1) with to calculate both terms of the
formula (arbitrary variables λ1=1/100, λ2=1/10) . Table 6.3 contains the final outcome.
• From the table above, it's easy to figure out that the firefly protocol is less than
FTSP protocol in accuracy and better in power consumption. These
conclusions are matching the inferences of other related works (mentioned in
references).
• Compared to algorithms such as RBS, TPSN and FTSP, the firefly-inspired
algorithm represents a radically different approach. All of the nodes behave in
a simple and identical manner. There are no special nodes, such as the root in
TPSN or reference node in RBS that needs to be elected. A node does not
maintain any per-neighbor or per- link state; in fact it is completely agnostic to
the identity of its neighbors. The algorithm remains the same even if the
topology is multi-hop.
• Although the gotten results are not very accurate, it still give a strong base for
comparison objective and provided the necessary graphs which used to
determine optimum values of some parameters. Those values could be used in
case of identical circumstances.
‐ 30 ‐
Chapter 6 Simulation
‐ 31 ‐
Chapter 7 Conclusion
7 Conclusion
7.1 Conclusion
It's so expected that the firefly algorithm will be integrated with FTSP or TPSN to
produce efficient, scalable and a comprehensive solution to the problem of time
synchronization in sensor networks.
- 32 -
References____________________________________________________________
References
• Miklós Maróti, Branislav Kusy, Gyula Simon, Ákos Lédeczi, "The Flooding
Time Synchronization Protocol".
• http://www.isis.vanderbilt.edu/Projects/nest/prowler/
• http://www.wikipedia.org
- 33 -
Appendix A Matlab Code
APPENDIX A
MATLAB CODE
function application(S)
S;
S; persistent app_data
S; global ID t
S; [t, event, ID, data]=get_event(S);
S; [topology, mote_IDs]=prowler('GetTopologyInfo');
S; ix=find(mote_IDs==ID);
S; if ~strcmp(event, 'Init_Application')
S; try memory=app_data{ix}; catch memory=[]; end,
S; end
S;
SENDER_ID=sim_params('get_app', 'Start_Mote');
if isempty(SENDER_ID), SENDER_ID=1; end
switch event
case 'Init_Application'
signal_strength=1;
if ID==SENDER_ID
Set_Clock(1000)
end
PrintMessage('')
case 'Packet_Sent'
- 35 -
Appendix A Matlab Code
case 'Packet_Received'
p=sim_params('get_app', 'P');
if isempty(p); p=.3; end
if memory.parent<0
memory.parent=data.data.ID;
memory.hops=data.data.hops+1;
if rand<p
Send_Packet(radiostream(struct('time', t, 'ID', ID, 'hops', memory.hops),
memory.signal_strength));
end
PrintMessage([num2str(memory.parent) '/' num2str(memory.hops)])
DrawLine('Arrow', memory.parent,ID, 'color', [0 0 0])
if memory.hops<3
LED('red on')
elseif memory.hops<6
LED('green on')
else
LED('yellow on')
end
end
case 'Collided_Packet_Received'
% this is for debug purposes only
case 'Clock_Tick'
if ID==SENDER_ID
memory.parent=0;
memory.hops=0;
Send_Packet(radiostream(struct('time', t, 'ID', ID, 'hops', 0),
memory.signal_strength));
end
case 'GuiInfoRequest'
- 36 -
Appendix A Matlab Code
if ~isempty(memory)
disp(sprintf('Memory Dump of mote ID# %d:\n',ID)); disp(memory)
else
disp(sprintf('No memory dump available for node %d.\n',ID));
end
case 'Application_Stopped'
% this event is called when simulation is stopped/suspended
case 'Application_Finished'
% this event is called when simulation is finished
otherwise
error(['Bad event name for application: ' event])
end
S;
S; app_data{ix}=memory;
S;
function b=Send_Packet(data);
global ID t
radio=prowler('GetRadioName');
b=feval(radio, 'Send_Packet', ID, data, t);
function b=Set_Clock(alarm_time);
global ID
prowler('InsertEvents2Q', make_event(alarm_time, 'Clock_Tick', ID));
function PrintMessage(msg)
global ID
- 37 -
Appendix A Matlab Code
function LED(msg)
global ID
prowler('LED', ID, msg)
function param=params;
param(1).name='P'; param(1).default=0.5;
param(2).name='Start_Mote'; param(2).default=1;
param(3).name='X_Number'; param(3).default=10;
param(4).name='Y_Number'; param(4).default=10;
param(5).name='Distance'; param(5).default=1;
function [topology,mote_IDs]=topology(varargin);
ix=1;t=[];
Nx =sim_params('get_app', 'X_Number'); if isempty(Nx), Nx=10; end
Ny =sim_params('get_app', 'Y_Number'); if isempty(Ny), Ny=10; end
dist=sim_params('get_app', 'Distance'); if isempty(dist), dist=1; end
- 38 -
Appendix A Matlab Code
X=1:dist:(Nx-1)*dist+1;
Y=1:dist:(Ny-1)*dist+1;
for i=X
for j=Y
t=[t; i,j];
end
end
topology=t;
mote_IDs=1:Nx*Ny;
function x=animation
persistent anim_data
if isempty(anim_data)
small=5; medium=20; large=50;
for i=1:length(anim_def)
a=anim_def{i};
if i==1
anim_data=struct('event', a{1}, 'animated', a{2}, 'color', a{3}, 'size', a{4});
- 39 -
Appendix A Matlab Code
else
anim_data(i)=struct('event', a{1}, 'animated', a{2}, 'color', a{3}, 'size', a{4});
end
end
end
x=anim_data;
function varargout=simstats
global global_event_Q
for i=1:N
node_stat(i)=struct(...
'Sent_Messages', 0, ...
'Received_Messages', 0, ...
'Received_Collided_Messages', 0, ...
'Send_Times', [], ...
'Receive_Times', [], ...
'Collide_Times', []);
end
L=length(global_event_Q);
for i=1:L
t=global_event_Q(i).time;
e=global_event_Q(i).event;
id=global_event_Q(i).ID;
ix=find(mote_IDs==id);
switch e
case 'Packet_Transmit_Start'
- 40 -
Appendix A Matlab Code
node_stat(ix).Sent_Messages=node_stat(ix).Sent_Messages+1;
node_stat(ix).Send_Times=[node_stat(ix).Send_Times, t];
case 'Packet_Received'
node_stat(ix).Received_Messages=node_stat(ix).Received_Messages+1;
node_stat(ix).Receive_Times=[node_stat(ix).Receive_Times, t];
case 'Collided_Packet_Received'
node_stat(ix).Received_Collided_Messages=node_stat(ix).Received_Collided_Messa
ges+1;
node_stat(ix).Collide_Times=[node_stat(ix).Collide_Times, t];
otherwise
% not handled; can be extended
end
end
sys_stat=struct(...
'Sent_Messages', 0, ...
'Received_Messages', 0, ...
'Received_Collided_Messages', 0, ...
'First_Send_Time', inf, ...
'First_Receive_Time', inf, ...
'Last_Sent_Time', -inf, ...
'Last_Receive_Time', -inf, ...
'Sending_Nodes', 0, ...
'Receiving_Nodes', 0);
for i=1:N
sys_stat.Sent_Messages = ...
sys_stat.Sent_Messages + node_stat(i).Sent_Messages;
sys_stat.Received_Messages = ...
sys_stat.Received_Messages + node_stat(i).Received_Messages;
sys_stat.Received_Collided_Messages = ...
- 41 -
Appendix A Matlab Code
sys_stat.Received_Collided_Messages +
node_stat(i).Received_Collided_Messages;
sys_stat.First_Send_Time = ...
min([sys_stat.First_Send_Time, node_stat(i).Send_Times]);
sys_stat.First_Receive_Time = ...
min([sys_stat.First_Receive_Time, node_stat(i).Receive_Times]);
sys_stat.Last_Sent_Time = ...
max([sys_stat.Last_Sent_Time, node_stat(i).Send_Times]);
sys_stat.Last_Receive_Time = ...
max([sys_stat.Last_Receive_Time, node_stat(i).Receive_Times]);
sys_stat.Sending_Nodes = ...
sys_stat.Sending_Nodes + (node_stat(i).Sent_Messages > 0);
sys_stat.Receiving_Nodes = ...
sys_stat.Receiving_Nodes + (node_stat(i).Received_Messages > 0);
end
if nargout==0
disp(sys_stat)
else
varargout={sys_stat, node_stat};
end
- 42 -