A Discrete-Event Network Simulator
API
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 #include "ns3/boolean.h"
45 
46 namespace ns3 {
47 
48 NS_LOG_COMPONENT_DEFINE ("OnOffApplication");
49 
50 NS_OBJECT_ENSURE_REGISTERED (OnOffApplication);
51 
52 TypeId
54 {
55  static TypeId tid = TypeId ("ns3::OnOffApplication")
57  .SetGroupName("Applications")
58  .AddConstructor<OnOffApplication> ()
59  .AddAttribute ("DataRate", "The data rate in on state.",
60  DataRateValue (DataRate ("500kb/s")),
63  .AddAttribute ("PacketSize", "The size of packets sent in on state",
64  UintegerValue (512),
66  MakeUintegerChecker<uint32_t> (1))
67  .AddAttribute ("Remote", "The address of the destination",
68  AddressValue (),
71  .AddAttribute ("Local",
72  "The Address on which to bind the socket. If not set, it is generated automatically.",
73  AddressValue (),
76  .AddAttribute ("OnTime", "A RandomVariableStream used to pick the duration of the 'On' state.",
77  StringValue ("ns3::ConstantRandomVariable[Constant=1.0]"),
79  MakePointerChecker <RandomVariableStream>())
80  .AddAttribute ("OffTime", "A RandomVariableStream used to pick the duration of the 'Off' state.",
81  StringValue ("ns3::ConstantRandomVariable[Constant=1.0]"),
83  MakePointerChecker <RandomVariableStream>())
84  .AddAttribute ("MaxBytes",
85  "The total number of bytes to send. Once these bytes are sent, "
86  "no packet is sent again, even in on state. The value zero means "
87  "that there is no limit.",
88  UintegerValue (0),
90  MakeUintegerChecker<uint64_t> ())
91  .AddAttribute ("Protocol", "The type of protocol to use. This should be "
92  "a subclass of ns3::SocketFactory",
95  // This should check for SocketFactory as a parent
97  .AddAttribute ("EnableE2EStats",
98  "Enable E2E statistics (sequences, timestamps)",
99  BooleanValue (false),
102  .AddTraceSource ("Tx", "A new packet is created and is sent",
104  "ns3::Packet::TracedCallback")
105  .AddTraceSource ("TxWithAddresses", "A new packet is created and is sent",
107  "ns3::Packet::TwoAddressTracedCallback")
108  .AddTraceSource ("TxE2EStat", "Statistic sent with the packet",
110  "ns3::PacketSink::E2EStatCallback")
111  ;
112  return tid;
113 }
114 
115 
117  : m_socket (0),
118  m_connected (false),
119  m_residualBits (0),
120  m_lastStartTime (Seconds (0)),
121  m_totBytes (0)
122 {
123  NS_LOG_FUNCTION (this);
124 }
125 
127 {
128  NS_LOG_FUNCTION (this);
129 }
130 
131 void
132 OnOffApplication::SetMaxBytes (uint64_t maxBytes)
133 {
134  NS_LOG_FUNCTION (this << maxBytes);
135  m_maxBytes = maxBytes;
136 }
137 
140 {
141  NS_LOG_FUNCTION (this);
142  return m_socket;
143 }
144 
145 int64_t
147 {
148  NS_LOG_FUNCTION (this << stream);
149  m_onTime->SetStream (stream);
150  m_offTime->SetStream (stream + 1);
151  return 2;
152 }
153 
154 void
156 {
157  NS_LOG_FUNCTION (this);
158 
159  CancelEvents ();
160  m_socket = 0;
161  // chain up
163 }
164 
165 // Application Methods
166 void OnOffApplication::StartApplication () // Called at time specified by Start
167 {
168  NS_LOG_FUNCTION (this);
169 
170  // Create the socket if not already
171  if (!m_socket)
172  {
174  int ret = -1;
175 
176  if (! m_local.IsInvalid())
177  {
180  "Incompatible peer and local address IP version");
181  ret = m_socket->Bind (m_local);
182  }
183  else
184  {
186  {
187  ret = m_socket->Bind6 ();
188  }
191  {
192  ret = m_socket->Bind ();
193  }
194  }
195 
196  if (ret == -1)
197  {
198  NS_FATAL_ERROR ("Failed to bind socket");
199  }
200 
202  m_socket->SetAllowBroadcast (true);
204 
208  }
210 
211  // Insure no pending event
212  CancelEvents ();
213  // If we are not yet connected, there is nothing to do here
214  // The ConnectionComplete upcall will start timers at that time
215  //if (!m_connected) return;
217 }
218 
219 void OnOffApplication::StopApplication () // Called at time specified by Stop
220 {
221  NS_LOG_FUNCTION (this);
222 
223  CancelEvents ();
224  if(m_socket != 0)
225  {
226  m_socket->Close ();
227  }
228  else
229  {
230  NS_LOG_WARN ("OnOffApplication found null socket to close in StopApplication");
231  }
232 }
233 
235 {
236  NS_LOG_FUNCTION (this);
237 
239  { // Cancel the pending send packet event
240  // Calculate residual bits since last packet sent
241  Time delta (Simulator::Now () - m_lastStartTime);
242  int64x64_t bits = delta.To (Time::S) * m_cbrRate.GetBitRate ();
243  m_residualBits += bits.GetHigh ();
244  }
248 }
249 
250 // Event handlers
252 {
253  NS_LOG_FUNCTION (this);
255  ScheduleNextTx (); // Schedule the send packet event
257 }
258 
260 {
261  NS_LOG_FUNCTION (this);
262  CancelEvents ();
263 
265 }
266 
267 // Private helpers
269 {
270  NS_LOG_FUNCTION (this);
271 
272  if (m_maxBytes == 0 || m_totBytes < m_maxBytes)
273  {
274  uint32_t bits = m_pktSize * 8 - m_residualBits;
275  NS_LOG_LOGIC ("bits = " << bits);
276  Time nextTime (Seconds (bits /
277  static_cast<double>(m_cbrRate.GetBitRate ()))); // Time till next packet
278  NS_LOG_LOGIC ("nextTime = " << nextTime);
279  m_sendEvent = Simulator::Schedule (nextTime,
281  }
282  else
283  { // All done, cancel any pending events
284  StopApplication ();
285  }
286 }
287 
289 { // Schedules the event to start sending data (switch to the "On" state)
290  NS_LOG_FUNCTION (this);
291 
292  Time offInterval = Seconds (m_offTime->GetValue ());
293  NS_LOG_LOGIC ("start at " << offInterval);
295 }
296 
298 { // Schedules the event to stop sending data (switch to "Off" state)
299  NS_LOG_FUNCTION (this);
300 
301  Time onInterval = Seconds (m_onTime->GetValue ());
302  NS_LOG_LOGIC ("stop at " << onInterval);
304 }
305 
306 
308 {
309  NS_LOG_FUNCTION (this);
310 
312 
313  Ptr<Packet> packet;
314  if (m_enableE2EStats)
315  {
316  Address from, to;
317  m_socket->GetSockName (from);
318  m_socket->GetPeerName (to);
319  E2eStatsHeader header;
320  header.SetSeq (m_seq++);
321  header.SetSize (m_pktSize);
323  packet = Create<Packet> (m_pktSize - header.GetSerializedSize ());
324  packet->AddHeader (header);
325  m_txTraceWithStats (packet, from, to, header);
326  }
327  else
328  {
329  packet = Create<Packet> (m_pktSize);
330  }
331 
332  m_txTrace (packet);
333  m_socket->Send (packet);
335  Address localAddress;
336  m_socket->GetSockName (localAddress);
338  {
339  NS_LOG_INFO ("At time " << Simulator::Now ().GetSeconds ()
340  << "s on-off application sent "
341  << packet->GetSize () << " bytes to "
343  << " port " << InetSocketAddress::ConvertFrom (m_peer).GetPort ()
344  << " total Tx " << m_totBytes << " bytes");
346  }
348  {
349  NS_LOG_INFO ("At time " << Simulator::Now ().GetSeconds ()
350  << "s on-off application sent "
351  << packet->GetSize () << " bytes to "
354  << " total Tx " << m_totBytes << " bytes");
356  }
358  m_residualBits = 0;
359  ScheduleNextTx ();
360 }
361 
362 
364 {
365  NS_LOG_FUNCTION (this << socket);
366  m_connected = true;
367 }
368 
370 {
371  NS_LOG_FUNCTION (this << socket);
372  NS_FATAL_ERROR ("Can't connect");
373 }
374 
375 
376 } // Namespace ns3
static TypeId GetTypeId(void)
Get the type ID.
void StopSending()
Start an Off period.
bool IsInvalid(void) const
Definition: address.cc:68
Simulation virtual time values and global simulation resolution.
Definition: nstime.h:102
void SetSize(uint64_t size)
Set the size information that the header will carry.
#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 the RngStream.
virtual void StartApplication(void)
Application specific startup code.
EventId m_sendEvent
Event id of pending "send packet" event.
AttributeValue implementation for Boolean.
Definition: boolean.h:36
Ptr< Socket > GetSocket(void) const
Return a pointer to associated socket.
#define NS_OBJECT_ENSURE_REGISTERED(type)
Register an Object subclass with the TypeId system.
Definition: object-base.h:45
Ipv6Address GetIpv6(void) const
Get the IPv6 address.
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:41
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:45
Ptr< const AttributeAccessor > MakeBooleanAccessor(T1 a1)
Create an AttributeAccessor for a class data member, or a lone class get functor or set method...
Definition: boolean.h:85
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:67
static bool IsMatchingType(const Address &address)
Address m_local
Local address to bind to.
Generate traffic to a single destination according to an OnOff pattern.
#define NS_LOG_COMPONENT_DEFINE(name)
Define a Log component with a specific name.
Definition: log.h:205
virtual int GetSockName(Address &address) const =0
Get socket address.
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:281
#define NS_FATAL_ERROR(msg)
Report a fatal error with a message and terminate.
Definition: fatal-error.h:162
Header with a sequence, a timestamp, and a "size" attribute.
static void Cancel(const EventId &id)
Set the cancel bit on this event: the event&#39;s associated function will not be invoked when it expires...
Definition: simulator.cc:290
uint64_t GetBitRate() const
Get the underlying bitrate.
Definition: data-rate.cc:249
bool IsExpired(void) const
This method is syntactic sugar for the ns3::Simulator::IsExpired method.
Definition: event-id.cc:59
virtual double GetValue(void)=0
Get the next random value as a double drawn from the distribution.
a polymophic address class
Definition: address.h:90
Ptr< const AttributeChecker > MakeDataRateChecker(void)
Definition: data-rate.cc:30
Ptr< const TraceSourceAccessor > MakeTraceSourceAccessor(T a)
Create a TraceSourceAccessor which will control access to the underlying trace source.
TracedCallback< Ptr< const Packet >, const Address &, const Address & > m_txTraceWithAddresses
Callbacks for tracing the packet Tx events, includes source and destination addresses.
DataRate m_cbrRateFailSafe
Rate that data is generated (check copy)
Class for representing data rates.
Definition: data-rate.h:88
virtual void DoDispose(void)
Destructor implementation.
EventId m_startStopEvent
Event id for next start or stop event.
Ptr< const AttributeAccessor > MakeAddressAccessor(T1 a1)
Create an AttributeAccessor for a class data member, or a lone class get functor or set method...
Definition: address.h:278
void SendPacket()
Send a packet.
Ptr< const AttributeAccessor > MakePointerAccessor(T1 a1)
Create an AttributeAccessor for a class data member, or a lone class get functor or set method...
Definition: pointer.h:227
static EventId Schedule(Time const &delay, MEM mem_ptr, OBJ obj)
Schedule an event to expire after delay.
Definition: simulator.h:1390
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:44
Ptr< RandomVariableStream > m_onTime
rng for On Time
AttributeValue implementation for TypeId.
Definition: type-id.h:611
Callback< R > MakeCallback(R(T::*memPtr)(void), OBJ objPtr)
Definition: callback.h:1610
uint64_t m_totBytes
Total bytes sent so far.
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:71
int64_t AssignStreams(int64_t stream)
Assign a fixed random variable stream number to the random variables used by this model...
Ptr< const AttributeAccessor > MakeDataRateAccessor(T1 a1)
Create an AttributeAccessor for a class data member, or a lone class get functor or set method...
Definition: data-rate.h:242
Ptr< Node > GetNode() const
Definition: application.cc:104
Ptr< RandomVariableStream > m_offTime
rng for Off Time
void SetMaxBytes(uint64_t maxBytes)
Set the total number of bytes to send.
virtual int Connect(const Address &address)=0
Initiate a connection to a remote host.
virtual void DoDispose(void)
Destructor implementation.
Definition: application.cc:83
TracedCallback< Ptr< const Packet > > m_txTrace
Traced Callback: transmitted packets.
virtual int Bind(const Address &address)=0
Allocate a local endpoint for this socket.
Every class exported by the ns3 library is enclosed in the ns3 namespace.
static InetSocketAddress ConvertFrom(const Address &address)
Returns an InetSocketAddress which corresponds to the input Address.
Ptr< const AttributeChecker > MakeBooleanChecker(void)
Definition: boolean.cc:121
void ScheduleNextTx()
Schedule the next packet transmission.
uint16_t GetPort(void) const
void StartSending()
Start an On period.
bool m_enableE2EStats
Enable or disable the e2e statistic generation.
Ptr< const AttributeChecker > MakeAddressChecker(void)
Definition: address.cc:172
static Time Now(void)
Return the current simulation virtual time.
Definition: simulator.cc:193
NS_LOG_LOGIC("Net device "<< nd<< " is not bridged")
void ConnectionSucceeded(Ptr< Socket > socket)
Handle a Connection Succeed event.
Time m_lastStartTime
Time last packet sent.
#define NS_ABORT_IF(cond)
Abnormal program termination if a condition is true.
Definition: abort.h:77
Ptr< const AttributeAccessor > MakeTypeIdAccessor(T1 a1)
Create an AttributeAccessor for a class data member, or a lone class get functor or set method...
Definition: type-id.h:611
AttributeValue implementation for Address.
Definition: address.h:278
virtual uint32_t GetSerializedSize(void) const override
#define NS_ABORT_MSG_IF(cond, msg)
Abnormal program termination if a condition is true, with a message.
Definition: abort.h:108
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:265
AttributeValue implementation for DataRate.
Definition: data-rate.h:242
void SetSeq(uint32_t seq)
uint32_t m_seq
Sequence.
Time Seconds(double value)
Construct a Time in the indicated unit.
Definition: nstime.h:1070
static Inet6SocketAddress ConvertFrom(const Address &addr)
Convert the address to a InetSocketAddress.
TracedCallback< Ptr< const Packet >, const Address &, const Address &, const E2eStatsHeader & > m_txTraceWithStats
Callback for tracing the packet Tx events, includes source, destination, and the packet sent...
bool IsRunning(void) const
This method is syntactic sugar for !IsExpired().
Definition: event-id.cc:65
static bool IsMatchingType(const Address &addr)
If the address match.
void ConnectionFailed(Ptr< Socket > socket)
Handle a Connection Failed event.
int64x64_t To(enum Unit unit) const
Get the Time value expressed in a particular unit.
Definition: nstime.h:515
virtual int GetPeerName(Address &address) const =0
Get the peer address of a connected socket.
second
Definition: nstime.h:114
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:84
bool m_connected
True if connected.
virtual void StopApplication(void)
Application specific shutdown code.
uint16_t GetPort(void) const
Get the port.
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.
Ptr< const AttributeChecker > MakeTypeIdChecker(void)
Definition: type-id.cc:1235
Ptr< const AttributeAccessor > MakeUintegerAccessor(T1 a1)
Create an AttributeAccessor for a class data member, or a lone class get functor or set method...
Definition: uinteger.h:45
a unique identifier for an interface.
Definition: type-id.h:58
TypeId SetParent(TypeId tid)
Set the parent TypeId.
Definition: type-id.cc:923
uint32_t m_residualBits
Number of generated, but not sent, bits.
uint64_t m_maxBytes
Limit total number of bytes sent.
static bool IsMatchingType(const Address &address)
Ipv4Address GetIpv4(void) const
int64_t GetHigh(void) const
Get the integer portion.
Definition: int64x64-128.h:222