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// SPDX-License-Identifier: GPL-2.0-only
5//
6// Author: George F. Riley<riley@ece.gatech.edu>
7//
8
9// ns3 - On/Off Data Source Application class
10// George F. Riley, Georgia Tech, Spring 2007
11// Adapted from ApplicationOnOff in GTNetS.
12
13#include "onoff-application.h"
14
15#include "ns3/boolean.h"
16#include "ns3/data-rate.h"
17#include "ns3/inet-socket-address.h"
18#include "ns3/inet6-socket-address.h"
19#include "ns3/log.h"
20#include "ns3/node.h"
21#include "ns3/nstime.h"
22#include "ns3/packet-socket-address.h"
23#include "ns3/packet.h"
24#include "ns3/pointer.h"
25#include "ns3/random-variable-stream.h"
26#include "ns3/simulator.h"
27#include "ns3/socket-factory.h"
28#include "ns3/socket.h"
29#include "ns3/string.h"
30#include "ns3/trace-source-accessor.h"
31#include "ns3/udp-socket-factory.h"
32#include "ns3/uinteger.h"
33
34namespace ns3
35{
36
37NS_LOG_COMPONENT_DEFINE("OnOffApplication");
38
40
43{
44 static TypeId tid =
45 TypeId("ns3::OnOffApplication")
47 .SetGroupName("Applications")
48 .AddConstructor<OnOffApplication>()
49 .AddAttribute("DataRate",
50 "The data rate in on state.",
51 DataRateValue(DataRate("500kb/s")),
54 .AddAttribute("PacketSize",
55 "The size of packets sent in on state",
56 UintegerValue(512),
59 .AddAttribute("OnTime",
60 "A RandomVariableStream used to pick the duration of the 'On' state.",
61 StringValue("ns3::ConstantRandomVariable[Constant=1.0]"),
64 .AddAttribute("OffTime",
65 "A RandomVariableStream used to pick the duration of the 'Off' state.",
66 StringValue("ns3::ConstantRandomVariable[Constant=1.0]"),
69 .AddAttribute("MaxBytes",
70 "The total number of bytes to send. Once these bytes are sent, "
71 "no packet is sent again, even in on state. The value zero means "
72 "that there is no limit.",
76 .AddAttribute("Protocol",
77 "The type of protocol to use. This should be "
78 "a subclass of ns3::SocketFactory",
81 // This should check for SocketFactory as a parent
83 .AddAttribute("EnableSeqTsSizeHeader",
84 "Enable use of SeqTsSizeHeader for sequence number and timestamp",
85 BooleanValue(false),
88 .AddTraceSource("TxWithAddresses",
89 "A new packet is created and is sent",
91 "ns3::Packet::TwoAddressTracedCallback")
92 .AddTraceSource("TxWithSeqTsSize",
93 "A new packet is created with SeqTsSizeHeader",
95 "ns3::PacketSink::SeqTsSizeCallback")
96 .AddTraceSource("OnOffState",
97 "Application state (0-OFF, 1-ON)",
99 "ns3::TracedValueCallback::Bool");
100 return tid;
101}
102
107
112
113void
115{
116 NS_LOG_FUNCTION(this << maxBytes);
117 m_maxBytes = maxBytes;
118}
119
120int64_t
122{
123 NS_LOG_FUNCTION(this << stream);
124 auto currentStream = stream;
125 m_onTime->SetStream(currentStream++);
126 m_offTime->SetStream(currentStream++);
127 currentStream += SourceApplication::AssignStreams(currentStream);
128 return (currentStream - stream);
129}
130
131// Application Methods
132void
133OnOffApplication::DoStartApplication() // Called at time specified by Start
134{
135 NS_LOG_FUNCTION(this);
136
137 m_socket->SetAllowBroadcast(true);
138 m_socket->ShutdownRecv();
139
141
142 // If we are not yet connected, there is nothing to do here,
143 // the ConnectionComplete upcall will start timers at that time.
144 // If we are already connected, CancelEvents did remove the events,
145 // so we have to start them again.
146 if (m_connected)
147 {
149 }
150}
151
152void
154{
155 NS_LOG_FUNCTION(this);
156
157 if (m_sendEvent.IsPending() && m_cbrRateFailSafe == m_cbrRate)
158 { // Cancel the pending send packet event
159 // Calculate residual bits since last packet sent
161 int64x64_t bits = delta.To(Time::S) * m_cbrRate.GetBitRate();
162 m_residualBits += bits.GetHigh();
163 }
167 // Canceling events may cause discontinuity in sequence number if the
168 // SeqTsSizeHeader is header, and m_unsentPacket is true
169 if (m_unsentPacket)
170 {
171 NS_LOG_DEBUG("Discarding cached packet upon CancelEvents ()");
172 }
173 m_unsentPacket = nullptr;
174}
175
176// Event handlers
177void
179{
180 NS_LOG_FUNCTION(this);
182 ScheduleNextTx(); // Schedule the send packet event
184 m_state = true;
185}
186
187void
195
196// Private helpers
197void
199{
200 NS_LOG_FUNCTION(this);
201
202 if (m_maxBytes == 0 || m_totBytes < m_maxBytes)
203 {
205 "Calculation to compute next send time will overflow");
206 uint32_t bits = m_pktSize * 8 - m_residualBits;
207 NS_LOG_LOGIC("bits = " << bits);
208 Time nextTime(
209 Seconds(bits / static_cast<double>(m_cbrRate.GetBitRate()))); // Time till next packet
210 NS_LOG_LOGIC("nextTime = " << nextTime.As(Time::S));
212 }
213 else
214 {
215 // All done, cancel any pending events and close connection
216 CancelEvents();
217 CloseSocket();
218 }
219}
220
221void
223{ // Schedules the event to start sending data (switch to the "On" state)
224 NS_LOG_FUNCTION(this);
225
226 Time offInterval = Seconds(m_offTime->GetValue());
227 NS_LOG_LOGIC("start at " << offInterval.As(Time::S));
229}
230
231void
233{ // Schedules the event to stop sending data (switch to "Off" state)
234 NS_LOG_FUNCTION(this);
235
236 Time onInterval = Seconds(m_onTime->GetValue());
237 NS_LOG_LOGIC("stop at " << onInterval.As(Time::S));
239}
240
241void
243{
244 NS_LOG_FUNCTION(this);
245
246 NS_ASSERT(m_sendEvent.IsExpired());
247
248 Ptr<Packet> packet;
249 if (m_unsentPacket)
250 {
251 packet = m_unsentPacket;
252 }
254 {
255 Address from;
256 Address to;
257 m_socket->GetSockName(from);
258 m_socket->GetPeerName(to);
259 SeqTsSizeHeader header;
260 header.SetSeq(m_seq++);
261 header.SetSize(m_pktSize);
263 packet = Create<Packet>(m_pktSize - header.GetSerializedSize());
264 // Trace before adding header, for consistency with PacketSink
265 m_txTraceWithSeqTsSize(packet, from, to, header);
266 packet->AddHeader(header);
267 }
268 else
269 {
270 packet = Create<Packet>(m_pktSize);
271 }
272
273 int actual = m_socket->Send(packet);
274 if ((unsigned)actual == m_pktSize)
275 {
276 m_txTrace(packet);
278 m_unsentPacket = nullptr;
279 Address localAddress;
280 m_socket->GetSockName(localAddress);
282 {
283 NS_LOG_INFO("At time " << Simulator::Now().As(Time::S) << " on-off application sent "
284 << packet->GetSize() << " bytes to "
285 << InetSocketAddress::ConvertFrom(m_peer).GetIpv4() << " port "
287 << " total Tx " << m_totBytes << " bytes");
289 }
291 {
292 NS_LOG_INFO("At time " << Simulator::Now().As(Time::S) << " on-off application sent "
293 << packet->GetSize() << " bytes to "
294 << Inet6SocketAddress::ConvertFrom(m_peer).GetIpv6() << " port "
296 << " total Tx " << m_totBytes << " bytes");
298 }
299 }
300 else
301 {
302 NS_LOG_DEBUG("Unable to send packet; actual " << actual << " size " << m_pktSize
303 << "; caching for later attempt");
304 m_unsentPacket = packet;
305 }
306 m_residualBits = 0;
309}
310
311void
317
318} // Namespace ns3
a polymophic address class
Definition address.h:111
virtual int64_t AssignStreams(int64_t stream)
Assign a fixed random variable stream number to the random variables used by this Application object.
AttributeValue implementation for Boolean.
Definition boolean.h:26
Class for representing data rates.
Definition data-rate.h:78
AttributeValue implementation for DataRate.
Definition data-rate.h:285
static Inet6SocketAddress ConvertFrom(const Address &addr)
Convert the address to a InetSocketAddress.
static bool IsMatchingType(const Address &addr)
If the address match.
static bool IsMatchingType(const Address &address)
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.
uint32_t m_residualBits
Number of generated, but not sent, bits.
TracedValue< bool > m_state
State of application (0-OFF, 1-ON).
EventId m_sendEvent
Event id of pending "send packet" event.
void ScheduleStartEvent()
Schedule the next On period start.
uint32_t m_pktSize
Size of packets.
void SetMaxBytes(uint64_t maxBytes)
Set the total number of bytes to send.
Ptr< RandomVariableStream > m_offTime
rng for Off Time
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.
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 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,...
void CancelEvents() override
Cancel all pending events.
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.
void DoStartApplication() override
Application specific startup code for child subclasses.
Ptr< RandomVariableStream > m_onTime
rng for On Time
bool m_enableSeqTsSizeHeader
Enable or disable the use of SeqTsSizeHeader.
uint32_t m_seq
Sequence.
DataRate m_cbrRate
Rate that data is generated.
void DoConnectionSucceeded(Ptr< Socket > socket) override
Application specific code for child subclasses upon a Connection Succeed event.
void SendPacket()
Send a packet.
Smart pointer class similar to boost::intrusive_ptr.
Definition ptr.h:67
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:561
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:274
static Time Now()
Return the current simulation virtual time.
Definition simulator.cc:197
TypeId m_protocolTid
Protocol TypeId value.
SourceApplication(bool allowPacketSocket=true)
Constructor.
Ptr< Socket > m_socket
Socket.
TracedCallback< Ptr< const Packet > > m_txTrace
Traced Callback: transmitted packets.
bool m_connected
flag whether socket is connected
Address m_peer
Peer address.
bool CloseSocket()
Close the socket.
Hold variables of type string.
Definition string.h:45
Simulation virtual time values and global simulation resolution.
Definition nstime.h:96
TimeWithUnit As(const Unit unit=Time::AUTO) const
Attach a unit to a Time, to facilitate output in a specific unit.
Definition time.cc:409
@ S
second
Definition nstime.h:107
a unique identifier for an interface.
Definition type-id.h:49
TypeId SetParent(TypeId tid)
Set the parent TypeId.
Definition type-id.cc:1001
AttributeValue implementation for TypeId.
Definition type-id.h:641
static TypeId GetTypeId()
Get the type ID.
Hold an unsigned integer type.
Definition uinteger.h:34
High precision numerical type, implementing Q64.64 fixed precision.
int64_t GetHigh() const
Get the integer portion.
#define NS_ASSERT(condition)
At runtime, in debugging builds, if this condition is not true, the program prints the source file,...
Definition assert.h:55
Ptr< const AttributeChecker > MakeBooleanChecker()
Definition boolean.cc:114
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:70
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:285
Ptr< const AttributeChecker > MakeDataRateChecker()
Definition data-rate.cc:20
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:249
Ptr< AttributeChecker > MakePointerChecker()
Create a PointerChecker for a type.
Definition pointer.h:270
Ptr< const AttributeChecker > MakeTypeIdChecker()
Definition type-id.cc:1335
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:641
Ptr< const AttributeChecker > MakeUintegerChecker()
Definition uinteger.h:85
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:35
#define NS_ABORT_MSG_IF(cond, msg)
Abnormal program termination if a condition is true, with a message.
Definition abort.h:97
#define NS_ABORT_IF(cond)
Abnormal program termination if a condition is true.
Definition abort.h:65
#define NS_LOG_COMPONENT_DEFINE(name)
Define a Log component with a specific name.
Definition log.h:191
#define NS_LOG_DEBUG(msg)
Use NS_LOG to output a message of level LOG_DEBUG.
Definition log.h:257
#define NS_LOG_LOGIC(msg)
Use NS_LOG to output a message of level LOG_LOGIC.
Definition log.h:271
#define NS_LOG_FUNCTION(parameters)
If log level LOG_FUNCTION is enabled, this macro will output all input parameters separated by ",...
#define NS_LOG_INFO(msg)
Use NS_LOG to output a message of level LOG_INFO.
Definition log.h:264
#define NS_OBJECT_ENSURE_REGISTERED(type)
Register an Object subclass with the TypeId system.
Definition object-base.h:35
Ptr< T > Create(Ts &&... args)
Create class instances by constructors with varying numbers of arguments and return them by Ptr.
Definition ptr.h:439
Time Seconds(double value)
Construct a Time in the indicated unit.
Definition nstime.h:1369
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.