25 except ModuleNotFoundError:
27 "Error: ns3 Python module not found;"
28 " Python bindings may not be enabled"
29 " or your PYTHONPATH might not be properly configured"
33 UINT32_MAX = 0xFFFFFFFF
48 """! Test schedule now
49 @param self this object
53 def callback(args: ns.cppyy.gbl.std.vector) ->
None:
54 """! Callback function
61 ns.Simulator.Destroy()
66 EventImpl* pythonMakeEvent(void (*f)(std::vector<std::string>), std::vector<std::string> l)
68 return MakeEvent(f, l);
72 event = ns.cppyy.gbl.pythonMakeEvent(callback, sys.argv)
73 ns.Simulator.ScheduleNow(event)
76 self.assertEqual(self.
_cb_time_cb_time.GetSeconds(), 0.0)
80 @param self this object
84 def callback(args: ns.cppyy.gbl.std.vector):
85 """! Callback function
90 self.
_cb_time_cb_time = ns.Simulator.Now()
92 ns.Simulator.Destroy()
97 EventImpl* pythonMakeEvent2(void (*f)(std::vector<std::string>), std::vector<std::string> l)
99 return MakeEvent(f, l);
103 event = ns.cppyy.gbl.pythonMakeEvent2(callback, sys.argv)
104 ns.Simulator.Schedule(ns.Seconds(123), event)
107 self.assertEqual(self.
_cb_time_cb_time.GetSeconds(), 123.0)
110 """! Test schedule destroy
111 @param self this object
115 def callback(args: ns.cppyy.gbl.std.vector):
116 """! Callback function
121 self.
_cb_time_cb_time = ns.Simulator.Now()
123 ns.Simulator.Destroy()
126 ns.cppyy.cppdef(
"void null(){ return; }")
127 ns.Simulator.Schedule(ns.Seconds(123), ns.cppyy.gbl.null)
130 EventImpl* pythonMakeEvent3(void (*f)(std::vector<std::string>), std::vector<std::string> l)
132 return MakeEvent(f, l);
136 event = ns.cppyy.gbl.pythonMakeEvent3(callback, sys.argv)
137 ns.Simulator.ScheduleDestroy(event)
139 ns.Simulator.Destroy()
141 self.assertEqual(self.
_cb_time_cb_time.GetSeconds(), 123.0)
144 """! Test schedule with context
145 @param self this object
149 def callback(context, args: ns.cppyy.gbl.std.vector):
151 @param context the context
152 @param args the arguments
157 self.
_cb_time_cb_time = ns.Simulator.Now()
159 ns.Simulator.Destroy()
165 EventImpl* pythonMakeEvent4(void (*f)(uint32_t, std::vector<std::string>), uint32_t context, std::vector<std::string> l)
167 return MakeEvent(f, context, l);
171 event = ns.cppyy.gbl.pythonMakeEvent4(callback, 54321, sys.argv)
172 ns.Simulator.ScheduleWithContext(54321, ns.Seconds(123), event)
176 self.assertEqual(self.
_cb_time_cb_time.GetSeconds(), 123.0)
179 """! Test time comparison
180 @param self this object
183 self.assertTrue(ns.Seconds(123) == ns.Seconds(123))
184 self.assertTrue(ns.Seconds(123) >= ns.Seconds(123))
185 self.assertTrue(ns.Seconds(123) <= ns.Seconds(123))
186 self.assertTrue(ns.Seconds(124) > ns.Seconds(123))
187 self.assertTrue(ns.Seconds(123) < ns.Seconds(124))
190 """! Test numeric operations
191 @param self this object
194 self.assertEqual(ns.Seconds(10) + ns.Seconds(5), ns.Seconds(15))
195 self.assertEqual(ns.Seconds(10) - ns.Seconds(5), ns.Seconds(5))
197 v1 = ns.int64x64_t(5.0) * ns.int64x64_t(10)
198 self.assertEqual(v1, ns.int64x64_t(50))
201 """! Test configuration
202 @param self this object
205 ns.Config.SetDefault(
"ns3::OnOffApplication::PacketSize", ns.core.UintegerValue(123))
213 nc = ns.NodeContainer(1)
215 internet = ns.CreateObject(
"InternetStackHelper")
216 internet.Install(node)
219 def python_rx_callback(socket) -> None:
220 self.
_received_packet_received_packet = socket.Recv(maxSize=UINT32_MAX, flags=0)
224 Callback<void,ns3::Ptr<ns3::Socket> > make_rx_callback_test_socket(void(*func)(Ptr<Socket>))
226 return MakeCallback(func);
231 sink = ns.network.Socket.CreateSocket(
232 node, ns.core.TypeId.LookupByName(
"ns3::UdpSocketFactory")
234 sink.Bind(ns.network.InetSocketAddress(ns.network.Ipv4Address.GetAny(), 80).ConvertTo())
235 sink.SetRecvCallback(ns.cppyy.gbl.make_rx_callback_test_socket(python_rx_callback))
237 source = ns.network.Socket.CreateSocket(
238 node, ns.core.TypeId.LookupByName(
"ns3::UdpSocketFactory")
241 ns.network.Packet(19),
243 ns.network.InetSocketAddress(ns.network.Ipv4Address(
"127.0.0.1"), 80).ConvertTo(),
254 """! Test attributes function
255 @param self this object
259 queue = ns.CreateObject(
"DropTailQueue<Packet>")
260 queueSizeValue = ns.network.QueueSizeValue(ns.network.QueueSize(
"500p"))
261 queue.SetAttribute(
"MaxSize", queueSizeValue)
263 limit = ns.network.QueueSizeValue()
264 queue.GetAttribute(
"MaxSize", limit)
265 self.assertEqual(limit.Get(), ns.network.QueueSize(
"500p"))
268 mobility = ns.CreateObject(
"RandomWaypointMobilityModel")
269 ptr = ns.CreateObject(
"PointerValue")
270 mobility.GetAttribute(
"PositionAllocator", ptr)
271 self.assertEqual(ptr.GetObject(), ns.core.Ptr[
"Object"](ns.cppyy.nullptr))
273 pos = ns.mobility.ListPositionAllocator()
275 mobility.SetAttribute(
"PositionAllocator", ptr)
277 ptr2 = ns.CreateObject(
"PointerValue")
278 mobility.GetAttribute(
"PositionAllocator", ptr2)
279 self.assertNotEqual(ptr.GetObject(), ns.core.Ptr[
"Object"](ns.cppyy.nullptr))
282 del queue, mobility, ptr, ptr2
286 @param self this object
289 csma = ns.CreateObject(
"CsmaNetDevice")
290 channel = ns.CreateObject(
"CsmaChannel")
293 c1 = csma.GetChannel()
294 c2 = csma.GetChannel()
296 self.assertEqual(c1, c2)
303 @param self this object
306 ok, typeId1 = ns.LookupByNameFailSafe(
"ns3::UdpSocketFactory")
308 self.assertEqual(typeId1.GetName(),
"ns3::UdpSocketFactory")
310 ok, typeId1 = ns.LookupByNameFailSafe(
"ns3::__InvalidTypeName__")
314 """! Test command line
315 @param self this object
318 from ctypes
import c_bool, c_char_p, c_double, c_int, create_string_buffer
322 test3 = c_double(3.1415)
324 test4Buffer = create_string_buffer(b
"this is a test option", BUFFLEN)
325 test4 = c_char_p(test4Buffer.raw)
327 cmd = ns.core.CommandLine(__file__)
328 cmd.AddValue(
"Test1",
"this is a test option", test1)
329 cmd.AddValue(
"Test2",
"this is a test option", test2)
330 cmd.AddValue[
"double"](
"Test3",
"this is a test option", test3)
331 cmd.AddValue(
"Test4",
"this is a test option", test4, BUFFLEN)
333 cmd.Parse([
"python"])
334 self.assertEqual(test1.value,
True)
335 self.assertEqual(test2.value, 42)
336 self.assertEqual(test3.value, 3.1415)
337 self.assertEqual(test4.value, b
"this is a test option")
339 cmd.Parse([
"python",
"--Test1=false",
"--Test2=0",
"--Test3=0.0"])
340 self.assertEqual(test1.value,
False)
341 self.assertEqual(test2.value, 0)
342 self.assertEqual(test3.value, 0.0)
344 cmd.Parse([
"python",
"--Test4=new_string"])
345 self.assertEqual(test4.value, b
"new_string")
349 @param self this object
354 class MyNode(ns.network.Node):
355 def GetLocalTime(self) -> ns.Time:
356 return ns.Seconds(10)
359 forced_local_time = node.GetLocalTime()
360 self.assertEqual(forced_local_time, ns.Seconds(10))
364 """! Test python-based application
365 @param self this object
368 ns.Simulator.Destroy()
370 nodes = ns.network.NodeContainer()
373 pointToPoint = ns.point_to_point.PointToPointHelper()
374 pointToPoint.SetDeviceAttribute(
"DataRate", ns.core.StringValue(
"5Mbps"))
375 pointToPoint.SetChannelAttribute(
"Delay", ns.core.StringValue(
"2ms"))
377 devices = pointToPoint.Install(nodes)
379 stack = ns.internet.InternetStackHelper()
382 address = ns.internet.Ipv4AddressHelper()
383 address.SetBase(ns.network.Ipv4Address(
"10.1.1.0"), ns.network.Ipv4Mask(
"255.255.255.0"))
385 interfaces = address.Assign(devices)
391 Callback<void,Ptr<Socket> > make_rx_callback(void(*func)(Ptr<Socket>))
393 return MakeCallback(func);
395 EventImpl* pythonMakeEventSend(void (*f)(Ptr<Socket>, Ptr<Packet>, Address&), Ptr<Socket> socket, Ptr<Packet> packet, Address address)
397 return MakeEvent(f, socket, packet, address);
404 class EchoServer(ns.applications.Application):
407 socketToInstanceDict = {}
409 def __init__(self, node: ns.Node, port=ECHO_PORT):
410 """! Constructor needs to call first the constructor to Application (super class)
411 @param self this object
412 @param node node where this application will be executed
413 @param port port to listen
422 self.
m_socketm_socket = ns.network.Socket.CreateSocket(
423 node, ns.core.TypeId.LookupByName(
"ns3::UdpSocketFactory")
426 ns.network.InetSocketAddress(
427 ns.network.Ipv4Address.GetAny(), self.
portport
430 self.
m_socketm_socket.SetRecvCallback(ns.make_rx_callback(EchoServer._Receive))
431 EchoServer.socketToInstanceDict[self.
m_socketm_socket] = self
435 @param self this object
438 del EchoServer.socketToInstanceDict[self.
m_socketm_socket]
440 def Send(self, packet: ns.Packet, address: ns.Address) ->
None:
441 """! Function to send a packet to an address
442 @param self this object
443 @param packet packet to send
444 @param address destination address
447 self.
m_socketm_socket.SendTo(packet, 0, address)
448 if EchoServer.LOGGING:
449 inetAddress = ns.InetSocketAddress.ConvertFrom(address)
451 "At time +{s}s server sent {b} bytes from {ip} port {port}".format(
452 s=ns.Simulator.Now().GetSeconds(),
453 b=packet.__deref__().
GetSize(),
454 ip=inetAddress.GetIpv4(),
455 port=inetAddress.GetPort(),
462 """! Function to receive a packet from an address
463 @param self this object
466 address = ns.Address()
467 packet = self.
m_socketm_socket.RecvFrom(address)
468 if EchoServer.LOGGING:
469 inetAddress = ns.InetSocketAddress.ConvertFrom(address)
471 "At time +{s}s server received {b} bytes from {ip} port {port}".format(
472 s=ns.Simulator.Now().GetSeconds(),
473 b=packet.__deref__().
GetSize(),
474 ip=inetAddress.GetIpv4(),
475 port=inetAddress.GetPort(),
480 event = ns.pythonMakeEventSend(EchoServer._Send, self.
m_socketm_socket, packet, address)
481 ns.Simulator.Schedule(ns.Seconds(1), event)
484 def _Send(socket: ns.Socket, packet: ns.Packet, address: ns.Address):
485 """! Static send function, which matches the output socket
486 to the EchoServer instance to call the instance Send function
487 @param socket socket from the instance that should send the packet
488 @param packet packet to send
489 @param address destination address
492 instance = EchoServer.socketToInstanceDict[socket]
493 instance.Send(packet, address)
496 def _Receive(socket: ns.Socket) ->
None:
497 """! Static receive function, which matches the input socket
498 to the EchoServer instance to call the instance Receive function
499 @param socket socket from the instance that should receive the packet
502 instance = EchoServer.socketToInstanceDict[socket]
505 echoServer = EchoServer(nodes.Get(1))
506 nodes.Get(1).AddApplication(echoServer)
508 serverApps = ns.ApplicationContainer()
509 serverApps.Add(echoServer)
510 serverApps.Start(ns.core.Seconds(1.0))
511 serverApps.Stop(ns.core.Seconds(10.0))
513 address = interfaces.GetAddress(1).ConvertTo()
514 echoClient = ns.applications.UdpEchoClientHelper(address, EchoServer.ECHO_PORT)
515 echoClient.SetAttribute(
"MaxPackets", ns.core.UintegerValue(10))
516 echoClient.SetAttribute(
"Interval", ns.core.TimeValue(ns.core.Seconds(1.0)))
517 echoClient.SetAttribute(
"PacketSize", ns.core.UintegerValue(101))
519 clientApps = echoClient.Install(nodes.Get(0))
520 clientApps.Start(ns.core.Seconds(2.0))
521 clientApps.Stop(ns.core.Seconds(10.0))
524 ns.Simulator.Destroy()
527 if __name__ ==
"__main__":
528 unittest.main(verbosity=1, failfast=
True)
def testScheduleDestroy(self)
Test schedule destroy.
port
Listen port for the server.
def testCommandLine(self)
Test command line.
def testTimeNumericOperations(self)
Test numeric operations.
def testEchoServerApplication(self)
Test python-based application.
__python_owns__
EchoServer application class.
def testScheduleNow(self)
Test schedule now.
def testTypeId(self)
Test type ID.
def testSubclass(self)
Test subclass.
def testSchedule(self)
Test schedule.
def testScheduleWithContext(self)
Test schedule with context.
def testAttributes(self)
Test attributes function.
def testSocket(self)
Test socket.
def testTimeComparison(self)
Test time comparison.
def testConfig(self)
Test configuration.
m_socket
Socket used by the server to listen to port.
_received_packet
received packet
def testIdentity(self)
Test identify.
static void Send(Ptr< NetDevice > dev, int level, std::string emuMode)
uint32_t GetSize(Ptr< const Packet > packet, const WifiMacHeader *hdr, bool isAmpdu)
Return the total size of the packet after WifiMacHeader and FCS trailer have been added.