A Discrete-Event Network Simulator
API
Loading...
Searching...
No Matches
onoff-application.cc
Go to the documentation of this file.
1//
2// Copyright (c) 2006 Georgia Tech Research Corporation
3//
4// This program is free software; you can redistribute it and/or modify
5// it under the terms of the GNU General Public License version 2 as
6// published by the Free Software Foundation;
7//
8// This program is distributed in the hope that it will be useful,
9// but WITHOUT ANY WARRANTY; without even the implied warranty of
10// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11// GNU General Public License for more details.
12//
13// You should have received a copy of the GNU General Public License
14// along with this program; if not, write to the Free Software
15// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
16//
17// Author: George F. Riley<riley@ece.gatech.edu>
18//
19
20// ns3 - On/Off Data Source Application class
21// George F. Riley, Georgia Tech, Spring 2007
22// Adapted from ApplicationOnOff in GTNetS.
23
24#include "onoff-application.h"
25
26#include "ns3/address.h"
27#include "ns3/boolean.h"
28#include "ns3/data-rate.h"
29#include "ns3/inet-socket-address.h"
30#include "ns3/inet6-socket-address.h"
31#include "ns3/log.h"
32#include "ns3/node.h"
33#include "ns3/nstime.h"
34#include "ns3/packet-socket-address.h"
35#include "ns3/packet.h"
36#include "ns3/pointer.h"
37#include "ns3/random-variable-stream.h"
38#include "ns3/simulator.h"
39#include "ns3/socket-factory.h"
40#include "ns3/socket.h"
41#include "ns3/string.h"
42#include "ns3/trace-source-accessor.h"
43#include "ns3/udp-socket-factory.h"
44#include "ns3/uinteger.h"
45
46namespace ns3
47{
48
49NS_LOG_COMPONENT_DEFINE("OnOffApplication");
50
51NS_OBJECT_ENSURE_REGISTERED(OnOffApplication);
52
53TypeId
55{
56 static TypeId tid =
57 TypeId("ns3::OnOffApplication")
59 .SetGroupName("Applications")
60 .AddConstructor<OnOffApplication>()
61 .AddAttribute("DataRate",
62 "The data rate in on state.",
63 DataRateValue(DataRate("500kb/s")),
66 .AddAttribute("PacketSize",
67 "The size of packets sent in on state",
68 UintegerValue(512),
70 MakeUintegerChecker<uint32_t>(1))
71 .AddAttribute("Remote",
72 "The address of the destination",
76 .AddAttribute("Local",
77 "The Address on which to bind the socket. If not set, it is generated "
78 "automatically.",
82 .AddAttribute("Tos",
83 "The Type of Service used to send IPv4 packets. "
84 "All 8 bits of the TOS byte are set (including ECN bits).",
87 MakeUintegerChecker<uint8_t>())
88 .AddAttribute("OnTime",
89 "A RandomVariableStream used to pick the duration of the 'On' state.",
90 StringValue("ns3::ConstantRandomVariable[Constant=1.0]"),
92 MakePointerChecker<RandomVariableStream>())
93 .AddAttribute("OffTime",
94 "A RandomVariableStream used to pick the duration of the 'Off' state.",
95 StringValue("ns3::ConstantRandomVariable[Constant=1.0]"),
97 MakePointerChecker<RandomVariableStream>())
98 .AddAttribute("MaxBytes",
99 "The total number of bytes to send. Once these bytes are sent, "
100 "no packet is sent again, even in on state. The value zero means "
101 "that there is no limit.",
102 UintegerValue(0),
104 MakeUintegerChecker<uint64_t>())
105 .AddAttribute("Protocol",
106 "The type of protocol to use. This should be "
107 "a subclass of ns3::SocketFactory",
110 // This should check for SocketFactory as a parent
112 .AddAttribute("EnableSeqTsSizeHeader",
113 "Enable use of SeqTsSizeHeader for sequence number and timestamp",
114 BooleanValue(false),
117 .AddTraceSource("Tx",
118 "A new packet is created and is sent",
120 "ns3::Packet::TracedCallback")
121 .AddTraceSource("TxWithAddresses",
122 "A new packet is created and is sent",
124 "ns3::Packet::TwoAddressTracedCallback")
125 .AddTraceSource("TxWithSeqTsSize",
126 "A new packet is created with SeqTsSizeHeader",
128 "ns3::PacketSink::SeqTsSizeCallback");
129 return tid;
130}
131
133 : m_socket(nullptr),
134 m_connected(false),
135 m_residualBits(0),
136 m_lastStartTime(Seconds(0)),
137 m_totBytes(0),
138 m_unsentPacket(nullptr)
139{
140 NS_LOG_FUNCTION(this);
141}
142
144{
145 NS_LOG_FUNCTION(this);
146}
147
148void
150{
151 NS_LOG_FUNCTION(this << maxBytes);
152 m_maxBytes = maxBytes;
153}
154
157{
158 NS_LOG_FUNCTION(this);
159 return m_socket;
160}
161
162int64_t
164{
165 NS_LOG_FUNCTION(this << stream);
166 m_onTime->SetStream(stream);
167 m_offTime->SetStream(stream + 1);
168 return 2;
169}
170
171void
173{
174 NS_LOG_FUNCTION(this);
175
176 CancelEvents();
177 m_socket = nullptr;
178 m_unsentPacket = nullptr;
179 // chain up
181}
182
183// Application Methods
184void
185OnOffApplication::StartApplication() // Called at time specified by Start
186{
187 NS_LOG_FUNCTION(this);
188
189 // Create the socket if not already
190 if (!m_socket)
191 {
193 int ret = -1;
194
195 NS_ABORT_MSG_IF(m_peer.IsInvalid(), "'Remote' attribute not properly set");
196
197 if (!m_local.IsInvalid())
198 {
203 "Incompatible peer and local address IP version");
204 ret = m_socket->Bind(m_local);
205 }
206 else
207 {
209 {
210 ret = m_socket->Bind6();
211 }
214 {
215 ret = m_socket->Bind();
216 }
217 }
218
219 if (ret == -1)
220 {
221 NS_FATAL_ERROR("Failed to bind socket");
222 }
223
226
228 {
229 m_socket->SetIpTos(m_tos); // Affects only IPv4 sockets.
230 }
234 }
236
237 // Ensure no pending event
238 CancelEvents();
239
240 // If we are not yet connected, there is nothing to do here,
241 // the ConnectionComplete upcall will start timers at that time.
242 // If we are already connected, CancelEvents did remove the events,
243 // so we have to start them again.
244 if (m_connected)
245 {
247 }
248}
249
250void
251OnOffApplication::StopApplication() // Called at time specified by Stop
252{
253 NS_LOG_FUNCTION(this);
254
255 CancelEvents();
256 if (m_socket)
257 {
258 m_socket->Close();
259 }
260 else
261 {
262 NS_LOG_WARN("OnOffApplication found null socket to close in StopApplication");
263 }
264}
265
266void
268{
269 NS_LOG_FUNCTION(this);
270
272 { // Cancel the pending send packet event
273 // Calculate residual bits since last packet sent
275 int64x64_t bits = delta.To(Time::S) * m_cbrRate.GetBitRate();
276 m_residualBits += bits.GetHigh();
277 }
281 // Canceling events may cause discontinuity in sequence number if the
282 // SeqTsSizeHeader is header, and m_unsentPacket is true
283 if (m_unsentPacket)
284 {
285 NS_LOG_DEBUG("Discarding cached packet upon CancelEvents ()");
286 }
287 m_unsentPacket = nullptr;
288}
289
290// Event handlers
291void
293{
294 NS_LOG_FUNCTION(this);
296 ScheduleNextTx(); // Schedule the send packet event
298}
299
300void
302{
303 NS_LOG_FUNCTION(this);
304 CancelEvents();
305
307}
308
309// Private helpers
310void
312{
313 NS_LOG_FUNCTION(this);
314
315 if (m_maxBytes == 0 || m_totBytes < m_maxBytes)
316 {
318 "Calculation to compute next send time will overflow");
319 uint32_t bits = m_pktSize * 8 - m_residualBits;
320 NS_LOG_LOGIC("bits = " << bits);
321 Time nextTime(
322 Seconds(bits / static_cast<double>(m_cbrRate.GetBitRate()))); // Time till next packet
323 NS_LOG_LOGIC("nextTime = " << nextTime.As(Time::S));
325 }
326 else
327 { // All done, cancel any pending events
329 }
330}
331
332void
334{ // Schedules the event to start sending data (switch to the "On" state)
335 NS_LOG_FUNCTION(this);
336
337 Time offInterval = Seconds(m_offTime->GetValue());
338 NS_LOG_LOGIC("start at " << offInterval.As(Time::S));
340}
341
342void
344{ // Schedules the event to stop sending data (switch to "Off" state)
345 NS_LOG_FUNCTION(this);
346
347 Time onInterval = Seconds(m_onTime->GetValue());
348 NS_LOG_LOGIC("stop at " << onInterval.As(Time::S));
350}
351
352void
354{
355 NS_LOG_FUNCTION(this);
356
358
359 Ptr<Packet> packet;
360 if (m_unsentPacket)
361 {
362 packet = m_unsentPacket;
363 }
365 {
366 Address from;
367 Address to;
368 m_socket->GetSockName(from);
370 SeqTsSizeHeader header;
371 header.SetSeq(m_seq++);
372 header.SetSize(m_pktSize);
374 packet = Create<Packet>(m_pktSize - header.GetSerializedSize());
375 // Trace before adding header, for consistency with PacketSink
376 m_txTraceWithSeqTsSize(packet, from, to, header);
377 packet->AddHeader(header);
378 }
379 else
380 {
381 packet = Create<Packet>(m_pktSize);
382 }
383
384 int actual = m_socket->Send(packet);
385 if ((unsigned)actual == m_pktSize)
386 {
387 m_txTrace(packet);
389 m_unsentPacket = nullptr;
390 Address localAddress;
391 m_socket->GetSockName(localAddress);
393 {
394 NS_LOG_INFO("At time " << Simulator::Now().As(Time::S) << " on-off application sent "
395 << packet->GetSize() << " bytes to "
398 << " total Tx " << m_totBytes << " bytes");
400 }
402 {
403 NS_LOG_INFO("At time " << Simulator::Now().As(Time::S) << " on-off application sent "
404 << packet->GetSize() << " bytes to "
407 << " total Tx " << m_totBytes << " bytes");
409 }
410 }
411 else
412 {
413 NS_LOG_DEBUG("Unable to send packet; actual " << actual << " size " << m_pktSize
414 << "; caching for later attempt");
415 m_unsentPacket = packet;
416 }
417 m_residualBits = 0;
420}
421
422void
424{
425 NS_LOG_FUNCTION(this << socket);
426
428 m_connected = true;
429}
430
431void
433{
434 NS_LOG_FUNCTION(this << socket);
435 NS_FATAL_ERROR("Can't connect");
436}
437
438} // Namespace ns3
a polymophic address class
Definition: address.h:101
bool IsInvalid() const
Definition: address.cc:71
AttributeValue implementation for Address.
Definition: address.h:286
The base class for all ns3 applications.
Definition: application.h:62
void DoDispose() override
Destructor implementation.
Definition: application.cc:86
Ptr< Node > GetNode() const
Definition: application.cc:108
AttributeValue implementation for Boolean.
Definition: boolean.h:37
Class for representing data rates.
Definition: data-rate.h:89
uint64_t GetBitRate() const
Get the underlying bitrate.
Definition: data-rate.cc:305
AttributeValue implementation for DataRate.
Definition: data-rate.h:296
bool IsExpired() const
This method is syntactic sugar for the ns3::Simulator::IsExpired method.
Definition: event-id.cc:69
bool IsRunning() const
This method is syntactic sugar for !IsExpired().
Definition: event-id.cc:76
static Inet6SocketAddress ConvertFrom(const Address &addr)
Convert the address to a InetSocketAddress.
uint16_t GetPort() const
Get the port.
static bool IsMatchingType(const Address &addr)
If the address match.
Ipv6Address GetIpv6() const
Get the IPv6 address.
static bool IsMatchingType(const Address &address)
Ipv4Address GetIpv4() const
static InetSocketAddress ConvertFrom(const Address &address)
Returns an InetSocketAddress which corresponds to the input Address.
Generate traffic to a single destination according to an OnOff pattern.
static TypeId GetTypeId()
Get the type ID.
uint8_t m_tos
The packets Type of Service.
uint32_t m_residualBits
Number of generated, but not sent, bits.
void ConnectionSucceeded(Ptr< Socket > socket)
Handle a Connection Succeed event.
EventId m_sendEvent
Event id of pending "send packet" event.
void ScheduleStartEvent()
Schedule the next On period start.
bool m_connected
True if connected.
uint32_t m_pktSize
Size of packets.
Ptr< Socket > GetSocket() const
Return a pointer to associated socket.
Ptr< Socket > m_socket
Associated socket.
TracedCallback< Ptr< const Packet > > m_txTrace
Traced Callback: transmitted packets.
void SetMaxBytes(uint64_t maxBytes)
Set the total number of bytes to send.
Ptr< RandomVariableStream > m_offTime
rng for Off Time
void StartApplication() override
Application specific startup code.
Ptr< Packet > m_unsentPacket
Unsent packet cached for future attempt.
int64_t AssignStreams(int64_t stream) override
Assign a fixed random variable stream number to the random variables used by this Application object.
TracedCallback< Ptr< const Packet >, const Address &, const Address & > m_txTraceWithAddresses
Callbacks for tracing the packet Tx events, includes source and destination addresses.
void DoDispose() override
Destructor implementation.
EventId m_startStopEvent
Event id for next start or stop event.
void ScheduleNextTx()
Schedule the next packet transmission.
DataRate m_cbrRateFailSafe
Rate that data is generated (check copy)
void ConnectionFailed(Ptr< Socket > socket)
Handle a Connection Failed event.
void ScheduleStopEvent()
Schedule the next Off period start.
TracedCallback< Ptr< const Packet >, const Address &, const Address &, const SeqTsSizeHeader & > m_txTraceWithSeqTsSize
Callback for tracing the packet Tx events, includes source, destination, the packet sent,...
uint64_t m_maxBytes
Limit total number of bytes sent.
Time m_lastStartTime
Time last packet sent.
uint64_t m_totBytes
Total bytes sent so far.
void StopSending()
Start an Off period.
void StartSending()
Start an On period.
Address m_local
Local address to bind to.
Ptr< RandomVariableStream > m_onTime
rng for On Time
bool m_enableSeqTsSizeHeader
Enable or disable the use of SeqTsSizeHeader.
TypeId m_tid
Type of the socket used.
uint32_t m_seq
Sequence.
DataRate m_cbrRate
Rate that data is generated.
void StopApplication() override
Application specific shutdown code.
Address m_peer
Peer address.
void CancelEvents()
Cancel all pending events.
void SendPacket()
Send a packet.
static bool IsMatchingType(const Address &address)
Smart pointer class similar to boost::intrusive_ptr.
Definition: ptr.h:77
virtual double GetValue()=0
Get the next random value drawn from the distribution.
void SetStream(int64_t stream)
Specifies the stream number for the RngStream.
void SetSeq(uint32_t seq)
Header with a sequence, a timestamp, and a "size" attribute.
uint32_t GetSerializedSize() const override
void SetSize(uint64_t size)
Set the size information that the header will carry.
static EventId Schedule(const Time &delay, FUNC f, Ts &&... args)
Schedule an event to expire after delay.
Definition: simulator.h:571
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:285
static Time Now()
Return the current simulation virtual time.
Definition: simulator.cc:208
virtual int Send(Ptr< Packet > p, uint32_t flags)=0
Send data (or dummy data) to the remote host.
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:87
void SetIpTos(uint8_t ipTos)
Manually set IP Type of Service field.
Definition: socket.cc:434
virtual bool SetAllowBroadcast(bool allowBroadcast)=0
Configure whether broadcast datagram transmissions are allowed.
virtual int ShutdownRecv()=0
virtual int Bind6()=0
Allocate a local IPv6 endpoint for this socket.
virtual int GetPeerName(Address &address) const =0
Get the peer address of a connected socket.
virtual int Connect(const Address &address)=0
Initiate a connection to a remote host.
virtual int GetSockName(Address &address) const =0
Get socket address.
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:72
virtual int Close()=0
Close a socket.
virtual int Bind(const Address &address)=0
Allocate a local endpoint for this socket.
Hold variables of type string.
Definition: string.h:56
Simulation virtual time values and global simulation resolution.
Definition: nstime.h:105
TimeWithUnit As(const Unit unit=Time::AUTO) const
Attach a unit to a Time, to facilitate output in a specific unit.
Definition: time.cc:415
@ S
second
Definition: nstime.h:116
a unique identifier for an interface.
Definition: type-id.h:59
TypeId SetParent(TypeId tid)
Set the parent TypeId.
Definition: type-id.cc:932
AttributeValue implementation for TypeId.
Definition: type-id.h:598
static TypeId GetTypeId()
Get the type ID.
Hold an unsigned integer type.
Definition: uinteger.h:45
High precision numerical type, implementing Q64.64 fixed precision.
Definition: int64x64-128.h:56
int64_t GetHigh() const
Get the integer portion.
Definition: int64x64-128.h:257
#define NS_ASSERT(condition)
At runtime, in debugging builds, if this condition is not true, the program prints the source file,...
Definition: assert.h:66
Ptr< const AttributeChecker > MakeAddressChecker()
Definition: address.cc:180
Ptr< const AttributeAccessor > MakeAddressAccessor(T1 a1)
Definition: address.h:286
Ptr< const AttributeAccessor > MakeBooleanAccessor(T1 a1)
Definition: boolean.h:81
Ptr< const AttributeChecker > MakeBooleanChecker()
Definition: boolean.cc:124
Ptr< const AttributeAccessor > MakeDataRateAccessor(T1 a1)
Definition: data-rate.h:296
Ptr< const AttributeChecker > MakeDataRateChecker()
Definition: data-rate.cc:31
Ptr< const AttributeAccessor > MakePointerAccessor(T1 a1)
Definition: pointer.h:259
Ptr< const AttributeChecker > MakeTypeIdChecker()
Definition: type-id.cc:1251
Ptr< const AttributeAccessor > MakeTypeIdAccessor(T1 a1)
Definition: type-id.h:598
Ptr< const AttributeAccessor > MakeUintegerAccessor(T1 a1)
Definition: uinteger.h:46
#define NS_FATAL_ERROR(msg)
Report a fatal error with a message and terminate.
Definition: fatal-error.h:179
#define NS_ABORT_MSG_IF(cond, msg)
Abnormal program termination if a condition is true, with a message.
Definition: abort.h:108
#define NS_ABORT_IF(cond)
Abnormal program termination if a condition is true.
Definition: abort.h:76
#define NS_LOG_COMPONENT_DEFINE(name)
Define a Log component with a specific name.
Definition: log.h:202
#define NS_LOG_DEBUG(msg)
Use NS_LOG to output a message of level LOG_DEBUG.
Definition: log.h:268
#define NS_LOG_LOGIC(msg)
Use NS_LOG to output a message of level LOG_LOGIC.
Definition: log.h:282
#define NS_LOG_FUNCTION(parameters)
If log level LOG_FUNCTION is enabled, this macro will output all input parameters separated by ",...
#define NS_LOG_WARN(msg)
Use NS_LOG to output a message of level LOG_WARN.
Definition: log.h:261
#define NS_LOG_INFO(msg)
Use NS_LOG to output a message of level LOG_INFO.
Definition: log.h:275
#define NS_OBJECT_ENSURE_REGISTERED(type)
Register an Object subclass with the TypeId system.
Definition: object-base.h:46
Time Seconds(double value)
Construct a Time in the indicated unit.
Definition: nstime.h:1326
Ptr< const TraceSourceAccessor > MakeTraceSourceAccessor(T a)
Create a TraceSourceAccessor which will control access to the underlying trace source.
Every class exported by the ns3 library is enclosed in the ns3 namespace.
Callback< R, Args... > MakeCallback(R(T::*memPtr)(Args...), OBJ objPtr)
Build Callbacks for class method members which take varying numbers of arguments and potentially retu...
Definition: callback.h:704