A Discrete-Event Network Simulator
API
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Groups Pages
onoff-application.cc
Go to the documentation of this file.
1 /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
2 //
3 // Copyright (c) 2006 Georgia Tech Research Corporation
4 //
5 // This program is free software; you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License version 2 as
7 // published by the Free Software Foundation;
8 //
9 // This program is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
13 //
14 // You should have received a copy of the GNU General Public License
15 // along with this program; if not, write to the Free Software
16 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 //
18 // Author: George F. Riley<riley@ece.gatech.edu>
19 //
20 
21 // ns3 - On/Off Data Source Application class
22 // George F. Riley, Georgia Tech, Spring 2007
23 // Adapted from ApplicationOnOff in GTNetS.
24 
25 #include "ns3/log.h"
26 #include "ns3/address.h"
27 #include "ns3/inet-socket-address.h"
28 #include "ns3/inet6-socket-address.h"
29 #include "ns3/packet-socket-address.h"
30 #include "ns3/node.h"
31 #include "ns3/nstime.h"
32 #include "ns3/data-rate.h"
33 #include "ns3/random-variable-stream.h"
34 #include "ns3/socket.h"
35 #include "ns3/simulator.h"
36 #include "ns3/socket-factory.h"
37 #include "ns3/packet.h"
38 #include "ns3/uinteger.h"
39 #include "ns3/trace-source-accessor.h"
40 #include "onoff-application.h"
41 #include "ns3/udp-socket-factory.h"
42 #include "ns3/string.h"
43 #include "ns3/pointer.h"
44 
45 NS_LOG_COMPONENT_DEFINE ("OnOffApplication");
46 
47 namespace ns3 {
48 
49 NS_OBJECT_ENSURE_REGISTERED (OnOffApplication);
50 
51 TypeId
53 {
54  static TypeId tid = TypeId ("ns3::OnOffApplication")
56  .AddConstructor<OnOffApplication> ()
57  .AddAttribute ("DataRate", "The data rate in on state.",
58  DataRateValue (DataRate ("500kb/s")),
59  MakeDataRateAccessor (&OnOffApplication::m_cbrRate),
60  MakeDataRateChecker ())
61  .AddAttribute ("PacketSize", "The size of packets sent in on state",
62  UintegerValue (512),
63  MakeUintegerAccessor (&OnOffApplication::m_pktSize),
64  MakeUintegerChecker<uint32_t> (1))
65  .AddAttribute ("Remote", "The address of the destination",
66  AddressValue (),
67  MakeAddressAccessor (&OnOffApplication::m_peer),
68  MakeAddressChecker ())
69  .AddAttribute ("OnTime", "A RandomVariableStream used to pick the duration of the 'On' state.",
70  StringValue ("ns3::ConstantRandomVariable[Constant=1.0]"),
71  MakePointerAccessor (&OnOffApplication::m_onTime),
72  MakePointerChecker <RandomVariableStream>())
73  .AddAttribute ("OffTime", "A RandomVariableStream used to pick the duration of the 'Off' state.",
74  StringValue ("ns3::ConstantRandomVariable[Constant=1.0]"),
75  MakePointerAccessor (&OnOffApplication::m_offTime),
76  MakePointerChecker <RandomVariableStream>())
77  .AddAttribute ("MaxBytes",
78  "The total number of bytes to send. Once these bytes are sent, "
79  "no packet is sent again, even in on state. The value zero means "
80  "that there is no limit.",
81  UintegerValue (0),
82  MakeUintegerAccessor (&OnOffApplication::m_maxBytes),
83  MakeUintegerChecker<uint32_t> ())
84  .AddAttribute ("Protocol", "The type of protocol to use.",
86  MakeTypeIdAccessor (&OnOffApplication::m_tid),
87  MakeTypeIdChecker ())
88  .AddTraceSource ("Tx", "A new packet is created and is sent",
90  ;
91  return tid;
92 }
93 
94 
96  : m_socket (0),
97  m_connected (false),
98  m_residualBits (0),
99  m_lastStartTime (Seconds (0)),
100  m_totBytes (0)
101 {
102  NS_LOG_FUNCTION (this);
103 }
104 
106 {
107  NS_LOG_FUNCTION (this);
108 }
109 
110 void
111 OnOffApplication::SetMaxBytes (uint32_t maxBytes)
112 {
113  NS_LOG_FUNCTION (this << maxBytes);
114  m_maxBytes = maxBytes;
115 }
116 
119 {
120  NS_LOG_FUNCTION (this);
121  return m_socket;
122 }
123 
124 int64_t
126 {
127  NS_LOG_FUNCTION (this << stream);
128  m_onTime->SetStream (stream);
129  m_offTime->SetStream (stream + 1);
130  return 2;
131 }
132 
133 void
135 {
136  NS_LOG_FUNCTION (this);
137 
138  m_socket = 0;
139  // chain up
141 }
142 
143 // Application Methods
144 void OnOffApplication::StartApplication () // Called at time specified by Start
145 {
146  NS_LOG_FUNCTION (this);
147 
148  // Create the socket if not already
149  if (!m_socket)
150  {
153  {
154  m_socket->Bind6 ();
155  }
158  {
159  m_socket->Bind ();
160  }
162  m_socket->SetAllowBroadcast (true);
164 
168  }
170 
171  // Insure no pending event
172  CancelEvents ();
173  // If we are not yet connected, there is nothing to do here
174  // The ConnectionComplete upcall will start timers at that time
175  //if (!m_connected) return;
177 }
178 
179 void OnOffApplication::StopApplication () // Called at time specified by Stop
180 {
181  NS_LOG_FUNCTION (this);
182 
183  CancelEvents ();
184  if(m_socket != 0)
185  {
186  m_socket->Close ();
187  }
188  else
189  {
190  NS_LOG_WARN ("OnOffApplication found null socket to close in StopApplication");
191  }
192 }
193 
195 {
196  NS_LOG_FUNCTION (this);
197 
199  { // Cancel the pending send packet event
200  // Calculate residual bits since last packet sent
201  Time delta (Simulator::Now () - m_lastStartTime);
202  int64x64_t bits = delta.To (Time::S) * m_cbrRate.GetBitRate ();
203  m_residualBits += bits.GetHigh ();
204  }
208 }
209 
210 // Event handlers
212 {
213  NS_LOG_FUNCTION (this);
215  ScheduleNextTx (); // Schedule the send packet event
217 }
218 
220 {
221  NS_LOG_FUNCTION (this);
222  CancelEvents ();
223 
225 }
226 
227 // Private helpers
229 {
230  NS_LOG_FUNCTION (this);
231 
232  if (m_maxBytes == 0 || m_totBytes < m_maxBytes)
233  {
234  uint32_t bits = m_pktSize * 8 - m_residualBits;
235  NS_LOG_LOGIC ("bits = " << bits);
236  Time nextTime (Seconds (bits /
237  static_cast<double>(m_cbrRate.GetBitRate ()))); // Time till next packet
238  NS_LOG_LOGIC ("nextTime = " << nextTime);
239  m_sendEvent = Simulator::Schedule (nextTime,
241  }
242  else
243  { // All done, cancel any pending events
244  StopApplication ();
245  }
246 }
247 
249 { // Schedules the event to start sending data (switch to the "On" state)
250  NS_LOG_FUNCTION (this);
251 
252  Time offInterval = Seconds (m_offTime->GetValue ());
253  NS_LOG_LOGIC ("start at " << offInterval);
255 }
256 
258 { // Schedules the event to stop sending data (switch to "Off" state)
259  NS_LOG_FUNCTION (this);
260 
261  Time onInterval = Seconds (m_onTime->GetValue ());
262  NS_LOG_LOGIC ("stop at " << onInterval);
264 }
265 
266 
268 {
269  NS_LOG_FUNCTION (this);
270 
272  Ptr<Packet> packet = Create<Packet> (m_pktSize);
273  m_txTrace (packet);
274  m_socket->Send (packet);
277  {
278  NS_LOG_INFO ("At time " << Simulator::Now ().GetSeconds ()
279  << "s on-off application sent "
280  << packet->GetSize () << " bytes to "
282  << " port " << InetSocketAddress::ConvertFrom (m_peer).GetPort ()
283  << " total Tx " << m_totBytes << " bytes");
284  }
286  {
287  NS_LOG_INFO ("At time " << Simulator::Now ().GetSeconds ()
288  << "s on-off application sent "
289  << packet->GetSize () << " bytes to "
292  << " total Tx " << m_totBytes << " bytes");
293  }
295  m_residualBits = 0;
296  ScheduleNextTx ();
297 }
298 
299 
301 {
302  NS_LOG_FUNCTION (this << socket);
303  m_connected = true;
304 }
305 
307 {
308  NS_LOG_FUNCTION (this << socket);
309 }
310 
311 
312 } // Namespace ns3
static TypeId GetTypeId(void)
Get the type ID.
void StopSending()
Start an Off period.
Ipv6Address GetIpv6(void) const
Get the IPv6 address.
Simulation virtual time values and global simulation resolution.
Definition: nstime.h:79
Ipv4Address GetIpv4(void) const
#define NS_LOG_FUNCTION(parameters)
If log level LOG_FUNCTION is enabled, this macro will output all input parameters separated by "...
void SetStream(int64_t stream)
Specifies the stream number for this RNG stream.
virtual void StartApplication(void)
Application specific startup code.
EventId m_sendEvent
Event id of pending "send packet" event.
#define NS_OBJECT_ENSURE_REGISTERED(type)
Register the class in the ns-3 factory.
Definition: object-base.h:38
uint32_t m_pktSize
Size of packets.
virtual int Bind6()=0
Allocate a local IPv6 endpoint for this socket.
hold variables of type string
Definition: string.h:18
virtual bool SetAllowBroadcast(bool allowBroadcast)=0
Configure whether broadcast datagram transmissions are allowed.
High precision numerical type, implementing Q64.64 fixed precision.
Definition: int64x64-128.h:20
void ScheduleStartEvent()
Schedule the next On period start.
void CancelEvents()
Cancel all pending events.
#define NS_ASSERT(condition)
At runtime, in debugging builds, if this condition is not true, the program prints the source file...
Definition: assert.h:61
static bool IsMatchingType(const Address &address)
#define NS_LOG_COMPONENT_DEFINE(name)
Define a Log component with a specific name.
Definition: log.h:170
virtual int ShutdownRecv(void)=0
void ScheduleStopEvent()
Schedule the next Off period start.
#define NS_LOG_INFO(msg)
Use NS_LOG to output a message of level LOG_INFO.
Definition: log.h:223
static void Cancel(const EventId &id)
Set the cancel bit on this event: the event's associated function will not be invoked when it expires...
Definition: simulator.cc:268
bool IsRunning(void) const
This method is syntactic sugar for the ns3::Simulator::isExpired method.
Definition: event-id.cc:59
static EventId Schedule(Time const &time, MEM mem_ptr, OBJ obj)
Schedule an event to expire at the relative time "time" is reached.
Definition: simulator.h:825
virtual double GetValue(void)=0
Returns a random double from the underlying distribution.
DataRate m_cbrRateFailSafe
Rate that data is generated (check copy)
Class for representing data rates.
Definition: data-rate.h:71
virtual void DoDispose(void)
This method is called by Object::Dispose or by the object's destructor, whichever comes first...
EventId m_startStopEvent
Event id for next start or stop event.
void SendPacket()
Send a packet.
TypeId m_tid
Type of the socket used.
The base class for all ns3 applications.
Definition: application.h:60
Address m_peer
Peer address.
DataRate m_cbrRate
Rate that data is generated.
Hold an unsigned integer type.
Definition: uinteger.h:46
Ptr< RandomVariableStream > m_onTime
rng for On Time
Ptr< Node > GetNode() const
Definition: application.cc:103
hold objects of type ns3::TypeId
Ptr< Socket > GetSocket(void) const
Return a pointer to associated socket.
Callback< R > MakeCallback(R(T::*memPtr)(void), OBJ objPtr)
Definition: callback.h:1242
Ptr< Socket > m_socket
Associated socket.
static Ptr< Socket > CreateSocket(Ptr< Node > node, TypeId tid)
This method wraps the creation of sockets that is performed on a given node by a SocketFactory specif...
Definition: socket.cc:70
int64_t AssignStreams(int64_t stream)
Assign a fixed random variable stream number to the random variables used by this model...
#define NS_LOG_LOGIC(msg)
Use NS_LOG to output a message of level LOG_LOGIC.
Definition: log.h:233
Ptr< RandomVariableStream > m_offTime
rng for Off Time
virtual int Connect(const Address &address)=0
Initiate a connection to a remote host.
virtual void DoDispose(void)
This method is called by Object::Dispose or by the object's destructor, whichever comes first...
Definition: application.cc:82
TracedCallback< Ptr< const Packet > > m_txTrace
Traced Callback: transmitted packets.
virtual int Bind(const Address &address)=0
Allocate a local endpoint for this socket.
static InetSocketAddress ConvertFrom(const Address &address)
Returns an InetSocketAddress which corresponds to the input Address.
Ptr< const TraceSourceAccessor > MakeTraceSourceAccessor(T a)
void ScheduleNextTx()
Schedule the next packet transmission.
void StartSending()
Start an On period.
uint64_t GetBitRate() const
Get the underlying bitrate.
Definition: data-rate.cc:235
void SetMaxBytes(uint32_t maxBytes)
Set the total number of bytes to send.
static Time Now(void)
Return the "current simulation time".
Definition: simulator.cc:180
void ConnectionSucceeded(Ptr< Socket > socket)
Handle a Connection Succeed event.
Time m_lastStartTime
Time last packet sent.
hold objects of type ns3::Address
static TypeId GetTypeId(void)
Get the type ID.
#define NS_LOG_WARN(msg)
Use NS_LOG to output a message of level LOG_WARN.
Definition: log.h:203
hold objects of type ns3::DataRate
static Inet6SocketAddress ConvertFrom(const Address &addr)
Convert the address to a InetSocketAddress.
static bool IsMatchingType(const Address &addr)
If the address match.
uint16_t GetPort(void) const
Get the port.
int64_t GetHigh(void) const
Get the integer portion.
Definition: int64x64-128.h:191
uint32_t m_maxBytes
Limit total number of bytes sent.
void ConnectionFailed(Ptr< Socket > socket)
Handle a Connection Failed event.
uint32_t m_totBytes
Total bytes sent so far.
uint16_t GetPort(void) const
second
Definition: nstime.h:91
void SetConnectCallback(Callback< void, Ptr< Socket > > connectionSucceeded, Callback< void, Ptr< Socket > > connectionFailed)
Specify callbacks to allow the caller to determine if the connection succeeds of fails.
Definition: socket.cc:83
bool m_connected
True if connected.
virtual void StopApplication(void)
Application specific shutdown code.
virtual int Send(Ptr< Packet > p, uint32_t flags)=0
Send data (or dummy data) to the remote host.
virtual int Close(void)=0
Close a socket.
bool IsExpired(void) const
This method is syntactic sugar for the ns3::Simulator::isExpired method.
Definition: event-id.cc:53
a unique identifier for an interface.
Definition: type-id.h:49
TypeId SetParent(TypeId tid)
Definition: type-id.cc:610
uint32_t m_residualBits
Number of generated, but not sent, bits.
static bool IsMatchingType(const Address &address)
int64x64_t To(enum Unit timeUnit) const
Definition: nstime.h:462