A Discrete-Event Network Simulator
API
Loading...
Searching...
No Matches
lorawan-test-suite.cc
Go to the documentation of this file.
1/*
2 * Copyright (c) 2017 University of Padova
3 *
4 * SPDX-License-Identifier: GPL-2.0-only
5 *
6 * Author: Davide Magrin <magrinda@dei.unipd.it>
7 */
8
9// An essential include is test.h
10#include "ns3/basic-energy-source-helper.h"
11#include "ns3/constant-position-mobility-model.h"
12#include "ns3/log.h"
13#include "ns3/propagation-delay-model.h"
14#include "ns3/propagation-loss-model.h"
15#include "ns3/simulator.h"
16#include "ns3/test.h"
17
18// Include headers of classes to test
19#include "ns3/class-a-end-device-lorawan-mac.h"
20#include "ns3/lora-net-device.h"
21#include "ns3/lora-radio-energy-model-helper.h"
22#include "ns3/lora-utils.h"
23#include "ns3/lorawan-mac-helper.h"
24#include "ns3/periodic-sender.h"
25#include "ns3/simple-end-device-lora-phy.h"
26#include "ns3/simple-gateway-lora-phy.h"
27
28using namespace ns3;
29using namespace lorawan;
30
31NS_LOG_COMPONENT_DEFINE("LorawanTestSuite");
32
33/**
34 * @ingroup lorawan
35 *
36 * It tests interference computations in a number of possible scenarios using the
37 * LoraInterferenceHelper class
38 */
40{
41 public:
42 InterferenceTest(); //!< Default constructor
43 ~InterferenceTest() override; //!< Destructor
44
45 private:
46 void DoRun() override;
47};
48
49// Add some help text to this case to describe what it is intended to test
51 : TestCase("Verify that LoraInterferenceHelper works as expected")
52{
53}
54
55// Reminder that the test case should clean up after itself
59
60// This method is the pure virtual method from class TestCase that every
61// TestCase must implement
62void
64{
65 NS_LOG_DEBUG("InterferenceTest");
66
67 LoraInterferenceHelper interferenceHelper;
68
69 uint32_t frequencyHz = 868100000;
70 uint32_t differentFrequencyHz = 868300000;
71
74
75 // Test overlap duration
76 event = interferenceHelper.Add(Seconds(2), 14, 7, nullptr, frequencyHz);
77 event1 = interferenceHelper.Add(Seconds(1), 14, 12, nullptr, frequencyHz);
78 NS_TEST_EXPECT_MSG_EQ(interferenceHelper.GetOverlapTime(event, event1),
79 Seconds(1),
80 "Overlap computation didn't give the expected result");
81 interferenceHelper.ClearAllEvents();
82
83 event = interferenceHelper.Add(Seconds(2), 14, 7, nullptr, frequencyHz);
84 event1 = interferenceHelper.Add(Seconds(1.5), 14, 12, nullptr, frequencyHz);
85 NS_TEST_EXPECT_MSG_EQ(interferenceHelper.GetOverlapTime(event, event1),
86 Seconds(1.5),
87 "Overlap computation didn't give the expected result");
88 interferenceHelper.ClearAllEvents();
89
90 event = interferenceHelper.Add(Seconds(2), 14, 7, nullptr, frequencyHz);
91 event1 = interferenceHelper.Add(Seconds(3), 14, 12, nullptr, frequencyHz);
92 NS_TEST_EXPECT_MSG_EQ(interferenceHelper.GetOverlapTime(event, event1),
93 Seconds(2),
94 "Overlap computation didn't give the expected result");
95 interferenceHelper.ClearAllEvents();
96
97 event = interferenceHelper.Add(Seconds(2), 14, 7, nullptr, frequencyHz);
98 event1 = interferenceHelper.Add(Seconds(2), 14, 12, nullptr, frequencyHz);
99 // Because of some strange behavior, this test would get stuck if we used the same syntax of the
100 // previous ones. This works instead.
101 bool retval = interferenceHelper.GetOverlapTime(event, event1) == Seconds(2);
102 NS_TEST_EXPECT_MSG_EQ(retval, true, "Overlap computation didn't give the expected result");
103 interferenceHelper.ClearAllEvents();
104
105 // Perfect overlap, packet survives
106 event = interferenceHelper.Add(Seconds(2), 14, 7, nullptr, frequencyHz);
107 interferenceHelper.Add(Seconds(2), 14, 12, nullptr, frequencyHz);
108 NS_TEST_EXPECT_MSG_EQ(interferenceHelper.IsDestroyedByInterference(event),
109 0,
110 "Packet did not survive interference as expected");
111 interferenceHelper.ClearAllEvents();
112
113 // Perfect overlap, packet survives
114 event = interferenceHelper.Add(Seconds(2), 14, 7, nullptr, frequencyHz);
115 interferenceHelper.Add(Seconds(2), 14 - 7, 7, nullptr, frequencyHz);
116 NS_TEST_EXPECT_MSG_EQ(interferenceHelper.IsDestroyedByInterference(event),
117 0,
118 "Packet did not survive interference as expected");
119 interferenceHelper.ClearAllEvents();
120
121 // Perfect overlap, packet destroyed
122 event = interferenceHelper.Add(Seconds(2), 14, 7, nullptr, frequencyHz);
123 interferenceHelper.Add(Seconds(2), 14 - 6, 7, nullptr, frequencyHz);
124 NS_TEST_EXPECT_MSG_EQ(interferenceHelper.IsDestroyedByInterference(event),
125 7,
126 "Packet was not destroyed by interference as expected");
127 interferenceHelper.ClearAllEvents();
128
129 // Partial overlap, packet survives
130 event = interferenceHelper.Add(Seconds(2), 14, 7, nullptr, frequencyHz);
131 interferenceHelper.Add(Seconds(1), 14 - 6, 7, nullptr, frequencyHz);
132 NS_TEST_EXPECT_MSG_EQ(interferenceHelper.IsDestroyedByInterference(event),
133 0,
134 "Packet did not survive interference as expected");
135 interferenceHelper.ClearAllEvents();
136
137 // Different frequencys
138 // Packet would be destroyed if they were on the same frequency, but survives
139 // since they are on different frequencies
140 event = interferenceHelper.Add(Seconds(2), 14, 7, nullptr, frequencyHz);
141 interferenceHelper.Add(Seconds(2), 14, 7, nullptr, differentFrequencyHz);
142 NS_TEST_EXPECT_MSG_EQ(interferenceHelper.IsDestroyedByInterference(event),
143 0,
144 "Packet did not survive interference as expected");
145 interferenceHelper.ClearAllEvents();
146
147 // Different SFs
148 // Packet would be destroyed if they both were SF7, but survives thanks to spreading factor
149 // semi-orthogonality
150 event = interferenceHelper.Add(Seconds(2), 14, 7, nullptr, frequencyHz);
151 interferenceHelper.Add(Seconds(2), 14 + 16, 8, nullptr, frequencyHz);
152 NS_TEST_EXPECT_MSG_EQ(interferenceHelper.IsDestroyedByInterference(event),
153 0,
154 "Packet did not survive interference as expected");
155 interferenceHelper.ClearAllEvents();
156
157 // Spreading factor imperfect orthogonality
158 // Different SFs are orthogonal only up to a point
159 event = interferenceHelper.Add(Seconds(2), 14, 7, nullptr, frequencyHz);
160 interferenceHelper.Add(Seconds(2), 14 + 17, 8, nullptr, frequencyHz);
161 NS_TEST_EXPECT_MSG_EQ(interferenceHelper.IsDestroyedByInterference(event),
162 8,
163 "Packet was not destroyed by interference as expected");
164 interferenceHelper.ClearAllEvents();
165
166 // If a more 'distant' spreading factor is used, isolation gets better
167 event = interferenceHelper.Add(Seconds(2), 14, 7, nullptr, frequencyHz);
168 interferenceHelper.Add(Seconds(2), 14 + 17, 10, nullptr, frequencyHz);
169 NS_TEST_EXPECT_MSG_EQ(interferenceHelper.IsDestroyedByInterference(event),
170 0,
171 "Packet was destroyed by interference while it should have survived");
172 interferenceHelper.ClearAllEvents();
173
174 // Cumulative interference
175 // Same spreading factor interference is cumulative
176 event = interferenceHelper.Add(Seconds(2), 14, 7, nullptr, frequencyHz);
177 interferenceHelper.Add(Seconds(2), 14 + 16, 8, nullptr, frequencyHz);
178 interferenceHelper.Add(Seconds(2), 14 + 16, 8, nullptr, frequencyHz);
179 interferenceHelper.Add(Seconds(2), 14 + 16, 8, nullptr, frequencyHz);
180 NS_TEST_EXPECT_MSG_EQ(interferenceHelper.IsDestroyedByInterference(event),
181 8,
182 "Packet was not destroyed by interference as expected");
183 interferenceHelper.ClearAllEvents();
184
185 // Cumulative interference
186 // Interference is not cumulative between different SFs
187 event = interferenceHelper.Add(Seconds(2), 14, 7, nullptr, frequencyHz);
188 interferenceHelper.Add(Seconds(2), 14 + 16, 8, nullptr, frequencyHz);
189 interferenceHelper.Add(Seconds(2), 14 + 16, 9, nullptr, frequencyHz);
190 interferenceHelper.Add(Seconds(2), 14 + 16, 10, nullptr, frequencyHz);
191 NS_TEST_EXPECT_MSG_EQ(interferenceHelper.IsDestroyedByInterference(event),
192 0,
193 "Packet did not survive interference as expected");
194 interferenceHelper.ClearAllEvents();
195}
196
197/**
198 * @ingroup lorawan
199 *
200 * It tests LoraDeviceAddress comparison operators overrides and generation of new addresses with
201 * LoraDeviceAddressGenerator
202 */
204{
205 public:
206 LorawanAddressTest(); //!< Default constructor
207 ~LorawanAddressTest() override; //!< Destructor
208
209 private:
210 void DoRun() override;
211};
212
213// Add some help text to this case to describe what it is intended to test
215 : TestCase("Verify that LoraDeviceAddress works as expected")
216{
217}
218
219// Reminder that the test case should clean up after itself
223
224// This method is the pure virtual method from class TestCase that every
225// TestCase must implement
226void
228{
229 NS_LOG_DEBUG("LorawanAddressTest");
230
231 //////////////////////////////////////
232 // Test the LoraDeviceAddress class //
233 //////////////////////////////////////
234
235 // Address equality
236 LoraDeviceAddress firstAddress(0xFFFFFFFF);
237 LoraDeviceAddress secondAddress(0xFFFFFFFF);
238 NS_TEST_EXPECT_MSG_EQ((firstAddress == secondAddress), true, "Addresses don't match");
239
240 // Address ordering
241 LoraDeviceAddress bigAddress(0xFFFFFF00);
242 LoraDeviceAddress smallAddress(0xFFF00000);
243 NS_TEST_EXPECT_MSG_EQ((bigAddress > smallAddress),
244 true,
245 "> function for addresses doesn't work correctly");
246
247 // Setting and getting
248 LoraDeviceAddress referenceAddress(0xFFFFFFFF);
249 LoraDeviceAddress address(0x00000000);
250 NS_TEST_EXPECT_MSG_EQ((address != referenceAddress), true, "Different addresses match!");
251 address.SetNwkAddr(0xFFFFFFF);
252 address.SetNwkID(0b1111111);
253 NS_TEST_EXPECT_MSG_EQ((address == referenceAddress),
254 true,
255 "Addresses set to be equal don't match");
256
257 // Serialization and deserialization
258 uint8_t buffer[4];
259 LoraDeviceAddress toSerialize(0x0F0F0F0F);
260 toSerialize.Serialize(buffer);
262 NS_TEST_EXPECT_MSG_EQ((toSerialize == deserialized),
263 true,
264 "Serialization + Deserialization doesn't yield an equal address");
265
266 ///////////////////////////////////
267 // Test the address generator class
268 ///////////////////////////////////
269
270 LoraDeviceAddressGenerator addressGenerator;
271 for (int i = 0; i < 200; i++)
272 {
273 addressGenerator.NextAddress();
274 }
275 // After 200 iterations, the address should be 0xC9
276 NS_TEST_EXPECT_MSG_EQ((addressGenerator.GetNextAddress() == LoraDeviceAddress(0xC9)),
277 true,
278 "LoraDeviceAddressGenerator doesn't increment as expected");
279}
280
281/**
282 * @ingroup lorawan
283 *
284 * It tests serialization/deserialization of LoRaWAN headers (the LorawanMacHeader and
285 * LoraFrameHeader classes) on packets
286 */
287class HeaderTest : public TestCase
288{
289 public:
290 HeaderTest(); //!< Default constructor
291 ~HeaderTest() override; //!< Destructor
292
293 private:
294 void DoRun() override;
295};
296
297// Add some help text to this case to describe what it is intended to test
299 : TestCase("Verify that LorawanMacHeader and LoraFrameHeader work as expected")
300{
301}
302
303// Reminder that the test case should clean up after itself
307
308// This method is the pure virtual method from class TestCase that every
309// TestCase must implement
310void
312{
313 NS_LOG_DEBUG("HeaderTest");
314
315 //////////////////////////////////
316 // Test the LorawanMacHeader class //
317 //////////////////////////////////
318 LorawanMacHeader macHdr;
320 macHdr.SetMajor(1);
321
322 Buffer macBuf;
323 macBuf.AddAtStart(100);
324 Buffer::Iterator macSerialized = macBuf.Begin();
325 macHdr.Serialize(macSerialized);
326
327 macHdr.Deserialize(macSerialized);
328
330 true,
331 "FType changes in the serialization/deserialization process");
332 NS_TEST_EXPECT_MSG_EQ((macHdr.GetMajor() == 1),
333 true,
334 "FType changes in the serialization/deserialization process");
335
336 ////////////////////////////////////
337 // Test the LoraFrameHeader class //
338 ////////////////////////////////////
339 LoraFrameHeader frameHdr;
340 frameHdr.SetAsDownlink();
341 frameHdr.SetAck(true);
342 frameHdr.SetAdr(false);
343 frameHdr.SetFCnt(1);
344 frameHdr.SetAddress(LoraDeviceAddress(56, 1864));
345 frameHdr.AddLinkCheckAns(10, 1);
346
347 // Serialization
348 Buffer buf;
349 buf.AddAtStart(100);
350 Buffer::Iterator serialized = buf.Begin();
351 frameHdr.Serialize(serialized);
352
353 // Deserialization
354 frameHdr.Deserialize(serialized);
355
356 Ptr<LinkCheckAns> command = DynamicCast<LinkCheckAns>(frameHdr.GetCommands().at(0));
357 uint8_t margin = command->GetMargin();
358 uint8_t gwCnt = command->GetGwCnt();
359
360 NS_TEST_EXPECT_MSG_EQ(frameHdr.GetAck(),
361 true,
362 "ACK bit changes in the serialization/deserialization process");
363 NS_TEST_EXPECT_MSG_EQ(frameHdr.GetAdr(),
364 false,
365 "ADR bit changes in the serialization/deserialization process");
367 1,
368 "FCnt changes in the serialization/deserialization process");
369 NS_TEST_EXPECT_MSG_EQ((frameHdr.GetAddress() == LoraDeviceAddress(56, 1864)),
370 true,
371 "Address changes in the serialization/deserialization process");
373 10,
374 "Margin changes in the serialization/deserialization process");
375 NS_TEST_EXPECT_MSG_EQ(gwCnt, 1, "GwCnt changes in the serialization/deserialization process");
376
377 /////////////////////////////////////////////////
378 // Test a combination of the two above classes //
379 /////////////////////////////////////////////////
380 Ptr<Packet> pkt = Create<Packet>(10);
381 pkt->AddHeader(frameHdr);
382 pkt->AddHeader(macHdr);
383
384 // Length = Payload + FrameHeader + MacHeader
385 // = 10 + (8+3) + 1 = 22
386 NS_TEST_EXPECT_MSG_EQ((pkt->GetSize()), 22, "Wrong size of packet + headers");
387
388 LorawanMacHeader macHdr1;
389
390 pkt->RemoveHeader(macHdr1);
391
392 NS_TEST_EXPECT_MSG_EQ((pkt->GetSize()), 21, "Wrong size of packet + headers - macHeader");
393
394 LoraFrameHeader frameHdr1;
395 frameHdr1.SetAsDownlink();
396
397 pkt->RemoveHeader(frameHdr1);
398 Ptr<LinkCheckAns> linkCheckAns = DynamicCast<LinkCheckAns>(frameHdr1.GetCommands().at(0));
399
400 NS_TEST_EXPECT_MSG_EQ((pkt->GetSize()),
401 10,
402 "Wrong size of packet + headers - macHeader - frameHeader");
403
404 // Verify contents of removed MAC header
406 macHdr.GetFType(),
407 "Removed header contents don't match");
409 macHdr.GetMajor(),
410 "Removed header contents don't match");
411
412 // Verify contents of removed frame header
413 NS_TEST_EXPECT_MSG_EQ(frameHdr1.GetAck(),
414 frameHdr.GetAck(),
415 "Removed header contents don't match");
416 NS_TEST_EXPECT_MSG_EQ(frameHdr1.GetAdr(),
417 frameHdr.GetAdr(),
418 "Removed header contents don't match");
419 NS_TEST_EXPECT_MSG_EQ(frameHdr1.GetFCnt(),
420 frameHdr.GetFCnt(),
421 "Removed header contents don't match");
422 NS_TEST_EXPECT_MSG_EQ((frameHdr1.GetAddress() == frameHdr.GetAddress()),
423 true,
424 "Removed header contents don't match");
425 NS_TEST_EXPECT_MSG_EQ(linkCheckAns->GetMargin(),
426 10,
427 "Removed header's MAC command contents don't match");
428 NS_TEST_EXPECT_MSG_EQ(linkCheckAns->GetGwCnt(),
429 1,
430 "Removed header's MAC command contents don't match");
431}
432
433/**
434 * @ingroup lorawan
435 *
436 * It tests a number of cases related to SimpleGatewayLoraPhy's parallel reception paths
437 */
439{
440 public:
441 ReceivePathTest(); //!< Default constructor
442 ~ReceivePathTest() override; //!< Destructor
443
444 private:
445 void DoRun() override;
446 /**
447 * Reset counters and gateway PHY for new sub test case.
448 *
449 * @param rxPathNb Number of reception paths to be created on the gateway PHY
450 */
451 void Reset(uint8_t rxPathNb);
452 /**
453 * Callback for tracing OccupiedReceptionPaths.
454 *
455 * @param oldValue The old value.
456 * @param newValue The new value.
457 */
458 void OccupiedReceptionPaths(int oldValue, int newValue);
459 /**
460 * Callback for tracing LostPacketBecauseNoMoreReceivers.
461 *
462 * @param packet The packet lost.
463 * @param node The receiver node id if any, 0 otherwise.
464 */
466 /**
467 * Callback for tracing LostPacketBecauseInterference.
468 *
469 * @param packet The packet lost.
470 * @param node The receiver node id if any, 0 otherwise.
471 */
472 void Interference(Ptr<const Packet> packet, uint32_t node);
473 /**
474 * Callback for tracing ReceivedPacket.
475 *
476 * @param packet The packet received.
477 * @param node The receiver node id if any, 0 otherwise.
478 */
479 void ReceivedPacket(Ptr<const Packet> packet, uint32_t node);
480
481 Ptr<SimpleGatewayLoraPhy> gatewayPhy; //!< PHY layer of a gateway to be tested
482
483 int m_noMoreDemodulatorsCalls = 0; //!< Counter for LostPacketBecauseNoMoreReceivers calls
484 int m_interferenceCalls = 0; //!< Counter for LostPacketBecauseInterference calls
485 int m_receivedPacketCalls = 0; //!< Counter for ReceivedPacket calls
486 int m_maxOccupiedReceptionPaths = 0; //!< Max number of concurrent OccupiedReceptionPaths
487};
488
489// Add some help text to this case to describe what it is intended to test
491 : TestCase("Verify that ReceivePaths work as expected")
492{
493}
494
495// Reminder that the test case should clean up after itself
499
500void
501ReceivePathTest::Reset(uint8_t rxPathNb)
502{
507
508 // The following tests are designed around GOURSAUD signal-to-interference matrix
510
512
513 gatewayPhy->AddFrequency(868'100'000);
514 gatewayPhy->AddFrequency(868'300'000);
515 gatewayPhy->AddFrequency(868'500'000);
516
517 for (uint8_t i = 0; i < rxPathNb; i++)
518 {
519 gatewayPhy->AddReceptionPath();
520 }
521
522 // From GatewayLoraPhy
523 gatewayPhy->TraceConnectWithoutContext(
524 "LostPacketBecauseNoMoreReceivers",
526 gatewayPhy->TraceConnectWithoutContext(
527 "OccupiedReceptionPaths",
529
530 // From LoraPhy
531 gatewayPhy->TraceConnectWithoutContext("LostPacketBecauseInterference",
533 gatewayPhy->TraceConnectWithoutContext("ReceivedPacket",
535}
536
537void
539{
540 NS_LOG_FUNCTION(oldValue << newValue);
541
542 if (m_maxOccupiedReceptionPaths < newValue)
543 {
545 }
546}
547
548void
555
556void
563
564void
571
572// This method is the pure virtual method from class TestCase that every
573// TestCase must implement
574void
576{
577 NS_LOG_DEBUG("ReceivePathTest");
578
579 Ptr<Packet> packet = Create<Packet>();
580
581 ///////////////////////////////////////////////////////////
582 // If no ReceptionPath is configured, no packet is received
583 ///////////////////////////////////////////////////////////
584
585 Reset(0);
586
590 packet,
591 868'100'000,
593 7,
594 14,
595 Seconds(1));
596
600
601 NS_TEST_EXPECT_MSG_EQ(m_noMoreDemodulatorsCalls, 1, "Unexpected value");
602
603 //////////////////////////////////////////////////////////////////////////////
604 // A ReceptionPath can receive a packet of any SF without any preconfiguration
605 //////////////////////////////////////////////////////////////////////////////
606
607 Reset(1);
608
612 packet,
613 868'100'000,
615 7,
616 14,
617 Seconds(1));
621 packet,
622 868'100'000,
624 8,
625 14,
626 Seconds(1));
630 packet,
631 868'100'000,
633 9,
634 14,
635 Seconds(1));
639 packet,
640 868'100'000,
642 10,
643 14,
644 Seconds(1));
648 packet,
649 868'100'000,
651 11,
652 14,
653 Seconds(1));
657 packet,
658 868'100'000,
660 12,
661 14,
662 Seconds(1));
663
667
668 NS_TEST_EXPECT_MSG_EQ(m_noMoreDemodulatorsCalls, 0, "Unexpected value");
669 NS_TEST_EXPECT_MSG_EQ(m_receivedPacketCalls, 6, "Unexpected value");
670
671 ///////////////////////////////////////////////////////////////////////////////////////
672 // Schedule two overlapping reception events. Each packet should be received correctly.
673 ///////////////////////////////////////////////////////////////////////////////////////
674
675 Reset(2);
676
680 packet,
681 868'100'000,
683 7,
684 14,
685 Seconds(4));
689 packet,
690 868'100'000,
692 9,
693 14,
694 Seconds(4));
695
699
700 NS_TEST_EXPECT_MSG_EQ(m_noMoreDemodulatorsCalls, 0, "Unexpected value");
701 NS_TEST_EXPECT_MSG_EQ(m_receivedPacketCalls, 2, "Unexpected value");
703
704 //////////////////////////////////////////////////////////////////////////////////
705 // Interference between packets on the same frequency and different ReceptionPaths
706 //////////////////////////////////////////////////////////////////////////////////
707
708 Reset(2);
709
713 packet,
714 868'100'000,
716 7,
717 14,
718 Seconds(4));
722 packet,
723 868'100'000,
725 7,
726 14,
727 Seconds(4));
728
732
733 NS_TEST_EXPECT_MSG_EQ(m_noMoreDemodulatorsCalls, 0, "Unexpected value");
734 NS_TEST_EXPECT_MSG_EQ(m_interferenceCalls, 2, "Unexpected value");
735
736 /////////////////////////////////////////////////////////////
737 // Three receptions where only two receivePaths are available
738 /////////////////////////////////////////////////////////////
739
740 Reset(2);
741
745 packet,
746 868'100'000,
748 7,
749 14,
750 Seconds(4));
754 packet,
755 868'100'000,
757 7,
758 14,
759 Seconds(4));
763 packet,
764 868'100'000,
766 7,
767 14,
768 Seconds(4));
769
773
774 NS_TEST_EXPECT_MSG_EQ(m_noMoreDemodulatorsCalls, 1, "Unexpected value");
775
776 ///////////////////////////////////////////////////////////////////////////
777 // Packets that are on different frequencys do not interfere
778 ///////////////////////////////////////////////////////////////////////////
779
780 Reset(2);
781
785 packet,
786 868'100'000,
788 7,
789 14,
790 Seconds(4));
794 packet,
795 868'300'000,
797 7,
798 14,
799 Seconds(4));
800
804
805 NS_TEST_EXPECT_MSG_EQ(m_interferenceCalls, 0, "Unexpected value");
806
807 ///////////////////////////////////////////////////////////////////////////
808 // Full capacity (siw packets, on six SFs, distributed over 3 frequencies)
809 ///////////////////////////////////////////////////////////////////////////
810
811 Reset(6);
812
816 packet,
817 868'100'000,
819 7,
820 14,
821 Seconds(4));
825 packet,
826 868'100'000,
828 8,
829 14,
830 Seconds(4));
834 packet,
835 868'300'000,
837 9,
838 14,
839 Seconds(4));
843 packet,
844 868'300'000,
846 10,
847 14,
848 Seconds(4));
852 packet,
853 868'500'000,
855 11,
856 14,
857 Seconds(4));
861 packet,
862 868'500'000,
864 12,
865 14,
866 Seconds(4));
867
871
872 NS_TEST_EXPECT_MSG_EQ(m_noMoreDemodulatorsCalls, 0, "Unexpected value");
873 NS_TEST_EXPECT_MSG_EQ(m_interferenceCalls, 0, "Unexpected value");
874 NS_TEST_EXPECT_MSG_EQ(m_receivedPacketCalls, 6, "Unexpected value");
875
876 ///////////////////////////////////////////////////////////////////////////
877 // Full capacity + 1
878 ///////////////////////////////////////////////////////////////////////////
879
880 Reset(6);
881
885 packet,
886 868'100'000,
888 7,
889 14,
890 Seconds(4));
894 packet,
895 868'100'000,
897 8,
898 14,
899 Seconds(4));
903 packet,
904 868'300'000,
906 9,
907 14,
908 Seconds(4));
912 packet,
913 868'300'000,
915 10,
916 14,
917 Seconds(4));
921 packet,
922 868'500'000,
924 11,
925 14,
926 Seconds(4));
930 packet,
931 868'500'000,
933 12,
934 14,
935 Seconds(4));
939 packet,
940 868'500'000,
942 10,
943 14,
944 Seconds(4));
945
949
950 NS_TEST_EXPECT_MSG_EQ(m_noMoreDemodulatorsCalls, 1, "Unexpected value");
951 NS_TEST_EXPECT_MSG_EQ(m_interferenceCalls, 0, "Unexpected value");
952 NS_TEST_EXPECT_MSG_EQ(m_receivedPacketCalls, 6, "Unexpected value");
953
954 ////////////////////////////////////
955 // Receive Paths are correctly freed
956 ////////////////////////////////////
957
958 Reset(6);
959
963 packet,
964 868'100'000,
966 7,
967 14,
968 Seconds(4));
972 packet,
973 868'100'000,
975 8,
976 14,
977 Seconds(4));
981 packet,
982 868'300'000,
984 9,
985 14,
986 Seconds(4));
990 packet,
991 868'300'000,
993 10,
994 14,
995 Seconds(4));
999 packet,
1000 868'500'000,
1002 11,
1003 14,
1004 Seconds(4));
1007 gatewayPhy,
1008 packet,
1009 868'500'000,
1011 12,
1012 14,
1013 Seconds(4));
1014
1017 gatewayPhy,
1018 packet,
1019 868'100'000,
1021 7,
1022 14,
1023 Seconds(4));
1026 gatewayPhy,
1027 packet,
1028 868'100'000,
1030 8,
1031 14,
1032 Seconds(4));
1035 gatewayPhy,
1036 packet,
1037 868'300'000,
1039 9,
1040 14,
1041 Seconds(4));
1044 gatewayPhy,
1045 packet,
1046 868'300'000,
1048 10,
1049 14,
1050 Seconds(4));
1053 gatewayPhy,
1054 packet,
1055 868'500'000,
1057 11,
1058 14,
1059 Seconds(4));
1062 gatewayPhy,
1063 packet,
1064 868'500'000,
1066 12,
1067 14,
1068 Seconds(4));
1069
1073
1074 NS_TEST_EXPECT_MSG_EQ(m_noMoreDemodulatorsCalls, 0, "Unexpected value");
1075 NS_TEST_EXPECT_MSG_EQ(m_interferenceCalls, 0, "Unexpected value");
1076 NS_TEST_EXPECT_MSG_EQ(m_receivedPacketCalls, 12, "Unexpected value");
1077
1078 /////////////////////////////////////////////////////////////
1079 // Receive Paths stay occupied exactly for the necessary time
1080 /////////////////////////////////////////////////////////////
1081
1082 Reset(2);
1083
1086 gatewayPhy,
1087 packet,
1088 868'100'000,
1090 7,
1091 14,
1092 Seconds(4));
1095 gatewayPhy,
1096 packet,
1097 868'100'000,
1099 8,
1100 14,
1101 Seconds(4));
1102
1103 // This packet will find no free ReceptionPaths
1106 gatewayPhy,
1107 packet,
1108 868'100'000,
1110 9,
1111 14,
1112 Seconds(4));
1113
1114 // This packet will find a free ReceptionPath
1117 gatewayPhy,
1118 packet,
1119 868'100'000,
1121 10,
1122 14,
1123 Seconds(4));
1124
1128
1129 NS_TEST_EXPECT_MSG_EQ(m_noMoreDemodulatorsCalls, 1, "Unexpected value");
1130 NS_TEST_EXPECT_MSG_EQ(m_interferenceCalls, 0, "Unexpected value");
1131 NS_TEST_EXPECT_MSG_EQ(m_receivedPacketCalls, 3, "Unexpected value");
1132
1133 ////////////////////////////////////////////////////
1134 // Only one ReceivePath locks on the incoming packet
1135 ////////////////////////////////////////////////////
1136
1137 Reset(6);
1138
1141 gatewayPhy,
1142 packet,
1143 868'100'000,
1145 7,
1146 14,
1147 Seconds(4));
1148
1152
1153 NS_TEST_EXPECT_MSG_EQ(m_noMoreDemodulatorsCalls, 0, "Unexpected value");
1154 NS_TEST_EXPECT_MSG_EQ(m_interferenceCalls, 0, "Unexpected value");
1155 NS_TEST_EXPECT_MSG_EQ(m_receivedPacketCalls, 1, "Unexpected value");
1156 NS_TEST_EXPECT_MSG_EQ(m_maxOccupiedReceptionPaths, 1, "Unexpected value");
1157}
1158
1159/**
1160 * @ingroup lorawan
1161 *
1162 * It tests functionality of the LogicalLoraChannel, SubBand and LogicalLoraChannelHelper classes
1163 */
1165{
1166 public:
1167 LogicalLoraChannelTest(); //!< Default constructor
1168 ~LogicalLoraChannelTest() override; //!< Destructor
1169
1170 private:
1171 void DoRun() override;
1172};
1173
1174// Add some help text to this case to describe what it is intended to test
1176 : TestCase("Verify that LogicalLoraChannel and LogicalLoraChannelHelper work as expected")
1177{
1178}
1179
1180// Reminder that the test case should clean up after itself
1184
1185// This method is the pure virtual method from class TestCase that every
1186// TestCase must implement
1187void
1189{
1190 NS_LOG_DEBUG("LogicalLoraChannelTest");
1191
1192 /////////////////////////////
1193 // Test LogicalLoraChannel //
1194 /////////////////////////////
1195
1196 // Setup
1197 Ptr<LogicalLoraChannel> channel1 = Create<LogicalLoraChannel>(868000000, 0, 5);
1198 Ptr<LogicalLoraChannel> channel2 = Create<LogicalLoraChannel>(868000000, 0, 5);
1199 Ptr<LogicalLoraChannel> channel3 = Create<LogicalLoraChannel>(868100000, 0, 5);
1200 Ptr<LogicalLoraChannel> channel4 = Create<LogicalLoraChannel>(868001000, 0, 5);
1201
1202 // Equality between channels
1203 // Test the == and != operators
1204 NS_TEST_EXPECT_MSG_EQ(channel1, channel2, "== operator doesn't work as expected");
1205 NS_TEST_EXPECT_MSG_NE(channel1, channel3, "!= operator doesn't work as expected");
1206 NS_TEST_EXPECT_MSG_NE(channel1, channel4, "!= operator doesn't work as expected");
1207
1208 //////////////////
1209 // Test SubBand //
1210 //////////////////
1211 // Setup
1212
1213 auto subBand = Create<SubBand>(868000000, 868600000, 0.01, 14);
1214 Ptr<LogicalLoraChannel> channel5 = Create<LogicalLoraChannel>(870000000, 0, 5);
1215
1216 // Test Contains
1217 NS_TEST_EXPECT_MSG_EQ(subBand->Contains(channel3),
1218 true,
1219 "Contains does not behave as expected");
1220 NS_TEST_EXPECT_MSG_EQ(subBand->Contains(channel3->GetFrequency()),
1221 true,
1222 "Contains does not behave as expected");
1223 NS_TEST_EXPECT_MSG_EQ(subBand->Contains(channel5),
1224 false,
1225 "Contains does not behave as expected");
1226
1227 ///////////////////////////////////
1228 // Test LogicalLoraChannelHelper //
1229 ///////////////////////////////////
1230
1231 // Setup
1232 auto channelHelper = Create<LogicalLoraChannelHelper>(16);
1233 auto subBand1 = Create<SubBand>(869400000, 869650000, 0.10, 27);
1234 channel1 = Create<LogicalLoraChannel>(868100000, 0, 5);
1235 channel2 = Create<LogicalLoraChannel>(868300000, 0, 5);
1236 channel3 = Create<LogicalLoraChannel>(869525000, 0, 5);
1237
1238 // Channel diagram
1239 //
1240 // Channels 1 2 3
1241 // SubBands 868 ----- 1% ----- 868.6 869 ----- 10% ----- 869.4
1242
1243 // Add SubBands and LogicalLoraChannels to the helper
1244 channelHelper->AddSubBand(subBand);
1245 channelHelper->AddSubBand(subBand1);
1246 channelHelper->SetChannel(0, channel1);
1247 channelHelper->SetChannel(1, channel2);
1248 channelHelper->SetChannel(2, channel3);
1249
1250 // Duty Cycle tests
1251 // (high level duty cycle behavior)
1252 ///////////////////////////////////
1253
1254 channelHelper->AddEvent(Seconds(2), channel1);
1255 Time expectedTimeOff = Seconds(2 / 0.01);
1256
1257 // Wait time is computed correctly
1258 NS_TEST_EXPECT_MSG_EQ(channelHelper->GetWaitTime(channel1),
1259 expectedTimeOff,
1260 "Wait time doesn't behave as expected");
1261
1262 // Duty Cycle involves the whole SubBand, not just a channel
1263 NS_TEST_EXPECT_MSG_EQ(channelHelper->GetWaitTime(channel2),
1264 expectedTimeOff,
1265 "Wait time doesn't behave as expected");
1266
1267 // Other bands are not affected by this transmission
1268 NS_TEST_EXPECT_MSG_EQ(channelHelper->GetWaitTime(channel3),
1269 Time(0),
1270 "Wait time affects other subbands");
1271}
1272
1273/**
1274 * @ingroup lorawan
1275 *
1276 * It tests the correctness of the LoraPhy::GetTimeOnAir calculator against a number of pre-sourced
1277 * time values of known scenarios
1278 */
1280{
1281 public:
1282 TimeOnAirTest(); //!< Default constructor
1283 ~TimeOnAirTest() override; //!< Destructor
1284
1285 private:
1286 void DoRun() override;
1287};
1288
1289// Add some help text to this case to describe what it is intended to test
1291 : TestCase(
1292 "Verify that LoraPhy's function to compute the time on air of a packet works as expected")
1293{
1294}
1295
1296// Reminder that the test case should clean up after itself
1300
1301// This method is the pure virtual method from class TestCase that every
1302// TestCase must implement
1303void
1305{
1306 NS_LOG_DEBUG("TimeOnAirTest");
1307
1308 Ptr<Packet> packet;
1309 Time duration;
1310
1311 // Starting parameters
1312 packet = Create<Packet>(10);
1313 LoraTxParameters txParams;
1314 txParams.spreadingFactor = 7;
1315 txParams.bandwidthHz = 125'000;
1316 txParams.codingRate = CodingRate::CR_4_5;
1317 txParams.lowDataRateOptimize = false;
1318 txParams.preambleLenSymb = 8;
1319 txParams.implicitHeader = false;
1320 txParams.crcEnabled = true;
1321
1322 duration = LoraPhy::GetTimeOnAir(packet->GetSize(), txParams);
1323 NS_TEST_EXPECT_MSG_EQ_TOL(duration.GetSeconds(), 0.041216, 0.0001, "Unexpected duration");
1324
1325 txParams.spreadingFactor = 8;
1326 duration = LoraPhy::GetTimeOnAir(packet->GetSize(), txParams);
1327 NS_TEST_EXPECT_MSG_EQ_TOL(duration.GetSeconds(), 0.072192, 0.0001, "Unexpected duration");
1328
1329 txParams.implicitHeader = true;
1330 duration = LoraPhy::GetTimeOnAir(packet->GetSize(), txParams);
1331 NS_TEST_EXPECT_MSG_EQ_TOL(duration.GetSeconds(), 0.072192, 0.0001, "Unexpected duration");
1332
1333 txParams.codingRate = CodingRate::CR_4_6;
1334 duration = LoraPhy::GetTimeOnAir(packet->GetSize(), txParams);
1335 NS_TEST_EXPECT_MSG_EQ_TOL(duration.GetSeconds(), 0.078336, 0.0001, "Unexpected duration");
1336
1337 txParams.preambleLenSymb = 10;
1338 duration = LoraPhy::GetTimeOnAir(packet->GetSize(), txParams);
1339 NS_TEST_EXPECT_MSG_EQ_TOL(duration.GetSeconds(), 0.082432, 0.0001, "Unexpected duration");
1340
1341 txParams.lowDataRateOptimize = true;
1342 duration = LoraPhy::GetTimeOnAir(packet->GetSize(), txParams);
1343 NS_TEST_EXPECT_MSG_EQ_TOL(duration.GetSeconds(), 0.082432, 0.0001, "Unexpected duration");
1344
1345 txParams.spreadingFactor = 10;
1346 duration = LoraPhy::GetTimeOnAir(packet->GetSize(), txParams);
1347 NS_TEST_EXPECT_MSG_EQ_TOL(duration.GetSeconds(), 0.280576, 0.0001, "Unexpected duration");
1348
1349 txParams.bandwidthHz = 250000;
1350 duration = LoraPhy::GetTimeOnAir(packet->GetSize(), txParams);
1351 NS_TEST_EXPECT_MSG_EQ_TOL(duration.GetSeconds(), 0.14028, 0.0001, "Unexpected duration");
1352
1353 txParams.bandwidthHz = 500000;
1354 duration = LoraPhy::GetTimeOnAir(packet->GetSize(), txParams);
1355 NS_TEST_EXPECT_MSG_EQ_TOL(duration.GetSeconds(), 0.070144, 0.0001, "Unexpected duration");
1356
1357 txParams.implicitHeader = false;
1358 duration = LoraPhy::GetTimeOnAir(packet->GetSize(), txParams);
1359 NS_TEST_EXPECT_MSG_EQ_TOL(duration.GetSeconds(), 0.082432, 0.0001, "Unexpected duration");
1360
1361 txParams.preambleLenSymb = 8;
1362 duration = LoraPhy::GetTimeOnAir(packet->GetSize(), txParams);
1363 NS_TEST_EXPECT_MSG_EQ_TOL(duration.GetSeconds(), 0.078336, 0.0001, "Unexpected duration");
1364
1365 txParams.spreadingFactor = 12;
1366 duration = LoraPhy::GetTimeOnAir(packet->GetSize(), txParams);
1367 NS_TEST_EXPECT_MSG_EQ_TOL(duration.GetSeconds(), 0.264192, 0.0001, "Unexpected duration");
1368
1369 packet = Create<Packet>(50);
1370 duration = LoraPhy::GetTimeOnAir(packet->GetSize(), txParams);
1371 NS_TEST_EXPECT_MSG_EQ_TOL(duration.GetSeconds(), 0.657408, 0.0001, "Unexpected duration");
1372
1373 txParams.bandwidthHz = 125000;
1374 duration = LoraPhy::GetTimeOnAir(packet->GetSize(), txParams);
1375 NS_TEST_EXPECT_MSG_EQ_TOL(duration.GetSeconds(), 2.629632, 0.0001, "Unexpected duration");
1376
1377 txParams.codingRate = CodingRate::CR_4_5;
1378 duration = LoraPhy::GetTimeOnAir(packet->GetSize(), txParams);
1379 NS_TEST_EXPECT_MSG_EQ_TOL(duration.GetSeconds(), 2.301952, 0.0001, "Unexpected duration");
1380}
1381
1382/**
1383 * @ingroup lorawan
1384 *
1385 * It tests sending packets over a LoRa physical channel between multiple devices and the resulting
1386 * possible outcomes
1387 */
1389{
1390 public:
1391 PhyConnectivityTest(); //!< Default constructor
1392 ~PhyConnectivityTest() override; //!< Destructor
1393
1394 /**
1395 * Reset counters and end devices' PHYs for new sub test case.
1396 */
1397 void Reset();
1398
1399 /**
1400 * Callback for tracing ReceivedPacket.
1401 *
1402 * @param packet The packet received.
1403 * @param node The receiver node id if any, 0 otherwise.
1404 */
1405 void ReceivedPacket(Ptr<const Packet> packet, uint32_t node);
1406
1407 /**
1408 * Callback for tracing LostPacketBecauseUnderSensitivity.
1409 *
1410 * @param packet The packet lost.
1411 * @param node The receiver node id if any, 0 otherwise.
1412 */
1413 void UnderSensitivity(Ptr<const Packet> packet, uint32_t node);
1414
1415 /**
1416 * Callback for tracing LostPacketBecauseInterference.
1417 *
1418 * @param packet The packet lost.
1419 * @param node The receiver node id if any, 0 otherwise.
1420 */
1421 void Interference(Ptr<const Packet> packet, uint32_t node);
1422
1423 /**
1424 * Callback for tracing LostPacketBecauseWrongFrequency.
1425 *
1426 * @param packet The packet lost.
1427 * @param node The receiver node id if any, 0 otherwise.
1428 */
1429 void WrongFrequency(Ptr<const Packet> packet, uint32_t node);
1430
1431 /**
1432 * Callback for tracing LostPacketBecauseWrongSpreadingFactor.
1433 *
1434 * @param packet The packet lost.
1435 * @param node The receiver node id if any, 0 otherwise.
1436 */
1437 void WrongSf(Ptr<const Packet> packet, uint32_t node);
1438
1439 /**
1440 * Compare two packets to check if they are equal.
1441 *
1442 * @param packet1 A first packet.
1443 * @param packet2 A second packet.
1444 * @return True if their unique identifiers are equal,
1445 * @return false otherwise.
1446 */
1447 bool IsSamePacket(Ptr<Packet> packet1, Ptr<Packet> packet2);
1448
1449 private:
1450 void DoRun() override;
1451
1452 Ptr<LoraChannel> channel; //!< The LoRa channel used for tests
1453 Ptr<SimpleEndDeviceLoraPhy> edPhy1; //!< The first end device's PHY layer used in tests
1454 Ptr<SimpleEndDeviceLoraPhy> edPhy2; //!< The second end device's PHY layer used in tests
1455 Ptr<SimpleEndDeviceLoraPhy> edPhy3; //!< The third end device's PHY layer used in tests
1456
1457 Ptr<Packet> m_latestReceivedPacket; //!< Pointer to track the last received packet
1458 int m_receivedPacketCalls = 0; //!< Counter for ReceivedPacket calls
1459 int m_underSensitivityCalls = 0; //!< Counter for LostPacketBecauseUnderSensitivity calls
1460 int m_interferenceCalls = 0; //!< Counter for LostPacketBecauseInterference calls
1461 int m_wrongSfCalls = 0; //!< Counter for LostPacketBecauseWrongSpreadingFactor calls
1462 int m_wrongFrequencyCalls = 0; //!< Counter for LostPacketBecauseWrongFrequency calls
1463};
1464
1465// Add some help text to this case to describe what it is intended to test
1467 : TestCase("Verify that PhyConnectivity works as expected")
1468{
1469}
1470
1471// Reminder that the test case should clean up after itself
1475
1476void
1478{
1479 NS_LOG_FUNCTION(packet << node);
1480
1482
1483 m_latestReceivedPacket = packet->Copy();
1484}
1485
1486void
1493
1494void
1496{
1497 NS_LOG_FUNCTION(packet << node);
1498
1500}
1501
1502void
1504{
1505 NS_LOG_FUNCTION(packet << node);
1506
1508}
1509
1510void
1517
1518bool
1520{
1521 return packet1->GetUid() == packet2->GetUid();
1522}
1523
1524void
1526{
1530 m_wrongSfCalls = 0;
1532
1534 loss->SetPathLossExponent(3.76);
1535 loss->SetReference(1, 7.7);
1536
1538
1539 // Create the channel
1540 channel = CreateObject<LoraChannel>(loss, delay);
1541
1542 // Connect PHYs
1546
1550
1551 mob1->SetPosition(Vector(0.0, 0.0, 0.0));
1552 mob2->SetPosition(Vector(10.0, 0.0, 0.0));
1553 mob3->SetPosition(Vector(20.0, 0.0, 0.0));
1554
1555 edPhy1->SetMobility(mob1);
1556 edPhy2->SetMobility(mob2);
1557 edPhy3->SetMobility(mob3);
1558
1559 channel->Add(edPhy1);
1560 channel->Add(edPhy2);
1561 channel->Add(edPhy3);
1562
1563 edPhy1->SetChannel(channel);
1564 edPhy2->SetChannel(channel);
1565 edPhy3->SetChannel(channel);
1566
1567 edPhy1->TraceConnectWithoutContext("ReceivedPacket",
1569 edPhy2->TraceConnectWithoutContext("ReceivedPacket",
1571 edPhy3->TraceConnectWithoutContext("ReceivedPacket",
1573
1574 edPhy1->TraceConnectWithoutContext("LostPacketBecauseUnderSensitivity",
1576 edPhy2->TraceConnectWithoutContext("LostPacketBecauseUnderSensitivity",
1578 edPhy3->TraceConnectWithoutContext("LostPacketBecauseUnderSensitivity",
1580
1581 edPhy1->TraceConnectWithoutContext("LostPacketBecauseInterference",
1583 edPhy2->TraceConnectWithoutContext("LostPacketBecauseInterference",
1585 edPhy3->TraceConnectWithoutContext("LostPacketBecauseInterference",
1587
1588 edPhy1->TraceConnectWithoutContext("LostPacketBecauseWrongFrequency",
1590 edPhy2->TraceConnectWithoutContext("LostPacketBecauseWrongFrequency",
1592 edPhy3->TraceConnectWithoutContext("LostPacketBecauseWrongFrequency",
1594
1595 edPhy1->TraceConnectWithoutContext("LostPacketBecauseWrongSpreadingFactor",
1597 edPhy2->TraceConnectWithoutContext("LostPacketBecauseWrongSpreadingFactor",
1599 edPhy3->TraceConnectWithoutContext("LostPacketBecauseWrongSpreadingFactor",
1601}
1602
1603// This method is the pure virtual method from class TestCase that every
1604// TestCase must implement
1605void
1607{
1608 NS_LOG_DEBUG("PhyConnectivityTest");
1609
1610 // Setup
1611 ////////
1612
1613 uint8_t buffer[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
1614
1615 LoraTxParameters txParams;
1616 txParams.spreadingFactor = 12;
1617 txParams.bandwidthHz = 125'000;
1618 txParams.codingRate = CodingRate::CR_4_5;
1619 txParams.lowDataRateOptimize = true;
1620 txParams.preambleLenSymb = 8;
1621 txParams.implicitHeader = false;
1622 txParams.crcEnabled = true;
1623
1624 Reset();
1625
1626 // Testing
1627 //////////
1628
1629 // Basic packet delivery test
1630 /////////////////////////////
1631
1634 edPhy1,
1635 868'100'000,
1637 txParams.spreadingFactor,
1638 txParams.bandwidthHz,
1639 8,
1641
1644 edPhy2,
1645 868'100'000,
1647 txParams.spreadingFactor,
1648 txParams.bandwidthHz,
1649 8,
1651
1654 edPhy3,
1655 Create<Packet>(buffer, 10),
1656 868'100'000,
1658 txParams,
1659 14);
1660
1664
1667 2,
1668 "Channel skipped some PHYs when delivering a packet"); // All PHYs except the sender
1669
1670 Reset();
1671
1672 // Sleeping PHYs do not receive the packet
1673
1674 edPhy1->SetSleepMode();
1675
1678 edPhy2,
1679 868'100'000,
1681 txParams.spreadingFactor,
1682 txParams.bandwidthHz,
1683 8,
1685
1688 edPhy3,
1689 Create<Packet>(buffer, 10),
1690 868'100'000,
1692 txParams,
1693 14);
1694
1698
1701 1,
1702 "Packet was received by a PHY in SLEEP mode"); // All PHYs in Rx except the sender
1703
1704 Reset();
1705
1706 // Packet that arrives under sensitivity is received correctly if the spreading factor increases
1707
1708 txParams.spreadingFactor = 7;
1709
1711 ->SetPosition(Vector(2990, 0, 0));
1712
1715 edPhy1,
1716 868'100'000,
1718 txParams.spreadingFactor,
1719 txParams.bandwidthHz,
1720 8,
1722
1725 edPhy2,
1726 Create<Packet>(buffer, 10),
1727 868'100'000,
1729 txParams,
1730 14);
1731
1735
1738 1,
1739 "Packet that should have been lost because of low receive power was received");
1740
1741 Reset();
1742
1743 // Try again using a packet with higher spreading factor
1744 txParams.spreadingFactor = 8;
1745
1747 ->SetPosition(Vector(2990, 0, 0));
1748
1751 edPhy1,
1752 868'100'000,
1754 txParams.spreadingFactor,
1755 txParams.bandwidthHz,
1756 8,
1758
1761 edPhy2,
1762 Create<Packet>(buffer, 10),
1763 868'100'000,
1765 txParams,
1766 14);
1767
1771
1773 0,
1774 "Packets that should have arrived above sensitivity were under it");
1775
1776 Reset();
1777
1778 // Packets can be destroyed by interference
1779
1780 txParams.spreadingFactor = 12;
1781
1784 edPhy2,
1785 868'100'000,
1787 txParams.spreadingFactor,
1788 txParams.bandwidthHz,
1789 8,
1791
1794 edPhy1,
1795 Create<Packet>(buffer, 10),
1796 868'100'000,
1798 txParams,
1799 14);
1800
1803 edPhy3,
1804 Create<Packet>(buffer, 10),
1805 868'100'000,
1807 txParams,
1808 14);
1809
1813
1815 1,
1816 "Packets that should be destroyed by interference weren't");
1817
1818 Reset();
1819
1820 // Packets can be lost because the PHY is not listening on the right frequency
1821
1824 edPhy1,
1825 868'100'000,
1827 txParams.spreadingFactor,
1828 txParams.bandwidthHz,
1829 8,
1831
1834 edPhy2,
1835 Create<Packet>(buffer, 10),
1836 868'300'000,
1838 txParams,
1839 14);
1840
1844
1846 1,
1847 "Packets were received even though PHY was on a different frequency");
1848
1849 Reset();
1850
1851 // Packets can be lost because the PHY is not listening for the right spreading factor
1852
1853 txParams.spreadingFactor = 8; // Send with 8, listening for 12
1854
1857 edPhy1,
1858 868'100'000,
1860 12,
1861 txParams.bandwidthHz,
1862 8,
1864
1867 edPhy2,
1868 Create<Packet>(buffer, 10),
1869 868'100'000,
1871 txParams,
1872 14);
1873
1877
1880 1,
1881 "Packets were received even though PHY was listening for a different spreading factor.");
1882
1883 Reset();
1884
1885 // Sending of packets
1886 /////////////////////
1887
1888 // The very same packet arrives at the other PHY
1889
1890 auto packet = Create<Packet>(buffer, 10);
1891
1894 edPhy1,
1895 868'100'000,
1897 txParams.spreadingFactor,
1898 txParams.bandwidthHz,
1899 8,
1901
1904 edPhy2,
1905 packet,
1906 868'100'000,
1908 txParams,
1909 14);
1910
1914
1916 true,
1917 "Packet changed contents when going through the channel");
1918
1919 Reset();
1920
1921 // Correct state transitions
1922 ////////////////////////////
1923
1924 // PHY switches to STANDBY after TX and RX
1925
1928 edPhy1,
1929 868'100'000,
1931 txParams.spreadingFactor,
1932 txParams.bandwidthHz,
1933 8,
1935
1938 edPhy2,
1939 Create<Packet>(buffer, 10),
1940 868'100'000,
1942 txParams,
1943 14);
1944
1948
1949 NS_TEST_EXPECT_MSG_EQ(edPhy1->GetState(),
1951 "State didn't switch to STANDBY as expected");
1952 NS_TEST_EXPECT_MSG_EQ(edPhy2->GetState(),
1954 "State didn't switch to STANDBY as expected");
1955}
1956
1957/**
1958 * @ingroup lorawan
1959 *
1960 * It tests the functionalities of the MAC layer of LoRaWAN devices
1961 *
1962 * @todo Not implemented yet.
1963 */
1965{
1966 public:
1967 LorawanMacTest(); //!< Default constructor
1968 ~LorawanMacTest() override; //!< Destructor
1969
1970 private:
1971 void DoRun() override;
1972};
1973
1974// Add some help text to this case to describe what it is intended to test
1976 : TestCase("Verify that the MAC layer of end devices behaves as expected")
1977{
1978}
1979
1980// Reminder that the test case should clean up after itself
1984
1985// This method is the pure virtual method from class TestCase that every
1986// TestCase must implement
1987void
1989{
1990 NS_LOG_DEBUG("LorawanMacTest");
1991}
1992
1993/**
1994 * @ingroup lorawan
1995 *
1996 * It tests the functionalities of LoRaWAN MAC commands received by devices.
1997 *
1998 * This means testing that (i) settings in the downlink MAC commands are correctly applied/rejected
1999 * by the device, and that (ii) the correct answer (if expected) is produced by the device.
2000 */
2002{
2003 public:
2004 MacCommandTest(); //!< Default constructor
2005 ~MacCommandTest() override; //!< Destructor
2006
2007 private:
2008 /**
2009 * Have this class' MAC layer receive a downlink packet carrying the input MAC command. After,
2010 * trigger a new empty uplink packet send that can then be used to examine the MAC command
2011 * answers in the header.
2012 *
2013 * @tparam T \explicit The type of MAC command to create.
2014 * @tparam Ts \deduced Types of the constructor arguments.
2015 * @param [in] args MAC command constructor arguments.
2016 * @return The list of MAC commands produced by the device as an answer.
2017 */
2018 template <typename T, typename... Ts>
2019 std::vector<Ptr<MacCommand>> RunMacCommand(Ts&&... args);
2020
2021 /**
2022 * This function resets the state of the MAC layer used for tests. Use it before each call of
2023 * RunMacCommand. Otherwise, on consecutive calls the MAC layer will not send due to duty-cycle
2024 * limitations.
2025 */
2026 void Reset();
2027
2028 void DoRun() override;
2029
2030 Ptr<ClassAEndDeviceLorawanMac> m_mac; //!< The end device's MAC layer used in tests.
2031};
2032
2034 : TestCase("Test functionality of MAC commands when received by a device")
2035{
2036}
2037
2039{
2040 m_mac = nullptr;
2041}
2042
2043template <typename T, typename... Ts>
2044std::vector<Ptr<MacCommand>>
2046{
2047 Ptr<Packet> pkt;
2048 LoraFrameHeader fhdr;
2049 LorawanMacHeader mhdr;
2050 // Prepare DL packet with input command
2051 pkt = Create<Packet>(0);
2052 fhdr.SetAsDownlink();
2053 auto cmd = Create<T>(args...);
2054 fhdr.AddCommand(cmd);
2055 pkt->AddHeader(fhdr);
2057 pkt->AddHeader(mhdr);
2058 pkt->AddPaddingAtEnd(4); // MIC
2059 // Trigger MAC layer reception
2060 DynamicCast<LorawanMac>(m_mac)->Receive(pkt);
2061 // Trigger MAC layer send
2062 pkt = Create<Packet>(0);
2063 m_mac->Send(pkt);
2064 // Retrieve uplink MAC commands
2065 pkt->RemoveHeader(mhdr);
2066 fhdr.SetAsUplink();
2067 pkt->RemoveHeader(fhdr);
2068 return fhdr.GetCommands();
2069}
2070
2071void
2073{
2074 // Reset MAC state
2075 LorawanMacHelper macHelper;
2078 /// @todo Create should not require a node in input.
2079 m_mac = DynamicCast<ClassAEndDeviceLorawanMac>(macHelper.Install(nullptr, nullptr));
2080 NS_TEST_EXPECT_MSG_NE(m_mac, nullptr, "Failed to initialize MAC layer object.");
2082 phy->SetChannel(CreateObject<LoraChannel>());
2084 m_mac->SetPhy(phy);
2085}
2086
2087void
2089{
2090 NS_LOG_DEBUG("MacCommandTest");
2091
2092 Reset();
2093 // LinkCheckAns: get connectivity metrics of last uplink LinkCheckReq command
2094 {
2095 uint8_t margin = 20; // best reception margin [dB] from demodulation floor
2096 uint8_t gwCnt = 3; // number of gateways that received last uplink
2097 auto answers = RunMacCommand<LinkCheckAns>(margin, gwCnt);
2098 NS_TEST_EXPECT_MSG_EQ(unsigned(m_mac->GetLastKnownLinkMarginDb()),
2099 unsigned(margin),
2100 "m_lastKnownMarginDb differs from Margin field of LinkCheckAns");
2101 NS_TEST_EXPECT_MSG_EQ(unsigned(m_mac->GetLastKnownGatewayCount()),
2102 unsigned(gwCnt),
2103 "m_lastKnownGatewayCount differs GwCnt field of LinkCheckAns");
2104 NS_TEST_EXPECT_MSG_EQ(answers.size(),
2105 0,
2106 "Unexpected uplink MAC command answer(s) to LinkCheckAns");
2107 }
2108
2109 Reset();
2110 // LinkAdrReq: change data rate, TX power, redundancy, or channel mask
2111 {
2112 uint8_t dataRate = 5;
2113 uint8_t txPower = 2;
2114 uint16_t chMask = 0b101;
2115 uint8_t chMaskCntl = 0;
2116 uint8_t nbTrans = 13;
2117 auto answers = RunMacCommand<LinkAdrReq>(dataRate, txPower, chMask, chMaskCntl, nbTrans);
2118 NS_TEST_EXPECT_MSG_EQ(unsigned(m_mac->GetDataRate()),
2119 unsigned(dataRate),
2120 "m_dataRate does not match DataRate field of LinkAdrReq");
2121 NS_TEST_EXPECT_MSG_EQ(m_mac->GetTransmissionPowerDbm(),
2122 14 - txPower * 2,
2123 "m_txPowerDbm does not match txPower field of LinkAdrReq");
2124 NS_TEST_EXPECT_MSG_EQ(unsigned(m_mac->GetMaxNumberOfTransmissions()),
2125 unsigned(nbTrans),
2126 "m_nbTrans does not match nbTrans field of LinkAdrReq");
2127 auto channels = m_mac->GetLogicalLoraChannelHelper()->GetRawChannelArray();
2128 for (size_t i = 0; i < channels.size(); i++)
2129 {
2130 const auto& c = channels.at(i + 16 * chMaskCntl);
2131 bool actual = (c) ? c->IsEnabledForUplink() : false;
2132 bool expected = (chMask & 0b1 << i);
2133 NS_TEST_EXPECT_MSG_EQ(actual, expected, "Channel " << i << " state != chMask");
2134 }
2135 NS_TEST_ASSERT_MSG_EQ(answers.size(), 1, "1 answer cmd was expected, found 0 or >1");
2136 auto laa = DynamicCast<LinkAdrAns>(answers.at(0));
2137 NS_TEST_ASSERT_MSG_NE(laa, nullptr, "LinkAdrAns was expected, cmd type cast failed");
2138 NS_TEST_EXPECT_MSG_EQ(laa->GetChannelMaskAck(), true, "ChannelMaskAck expected to be true");
2139 NS_TEST_EXPECT_MSG_EQ(laa->GetDataRateAck(), true, "DataRateAck expected to be true");
2140 NS_TEST_EXPECT_MSG_EQ(laa->GetPowerAck(), true, "PowerAck expected to be true");
2141 }
2142
2143 Reset();
2144 // LinkAdrReq: ADR bit off, only change channel mask
2145 {
2146 uint8_t dataRate = 5;
2147 uint8_t txPower = 2;
2148 uint16_t chMask = 0b010;
2149 uint8_t chMaskCntl = 0;
2150 uint8_t nbTrans = 13;
2151 m_mac->SetUplinkAdrBit(false);
2152 auto answers = RunMacCommand<LinkAdrReq>(dataRate, txPower, chMask, chMaskCntl, nbTrans);
2153 NS_TEST_EXPECT_MSG_NE(unsigned(m_mac->GetDataRate()),
2154 unsigned(dataRate),
2155 "m_dataRate expected to differ from DataRate field of LinkAdrReq");
2156 NS_TEST_EXPECT_MSG_NE(m_mac->GetTransmissionPowerDbm(),
2157 14 - txPower * 2,
2158 "m_txPowerDbm expected to not match txPower field of LinkAdrReq");
2159 NS_TEST_EXPECT_MSG_NE(unsigned(m_mac->GetMaxNumberOfTransmissions()),
2160 unsigned(nbTrans),
2161 "m_nbTrans expected to differ from nbTrans field of LinkAdrReq");
2162 auto channels = m_mac->GetLogicalLoraChannelHelper()->GetRawChannelArray();
2163 for (size_t i = 0; i < channels.size(); i++)
2164 {
2165 const auto& c = channels.at(i + 16 * chMaskCntl);
2166 bool actual = (c) ? c->IsEnabledForUplink() : false;
2167 bool expected = (chMask & 0b1 << i);
2168 NS_TEST_EXPECT_MSG_EQ(actual, expected, "Channel " << i << " state != chMask");
2169 }
2170 NS_TEST_ASSERT_MSG_EQ(answers.size(), 1, "1 answer cmd was expected, found 0 or >1");
2171 auto laa = DynamicCast<LinkAdrAns>(answers.at(0));
2172 NS_TEST_ASSERT_MSG_NE(laa, nullptr, "LinkAdrAns was expected, cmd type cast failed");
2173 NS_TEST_EXPECT_MSG_EQ(laa->GetChannelMaskAck(), true, "ChannelMaskAck expected to be true");
2174 NS_TEST_EXPECT_MSG_EQ(laa->GetDataRateAck(), false, "DataRateAck expected to be false");
2175 NS_TEST_EXPECT_MSG_EQ(laa->GetPowerAck(), false, "PowerAck expected to be false");
2176 }
2177
2178 Reset();
2179 // LinkAdrReq: invalid chMask, data rate and power
2180 { // WARNING: default values are manually set here
2181 uint8_t dataRate = 12;
2182 uint8_t txPower = 8;
2183 uint16_t chMask = 0b0;
2184 uint8_t chMaskCntl = 0;
2185 uint8_t nbTrans = 6;
2186 auto answers = RunMacCommand<LinkAdrReq>(dataRate, txPower, chMask, chMaskCntl, nbTrans);
2187 NS_TEST_EXPECT_MSG_EQ(unsigned(m_mac->GetDataRate()),
2188 0,
2189 "m_dataRate expected to be default value");
2190 NS_TEST_EXPECT_MSG_EQ(m_mac->GetTransmissionPowerDbm(),
2191 14,
2192 "m_txPowerDbm expected to be default value");
2193 NS_TEST_EXPECT_MSG_EQ(unsigned(m_mac->GetMaxNumberOfTransmissions()),
2194 1,
2195 "m_nbTrans expected to be default value");
2196 auto channels = m_mac->GetLogicalLoraChannelHelper()->GetRawChannelArray();
2197 for (size_t i = 0; i < channels.size(); i++)
2198 {
2199 const auto& c = channels.at(i + 16 * chMaskCntl);
2200 bool actual = (c) ? c->IsEnabledForUplink() : false;
2201 bool expected = (uint16_t(0b111) & 0b1 << i);
2202 NS_TEST_EXPECT_MSG_EQ(actual, expected, "Channel " << i << " state != default");
2203 }
2204 NS_TEST_ASSERT_MSG_EQ(answers.size(), 1, "1 answer cmd was expected, found 0 or >1");
2205 auto laa = DynamicCast<LinkAdrAns>(answers.at(0));
2206 NS_TEST_ASSERT_MSG_NE(laa, nullptr, "LinkAdrAns was expected, cmd type cast failed");
2207 NS_TEST_EXPECT_MSG_EQ(laa->GetChannelMaskAck(), false, "ChannelMaskAck != false");
2208 NS_TEST_EXPECT_MSG_EQ(laa->GetDataRateAck(), false, "DataRateAck expected to be false");
2209 NS_TEST_EXPECT_MSG_EQ(laa->GetPowerAck(), false, "PowerAck expected to be false");
2210 }
2211
2212 Reset();
2213 // LinkAdrReq: invalid chMask, valid data rate and power
2214 { // WARNING: default values are manually set here
2215 uint8_t dataRate = 1;
2216 uint8_t txPower = 7;
2217 uint16_t chMask = 0b1000; // enable only non-exisitng channel
2218 uint8_t chMaskCntl = 0;
2219 uint8_t nbTrans = 3;
2220 auto answers = RunMacCommand<LinkAdrReq>(dataRate, txPower, chMask, chMaskCntl, nbTrans);
2221 NS_TEST_EXPECT_MSG_EQ(unsigned(m_mac->GetDataRate()),
2222 0,
2223 "m_dataRate expected to be default value");
2224 NS_TEST_EXPECT_MSG_EQ(m_mac->GetTransmissionPowerDbm(),
2225 14,
2226 "m_txPowerDbm expected to be default value");
2227 NS_TEST_EXPECT_MSG_EQ(unsigned(m_mac->GetMaxNumberOfTransmissions()),
2228 1,
2229 "m_nbTrans expected to be default value");
2230 auto channels = m_mac->GetLogicalLoraChannelHelper()->GetRawChannelArray();
2231 for (size_t i = 0; i < channels.size(); i++)
2232 {
2233 const auto& c = channels.at(i + 16 * chMaskCntl);
2234 bool actual = (c) ? c->IsEnabledForUplink() : false;
2235 bool expected = (uint16_t(0b111) & 0b1 << i);
2236 NS_TEST_EXPECT_MSG_EQ(actual, expected, "Channel " << i << " state != default");
2237 }
2238 NS_TEST_ASSERT_MSG_EQ(answers.size(), 1, "1 answer cmd was expected, found 0 or >1");
2239 auto laa = DynamicCast<LinkAdrAns>(answers.at(0));
2240 NS_TEST_ASSERT_MSG_NE(laa, nullptr, "LinkAdrAns was expected, cmd type cast failed");
2241 NS_TEST_EXPECT_MSG_EQ(laa->GetChannelMaskAck(), false, "ChannelMaskAck != false");
2242 NS_TEST_EXPECT_MSG_EQ(laa->GetDataRateAck(), true, "DataRateAck expected to be true");
2243 NS_TEST_EXPECT_MSG_EQ(laa->GetPowerAck(), true, "PowerAck expected to be true");
2244 }
2245
2246 Reset();
2247 // LinkAdrReq: fringe parameter values
2248 { // WARNING: default values are manually set here
2249 uint8_t dataRate = 0xF;
2250 uint8_t txPower = 0xF; // 0x0F ignores config
2251 uint16_t chMask = 0b0; // should be ignored because chMaskCntl is 6
2252 uint8_t chMaskCntl = 6; // all channels on
2253 uint8_t nbTrans = 0; // restore default 1
2254 // Set device params to values different from default
2255 m_mac->SetDataRate(3);
2256 m_mac->SetTransmissionPowerDbm(12);
2257 m_mac->SetMaxNumberOfTransmissions(15);
2258 auto channels = m_mac->GetLogicalLoraChannelHelper()->GetRawChannelArray();
2259 channels.at(0)->DisableForUplink();
2260 auto answers = RunMacCommand<LinkAdrReq>(dataRate, txPower, chMask, chMaskCntl, nbTrans);
2261 NS_TEST_EXPECT_MSG_EQ(unsigned(m_mac->GetDataRate()),
2262 3,
2263 "m_dataRate expected to be default value");
2264 NS_TEST_EXPECT_MSG_EQ(m_mac->GetTransmissionPowerDbm(),
2265 12,
2266 "m_txPowerDbm expected to be default value");
2267 NS_TEST_EXPECT_MSG_EQ(unsigned(m_mac->GetMaxNumberOfTransmissions()),
2268 1,
2269 "m_nbTrans expected to be default value");
2270 for (size_t i = 0; i < channels.size(); i++)
2271 {
2272 const auto& c = channels.at(i);
2273 bool actual = (c) ? c->IsEnabledForUplink() : false;
2274 bool expected = (uint16_t(0b111) & 0b1 << i);
2275 NS_TEST_EXPECT_MSG_EQ(actual, expected, "Channel " << i << " state != default");
2276 }
2277 NS_TEST_ASSERT_MSG_EQ(answers.size(), 1, "1 answer cmd was expected, found 0 or >1");
2278 auto laa = DynamicCast<LinkAdrAns>(answers.at(0));
2279 NS_TEST_ASSERT_MSG_NE(laa, nullptr, "LinkAdrAns was expected, cmd type cast failed");
2280 NS_TEST_EXPECT_MSG_EQ(laa->GetChannelMaskAck(), true, "ChannelMaskAck != true");
2281 NS_TEST_EXPECT_MSG_EQ(laa->GetDataRateAck(), true, "DataRateAck expected to be true");
2282 NS_TEST_EXPECT_MSG_EQ(laa->GetPowerAck(), true, "PowerAck expected to be true");
2283 }
2284
2285 Reset();
2286 // DutyCycleReq: duty cycle to 100%
2287 {
2288 uint8_t maxDutyCycle = 0;
2289 auto answers = RunMacCommand<DutyCycleReq>(maxDutyCycle);
2290 NS_TEST_EXPECT_MSG_EQ(m_mac->GetAggregatedDutyCycle(),
2291 1 / std::pow(2, maxDutyCycle),
2292 "m_aggregatedDutyCycle != 1");
2293 NS_TEST_ASSERT_MSG_EQ(answers.size(), 1, "1 answer cmd was expected, found 0 or >1");
2294 auto dca = DynamicCast<DutyCycleAns>(answers.at(0));
2295 NS_TEST_EXPECT_MSG_NE(dca, nullptr, "DutyCycleAns was expected, cmd type cast failed");
2296 }
2297
2298 Reset();
2299 // DutyCycleReq: duty cycle to 12.5%
2300 {
2301 uint8_t maxDutyCycle = 3;
2302 auto answers = RunMacCommand<DutyCycleReq>(maxDutyCycle);
2303 NS_TEST_EXPECT_MSG_EQ(m_mac->GetAggregatedDutyCycle(),
2304 1 / std::pow(2, maxDutyCycle),
2305 "m_aggregatedDutyCycle != 1");
2306 NS_TEST_ASSERT_MSG_EQ(answers.size(), 1, "1 answer cmd was expected, found 0 or >1");
2307 auto dca = DynamicCast<DutyCycleAns>(answers.at(0));
2308 NS_TEST_EXPECT_MSG_NE(dca, nullptr, "DutyCycleAns was expected, cmd type cast failed");
2309 }
2310
2311 Reset();
2312 // RxParamSetupReq: set rx1Dr, rx2Dr, frequency
2313 {
2314 uint8_t rx1DrOffset = 5;
2315 uint8_t rx2DataRate = 5;
2316 double frequencyHz = 863500000;
2317 m_mac->SetDataRate(5);
2318 auto answers = RunMacCommand<RxParamSetupReq>(rx1DrOffset, rx2DataRate, frequencyHz);
2319 NS_TEST_EXPECT_MSG_EQ(unsigned(m_mac->GetFirstReceiveWindowDataRate()),
2320 unsigned(5 - rx1DrOffset),
2321 "Rx1DataRate does not match rx1DrOffset from RxParamSetupReq");
2322 NS_TEST_EXPECT_MSG_EQ(unsigned(m_mac->GetSecondReceiveWindowDataRate()),
2323 unsigned(rx2DataRate),
2324 "Rx2DataRate does not match rx2DataRate from RxParamSetupReq");
2325 NS_TEST_EXPECT_MSG_EQ(m_mac->GetSecondReceiveWindowFrequency(),
2326 frequencyHz,
2327 "Rx2 frequency does not match frequency from RxParamSetupReq");
2328 NS_TEST_ASSERT_MSG_EQ(answers.size(), 1, "1 answer cmd was expected, found 0 or >1");
2329 auto rpsa = DynamicCast<RxParamSetupAns>(answers.at(0));
2330 NS_TEST_ASSERT_MSG_NE(rpsa, nullptr, "RxParamSetupAns was expected, cmd type cast failed");
2331 NS_TEST_EXPECT_MSG_EQ(rpsa->GetRx1DrOffsetAck(), true, "Rx1DrOffsetAck != true");
2332 NS_TEST_EXPECT_MSG_EQ(rpsa->GetRx2DataRateAck(), true, "Rx2DataRateAck != true");
2333 NS_TEST_EXPECT_MSG_EQ(rpsa->GetChannelAck(), true, "ChannelAck expected to be true");
2334 }
2335
2336 Reset();
2337 // RxParamSetupReq: invalid rx1Dr, rx2Dr, frequency
2338 { // WARNING: default values are manually set here
2339 uint8_t rx1DrOffset = 6;
2340 uint8_t rx2DataRate = 12;
2341 double frequencyHz = 871000000;
2342 m_mac->SetDataRate(5);
2343 auto answers = RunMacCommand<RxParamSetupReq>(rx1DrOffset, rx2DataRate, frequencyHz);
2344 NS_TEST_EXPECT_MSG_EQ(unsigned(m_mac->GetFirstReceiveWindowDataRate()),
2345 5,
2346 "Rx1DataRate expected to be default value");
2347 NS_TEST_EXPECT_MSG_EQ(unsigned(m_mac->GetSecondReceiveWindowDataRate()),
2348 0,
2349 "Rx2DataRate expected to be default value");
2350 NS_TEST_EXPECT_MSG_EQ(m_mac->GetSecondReceiveWindowFrequency(),
2351 869525000,
2352 "Rx2 frequency expected to be default value");
2353 NS_TEST_ASSERT_MSG_EQ(answers.size(), 1, "1 answer cmd was expected, found 0 or >1");
2354 auto rpsa = DynamicCast<RxParamSetupAns>(answers.at(0));
2355 NS_TEST_ASSERT_MSG_NE(rpsa, nullptr, "RxParamSetupAns was expected, cmd type cast failed");
2356 NS_TEST_EXPECT_MSG_EQ(rpsa->GetRx1DrOffsetAck(), false, "Rx1DrOffsetAck != false");
2357 NS_TEST_EXPECT_MSG_EQ(rpsa->GetRx2DataRateAck(), false, "Rx2DataRateAck != false");
2358 NS_TEST_EXPECT_MSG_EQ(rpsa->GetChannelAck(), false, "ChannelAck expected to be false");
2359 }
2360
2361 Reset();
2362 // DevStatusReq: get default values
2363 { // WARNING: default values are manually set here
2364 auto answers = RunMacCommand<DevStatusReq>();
2365 NS_TEST_ASSERT_MSG_EQ(answers.size(), 1, "1 answer cmd was expected, found 0 or >1");
2366 auto dsa = DynamicCast<DevStatusAns>(answers.at(0));
2367 NS_TEST_ASSERT_MSG_NE(dsa, nullptr, "DevStatusAns was expected, cmd type cast failed");
2368 NS_TEST_EXPECT_MSG_EQ(unsigned(dsa->GetBattery()), 0, "Battery expected == 0 (ext power)");
2369 NS_TEST_EXPECT_MSG_EQ(unsigned(dsa->GetMargin()), 31, "Margin expected to be 31 (default)");
2370 }
2371
2372 Reset();
2373 // NewChannelReq: add a new channel
2374 {
2375 uint8_t chIndex = 4;
2376 double frequencyHz = 865100000;
2377 uint8_t minDataRate = 1;
2378 uint8_t maxDataRate = 4;
2379 auto answers = RunMacCommand<NewChannelReq>(chIndex, frequencyHz, minDataRate, maxDataRate);
2380 NS_TEST_ASSERT_MSG_EQ(answers.size(), 1, "1 answer cmd was expected, found 0 or >1");
2381 auto c = m_mac->GetLogicalLoraChannelHelper()->GetRawChannelArray().at(chIndex);
2382 NS_TEST_ASSERT_MSG_NE(c, nullptr, "Channel at chIndex slot expected not to be nullptr");
2383 NS_TEST_EXPECT_MSG_EQ(c->GetFrequency(),
2384 frequencyHz,
2385 "Channel frequency expected to equal NewChannelReq frequency");
2386 NS_TEST_EXPECT_MSG_EQ(c->GetMinimumDataRate(),
2387 unsigned(minDataRate),
2388 "Channel minDataRate expected to equal NewChannelReq minDataRate");
2389 NS_TEST_EXPECT_MSG_EQ(c->GetMaximumDataRate(),
2390 unsigned(maxDataRate),
2391 "Channel maxDataRate expected to equal NewChannelReq maxDataRate");
2392 auto nca = DynamicCast<NewChannelAns>(answers.at(0));
2393 NS_TEST_ASSERT_MSG_NE(nca, nullptr, "NewChannelAns was expected, cmd type cast failed");
2394 NS_TEST_EXPECT_MSG_EQ(nca->GetDataRateRangeOk(), true, "DataRateRangeOk != true");
2395 NS_TEST_EXPECT_MSG_EQ(nca->GetChannelFrequencyOk(), true, "ChannelFrequencyOk != true");
2396 }
2397
2398 Reset();
2399 // NewChannelReq: invalid new channel
2400 { // WARNING: default values are manually set here
2401 uint8_t chIndex = 1;
2402 double frequencyHz = 862000000;
2403 uint8_t minDataRate = 14;
2404 uint8_t maxDataRate = 13;
2405 auto answers = RunMacCommand<NewChannelReq>(chIndex, frequencyHz, minDataRate, maxDataRate);
2406 NS_TEST_ASSERT_MSG_EQ(answers.size(), 1, "1 answer cmd was expected, found 0 or >1");
2407 double defaultFrequenciesHz[3] = {868100000, 868300000, 868500000};
2408 auto channels = m_mac->GetLogicalLoraChannelHelper()->GetRawChannelArray();
2409 for (size_t i = 0; i < channels.size(); i++)
2410 {
2411 const auto& c = channels.at(i);
2412 if (i > 2)
2413 {
2414 NS_TEST_ASSERT_MSG_EQ(c, nullptr, "Channel " << i << "expected to be nullptr");
2415 continue;
2416 }
2417 NS_TEST_EXPECT_MSG_EQ(c->GetFrequency(),
2418 defaultFrequenciesHz[i],
2419 "Channel frequency expected to equal NewChannelReq frequency");
2420 NS_TEST_EXPECT_MSG_EQ(unsigned(c->GetMinimumDataRate()),
2421 0,
2422 "Channel " << i << " minDataRate expected to be default");
2423 NS_TEST_EXPECT_MSG_EQ(unsigned(c->GetMaximumDataRate()),
2424 5,
2425 "Channel " << i << " maxDataRate expected to be default");
2426 NS_TEST_EXPECT_MSG_EQ(c->IsEnabledForUplink(),
2427 true,
2428 "Channel " << i << " state expected to be active by default");
2429 }
2430 auto nca = DynamicCast<NewChannelAns>(answers.at(0));
2431 NS_TEST_ASSERT_MSG_NE(nca, nullptr, "NewChannelAns was expected, cmd type cast failed");
2432 NS_TEST_EXPECT_MSG_EQ(nca->GetDataRateRangeOk(), false, "DataRateRangeOk != false");
2433 NS_TEST_EXPECT_MSG_EQ(nca->GetChannelFrequencyOk(), false, "ChannelFrequencyOk != false");
2434 }
2435}
2436
2437/**
2438 * @ingroup lorawan
2439 *
2440 * It tests the correct execution of the ADR backoff procedure of LoRaWAN devices.
2441 * (See, LoRaWAN L2 1.0.4 Specifications (2020), Section 4.3.1.1)
2442 */
2444{
2445 public:
2446 AdrBackoffTest(); //!< Default constructor
2447 ~AdrBackoffTest() override; //!< Destructor
2448
2449 private:
2450 /**
2451 * Create and send an empty app payload unconfirmed frame through the MAC layer to increment
2452 * of the FCnt and ADRACKCnt and eventually activate the ADR backoff procedure configurations of
2453 * the MAC layer. The packet is sent after a delay (simulated time is fast-forwarded to the
2454 * event) such that the device does not incur any duty-cycle limitation. The sent packet FHDR is
2455 * returned as argument for validation purposes.
2456 *
2457 * @param after Delay to schedule the packet after to avoid duty-cycle limitations
2458 * @param fhdr [out] FHDR of the constructed frame passed to PHY by the MAC
2459 */
2460 void SendUplink(Time after, LoraFrameHeader& fhdr);
2461
2462 /**
2463 * Create and schedule the PHY reception of a downlink transmission configured for the LoRaWAN
2464 * MAC first reception window. This is used to test resetting the ADR backoff procedure.
2465 *
2466 * @note This does not call Simulator::Run(), enabling preemptive scheduling, but must be
2467 * manually timed to happen during the first reception window
2468 *
2469 * It constrains the device to a single uplink channel to force-out the first reception window
2470 * frequency. The downlink spreading factor is taken from the current MAC configuration.
2471 *
2472 * @param after Delay to schedule the packet after (must target the first reception window)
2473 */
2474 void ScheduleRx1Downlink(Time after);
2475
2476 /**
2477 * This function resets the simulation and device MAC layer, use before test sub-cases.
2478 */
2479 void Reset();
2480
2481 void DoRun() override;
2482
2483 Ptr<ClassAEndDeviceLorawanMac> m_mac; //!< The end device's MAC layer used in tests.
2484};
2485
2487 : TestCase("Test the ADR backoff procedure of the LoRaWAN MAC protocol")
2488{
2489}
2490
2492{
2493 m_mac = nullptr;
2494}
2495
2496void
2498{
2499 Ptr<Packet> pkt;
2500 LorawanMacHeader mhdr;
2501 // Send packet through the MAC layer
2502 pkt = Create<Packet>(0);
2505 // Retrieve uplink FHDR
2506 pkt->RemoveHeader(mhdr);
2507 fhdr.SetAsUplink();
2508 pkt->RemoveHeader(fhdr);
2509 NS_LOG_LOGIC("FHDR: " << fhdr);
2510}
2511
2512void
2514{
2515 Ptr<Packet> pkt;
2516 LoraFrameHeader fhdr;
2517 LorawanMacHeader mhdr;
2518 // Prepare DL packet
2519 pkt = Create<Packet>(0);
2520 fhdr.SetAsDownlink();
2521 pkt->AddHeader(fhdr);
2523 pkt->AddHeader(mhdr);
2524 pkt->AddPaddingAtEnd(4); // MIC
2525 // Force the next RX1 window channel frequency
2526 auto chVec = m_mac->GetLogicalLoraChannelHelper()->GetRawChannelArray();
2527 chVec.at(1)->DisableForUplink();
2528 chVec.at(2)->DisableForUplink();
2529 // Schedule MAC layer reception through PHY
2530 auto phy = DynamicCast<SimpleEndDeviceLoraPhy>(m_mac->GetPhy());
2531 Simulator::Schedule(after,
2533 phy,
2534 pkt,
2535 chVec.at(0)->GetFrequency(),
2537 12,
2538 -100,
2539 MilliSeconds(10));
2540}
2541
2542void
2544{
2546 // Reset MAC state
2547 LorawanMacHelper macHelper;
2550 /// @todo Install should not require a node in input.
2551 m_mac = DynamicCast<ClassAEndDeviceLorawanMac>(macHelper.Install(nullptr, nullptr));
2552 NS_TEST_EXPECT_MSG_NE(m_mac, nullptr, "Failed to initialize MAC layer object.");
2554 phy->SetChannel(CreateObject<LoraChannel>());
2556 m_mac->SetPhy(phy);
2557}
2558
2559void
2561{
2562 NS_LOG_DEBUG("AdrBackoffTest");
2563
2564 Reset();
2565 // Full ADR Backoff procedure
2566 {
2567 LoraFrameHeader fhdr;
2568 auto llch = m_mac->GetLogicalLoraChannelHelper();
2569 auto ADR_ACK_LIMIT = EndDeviceLorawanMac::ADR_ACK_LIMIT;
2570 auto ADR_ACK_DELAY = EndDeviceLorawanMac::ADR_ACK_DELAY;
2571 // Custom config to force full ADR backoff
2572 {
2573 // Tx parameters to furthest settings from default
2574 m_mac->SetDataRate(5);
2575 m_mac->SetTransmissionPowerDbm(0);
2576 m_mac->SetMaxNumberOfTransmissions(8);
2577 auto chVec = llch->GetRawChannelArray();
2578 chVec.at(0)->DisableForUplink();
2579 chVec.at(1)->DisableForUplink();
2580 chVec.at(2)->DisableForUplink();
2581 // Provide additional non-default channel for uplinks
2582 auto nonDefaultChannel = Create<LogicalLoraChannel>(869850000, 0, 5);
2583 llch->SetChannel(3, nonDefaultChannel);
2584 }
2585 // 7 total backoff steps: 1 tx power + 5 data rate + 1 nbtrans & channels
2586 for (uint32_t fCnt = 0; fCnt <= ADR_ACK_LIMIT + ADR_ACK_DELAY * 7U; ++fCnt)
2587 {
2588 SendUplink(Minutes(20), fhdr);
2589 NS_TEST_EXPECT_MSG_EQ(fhdr.GetFCnt(), fCnt, "Unexpected FCnt value in uplink FHDR");
2591 fCnt >= ADR_ACK_LIMIT,
2592 "Unexpected ADRACKReq value in FHDR of uplink fCnt=" << fCnt);
2593 uint8_t step = (fCnt >= ADR_ACK_LIMIT) ? (fCnt - ADR_ACK_LIMIT) / ADR_ACK_DELAY : 0;
2594 NS_TEST_EXPECT_MSG_EQ(m_mac->GetTransmissionPowerDbm(),
2595 (step > 0) ? 14 : 0,
2596 "Unexpected tx power on uplink fCnt=" << fCnt);
2597 uint8_t expectedDr = (step == 0) ? 5 : (step < 7) ? 5 - (step - 1) : 0;
2598 NS_TEST_EXPECT_MSG_EQ(m_mac->GetDataRate(),
2599 expectedDr,
2600 "Unexpected data rate on uplink fCnt=" << fCnt);
2601 const auto chVec = llch->GetRawChannelArray();
2602 for (uint8_t i = 0; i < 3; ++i)
2603 {
2604 NS_TEST_EXPECT_MSG_EQ(chVec.at(i)->IsEnabledForUplink(),
2605 step >= 7,
2606 "Unexpected activation state of channel "
2607 << unsigned(i) << " on uplink fCnt=" << fCnt);
2608 }
2610 chVec.at(3)->IsEnabledForUplink(),
2611 true,
2612 "Unexpected activation state of channel 3 on uplink fCnt=" << fCnt);
2613 }
2614 }
2615
2616 Reset();
2617 // ADRACKReq back to false after downlink
2618 {
2619 LoraFrameHeader fhdr;
2620 auto ADR_ACK_LIMIT = EndDeviceLorawanMac::ADR_ACK_LIMIT;
2621 // Trigger ADRACKReq
2622 for (uint16_t fCnt = 0; fCnt <= ADR_ACK_LIMIT + 5; ++fCnt)
2623 {
2624 SendUplink(Minutes(20), fhdr);
2625 NS_TEST_EXPECT_MSG_EQ(fhdr.GetFCnt(), fCnt, "Unexpected FCnt value in uplink FHDR");
2627 fCnt >= ADR_ACK_LIMIT,
2628 "Unexpected ADRACKReq value in FHDR of uplink fCnt=" << fCnt);
2629 }
2630 // Receive downlink for the next packet RX window
2632 // Trigger reception windows with new uplink
2633 SendUplink(Minutes(20), fhdr);
2635 ADR_ACK_LIMIT + 5 + 1,
2636 "Unexpected FCnt value in uplink FHDR");
2638 fhdr.GetAdrAckReq(),
2639 true,
2640 "Unexpected ADRACKReq value in FHDR of uplink fCnt=" << fhdr.GetFCnt());
2641 // Next uplink should have ADRACKReq unset because a downlink was received
2642 SendUplink(Minutes(20), fhdr);
2644 ADR_ACK_LIMIT + 5 + 2,
2645 "Unexpected FCnt value in uplink FHDR");
2647 fhdr.GetAdrAckReq(),
2648 false,
2649 "Unexpected ADRACKReq value in FHDR of uplink fCnt=" << fhdr.GetFCnt());
2650 }
2651}
2652
2653/**
2654 * @ingroup lorawan
2655 *
2656 * It tests the correct execution of the retransmissions in LoRaWAN devices.
2657 * (See, LoRaWAN L2 1.0.4 Specifications (2020), Section 4.3.1.3)
2658 */
2660{
2661 public:
2662 RetransmissionTest(); //!< Default constructor
2663 ~RetransmissionTest() override; //!< Destructor
2664
2665 private:
2666 /**
2667 * Create and send an empty app payload unconfirmed frame through the MAC layer NbTrans times.
2668 * The sent packet FHDR is returned as argument for validation purposes.
2669 *
2670 * @param fhdr [out] FHDR of the constructed frame passed to PHY by the MAC
2671 */
2672 void SendUplink(LoraFrameHeader& fhdr);
2673
2674 /**
2675 * Create and schedule the PHY reception of a downlink transmission configured for the LoRaWAN
2676 * MAC first reception window. This is used to test stopping the retransmission process.
2677 *
2678 * @note This does not call Simulator::Run(), enabling preemptive scheduling, but must be
2679 * manually timed to happen during the first reception window
2680 *
2681 * It constrains the device to a single uplink channel to force-out the first reception window
2682 * frequency. The downlink spreading factor is taken from the current MAC configuration.
2683 *
2684 * @param after Delay to schedule the packet after (must target the first reception window)
2685 * @param ack Whether to set the ACK flag in the frame header
2686 */
2687 void ScheduleRx1Downlink(Time after, bool ack = false);
2688
2689 /**
2690 * Callback for tracing MAC layer SentNewPacket.
2691 *
2692 * @param packet The packet sent.
2693 */
2695
2696 /**
2697 * Callback for tracing the outcome of MAC layer's confirmed packet retransmission and
2698 * acknowledgement.
2699 *
2700 * @note This callback only traces confirmed packets, unused otherwise.
2701 *
2702 * @param txCount Number of transmissions attempted during the process.
2703 * @param ack Whether the retransmission process led to acknowledgement.
2704 * @param firstAttempt Timestamp of the initial transmission attempt.
2705 * @param packet The packet being retransmitted.
2706 */
2707 void MacConfirmedTransmissionOutcome(uint8_t txCount,
2708 bool ack,
2709 Time firstAttempt,
2710 Ptr<Packet> packet);
2711
2712 /**
2713 * Callback for tracing PHY layer StartSending.
2714 *
2715 * @param packet The packet being sent.
2716 * @param node The sender node id if any, 0 otherwise.
2717 */
2718 void PhyStartSending(Ptr<const Packet> packet, uint32_t node);
2719
2720 /**
2721 * Callback for tracing PHY layer ReceivedPacket.
2722 *
2723 * @param packet The packet being received.
2724 * @param node The sender node id if any, 0 otherwise.
2725 */
2726 void PhyReceivedPacket(Ptr<const Packet> packet, uint32_t node);
2727
2728 /**
2729 * This function resets the simulation and device MAC layer, use before test sub-cases.
2730 */
2731 void Reset();
2732
2733 void DoRun() override;
2734
2735 Ptr<ClassAEndDeviceLorawanMac> m_mac; //!< The end device's MAC layer used in tests.
2736 Ptr<Packet> m_packet; //!< Target packet for tracing
2737
2738 int m_macSentNewPacketCalls = 0; //!< Counter for MacSentNewPacket calls
2739 int m_macConfirmedTxOutcome = 0; //!< Counter for MacConfirmedTransmissionOutcome calls
2740 int m_phyStartSendingCalls = 0; //!< Counter for PhyStartSending calls
2741 int m_phyReceivedPacketCalls = 0; //!< Counter for PhyReceivedPacket calls
2742
2743 uint8_t m_numTransmissions = 0; //!< Number of confirmed packet transmissions
2744 bool m_successfullyAcked = false; //!< Acknowledgement of confirmed packet
2745};
2746
2748 : TestCase("Test the retransmission process of the LoRaWAN MAC protocol")
2749{
2750}
2751
2756
2757void
2759{
2760 Ptr<Packet> pkt;
2761 LorawanMacHeader mhdr;
2762 // Send packet through the MAC layer
2763 pkt = Create<Packet>(0);
2764 m_packet = pkt;
2767 // Retrieve uplink FHDR
2768 pkt->RemoveHeader(mhdr);
2769 fhdr.SetAsUplink();
2770 pkt->RemoveHeader(fhdr);
2771 NS_LOG_LOGIC("Frame Header: " << fhdr);
2772}
2773
2774void
2776{
2777 Ptr<Packet> pkt;
2778 LoraFrameHeader fhdr;
2779 LorawanMacHeader mhdr;
2780 // Prepare DL packet
2781 pkt = Create<Packet>(0);
2782 fhdr.SetAsDownlink();
2783 fhdr.SetAck(ack);
2784 pkt->AddHeader(fhdr);
2786 pkt->AddHeader(mhdr);
2787 pkt->AddPaddingAtEnd(4); // MIC
2788 // Force the next RX1 window channel frequency
2789 auto chVec = m_mac->GetLogicalLoraChannelHelper()->GetRawChannelArray();
2790 chVec.at(1)->DisableForUplink();
2791 chVec.at(2)->DisableForUplink();
2792 // Schedule MAC layer reception through PHY
2793 auto phy = DynamicCast<SimpleEndDeviceLoraPhy>(m_mac->GetPhy());
2794 Simulator::Schedule(after,
2796 phy,
2797 pkt,
2798 chVec.at(0)->GetFrequency(),
2800 m_mac->GetSfFromDataRate(m_mac->GetDataRate()),
2801 -100,
2802 MilliSeconds(10));
2803}
2804
2805void
2810
2811void
2813 bool ack,
2814 Time firstAttempt,
2815 Ptr<Packet> packet)
2816{
2818 if (m_packet == packet)
2819 {
2820 m_numTransmissions = txCount;
2821 m_successfullyAcked = ack;
2822 }
2823}
2824
2825void
2830
2831void
2836
2837void
2839{
2845 m_successfullyAcked = false;
2847 // Reset MAC state
2848 LorawanMacHelper macHelper;
2851 m_mac = DynamicCast<ClassAEndDeviceLorawanMac>(macHelper.Install(nullptr, nullptr));
2852 m_mac->SetDataRate(5);
2853 m_mac->TraceConnectWithoutContext("SentNewPacket",
2855 m_mac->TraceConnectWithoutContext(
2856 "ConfirmedTransmissionOutcome",
2858 NS_TEST_EXPECT_MSG_NE(m_mac, nullptr, "Failed to initialize MAC layer object.");
2860 phy->SetChannel(CreateObject<LoraChannel>());
2862 phy->TraceConnectWithoutContext("StartSending",
2864 phy->TraceConnectWithoutContext("ReceivedPacket",
2866 m_mac->SetPhy(phy);
2867}
2868
2869void
2871{
2872 NS_LOG_DEBUG("RetransmissionTest");
2873
2874 Reset();
2875 // Unconfirmed send yields the correct number of retransmissions (base case)
2876 { // WARNING: default values are manually set here
2878 LoraFrameHeader fhdr;
2879 SendUplink(fhdr);
2880 NS_TEST_EXPECT_MSG_EQ(fhdr.GetFCnt(), 0, "Unexpected FCnt value in uplink FHDR");
2881 NS_TEST_EXPECT_MSG_EQ(m_mac->GetUplinkFrameCounter(),
2882 1,
2883 "Unexpected MAC frame counter value");
2885 1,
2886 "Unexpected number of PHY layer StartSending calls");
2888 0,
2889 "Unexpected number of PHY layer ReceivedPacket calls");
2891 1,
2892 "Unexpected number of MAC layer SendNewPacket calls");
2894 0,
2895 "Unexpected number of MAC layer ConfirmedTransmissionOutcome calls");
2896 }
2897
2898 Reset();
2899 // Unconfirmed send yields the correct number of retransmissions
2900 {
2901 uint8_t nbTrans = 4;
2902 m_mac->SetMaxNumberOfTransmissions(nbTrans);
2904 LoraFrameHeader fhdr;
2905 SendUplink(fhdr);
2906 NS_TEST_EXPECT_MSG_EQ(fhdr.GetFCnt(), 0, "Unexpected FCnt value in uplink FHDR");
2907 NS_TEST_EXPECT_MSG_EQ(m_mac->GetUplinkFrameCounter(),
2908 1,
2909 "Unexpected FCnt value in MAC layer");
2911 nbTrans,
2912 "Unexpected number of PHY layer StartSending calls");
2914 0,
2915 "Unexpected number of PHY layer ReceivedPacket calls");
2917 1,
2918 "Unexpected number of MAC layer SendNewPacket calls");
2920 0,
2921 "Unexpected number of MAC layer ConfirmedTransmissionOutcome calls");
2922 }
2923
2924 Reset();
2925 // Unconfirmed send yields the correct number of retransmissions (limit case)
2926 {
2927 uint8_t nbTrans = 15;
2928 m_mac->SetMaxNumberOfTransmissions(nbTrans);
2930 LoraFrameHeader fhdr;
2931 SendUplink(fhdr);
2932 NS_TEST_EXPECT_MSG_EQ(fhdr.GetFCnt(), 0, "Unexpected FCnt value in uplink FHDR");
2933 NS_TEST_EXPECT_MSG_EQ(m_mac->GetUplinkFrameCounter(),
2934 1,
2935 "Unexpected MAC frame counter value");
2937 nbTrans,
2938 "Unexpected number of physical layer transmissions");
2940 0,
2941 "Unexpected number of PHY layer ReceivedPacket calls");
2943 1,
2944 "Unexpected number of MAC layer SendNewPacket calls");
2946 0,
2947 "Unexpected number of MAC layer ConfirmedTransmissionOutcome calls");
2948 }
2949
2950 Reset();
2951 // Unconfirmed send interrupted in-between retransmissions
2952 {
2953 uint8_t nbTrans = 9;
2954 m_mac->SetMaxNumberOfTransmissions(nbTrans);
2958 m_mac,
2959 Create<Packet>(0));
2960 LoraFrameHeader fhdr;
2961 SendUplink(fhdr);
2962 NS_TEST_EXPECT_MSG_EQ(fhdr.GetFCnt(), 0, "Unexpected FCnt value in uplink FHDR");
2963 NS_TEST_EXPECT_MSG_EQ(m_mac->GetUplinkFrameCounter(),
2964 2,
2965 "Unexpected FCnt value in MAC layer");
2967 1 + nbTrans,
2968 "Unexpected number of PHY layer StartSending calls");
2970 0,
2971 "Unexpected number of PHY layer ReceivedPacket calls");
2973 2,
2974 "Unexpected number of MAC layer SendNewPacket calls");
2976 0,
2977 "Unexpected number of MAC layer ConfirmedTransmissionOutcome calls");
2978 }
2979
2980 Reset();
2981 // Unconfirmed send retransmissions interrupted while MAC layer busy
2982 {
2983 uint8_t nbTrans = 8;
2984 m_mac->SetMaxNumberOfTransmissions(nbTrans);
2987 LoraFrameHeader fhdr;
2988 SendUplink(fhdr);
2989 NS_TEST_EXPECT_MSG_EQ(fhdr.GetFCnt(), 0, "Unexpected FCnt value in uplink FHDR");
2990 NS_TEST_EXPECT_MSG_EQ(m_mac->GetUplinkFrameCounter(),
2991 2,
2992 "Unexpected FCnt value in MAC layer");
2994 2 + nbTrans,
2995 "Unexpected number of PHY layer StartSending calls");
2997 0,
2998 "Unexpected number of PHY layer ReceivedPacket calls");
3000 2,
3001 "Unexpected number of MAC layer SendNewPacket calls");
3003 0,
3004 "Unexpected number of MAC layer ConfirmedTransmissionOutcome calls");
3005 }
3006
3007 Reset();
3008 // Unconfirmed send retransmissions interrupted after downlink
3009 {
3010 uint8_t nbTrans = 3;
3011 m_mac->SetMaxNumberOfTransmissions(nbTrans);
3014 LoraFrameHeader fhdr;
3015 SendUplink(fhdr);
3016 NS_TEST_EXPECT_MSG_EQ(fhdr.GetFCnt(), 0, "Unexpected FCnt value in uplink FHDR");
3017 NS_TEST_EXPECT_MSG_EQ(m_mac->GetUplinkFrameCounter(),
3018 1,
3019 "Unexpected FCnt value in MAC layer");
3021 1,
3022 "Unexpected number of PHY layer StartSending calls");
3024 1,
3025 "Unexpected number of PHY layer ReceivedPacket calls");
3027 1,
3028 "Unexpected number of MAC layer SendNewPacket calls");
3030 0,
3031 "Unexpected number of MAC layer ConfirmedTransmissionOutcome calls");
3032 }
3033
3034 Reset();
3035 // Unconfirmed send retransmissions interrupted after downlink (different params)
3036 {
3037 uint8_t nbTrans = 13;
3038 m_mac->SetMaxNumberOfTransmissions(nbTrans);
3041 LoraFrameHeader fhdr;
3042 SendUplink(fhdr);
3043 NS_TEST_EXPECT_MSG_EQ(fhdr.GetFCnt(), 0, "Unexpected FCnt value in uplink FHDR");
3044 NS_TEST_EXPECT_MSG_EQ(m_mac->GetUplinkFrameCounter(),
3045 1,
3046 "Unexpected FCnt value in MAC layer");
3048 7,
3049 "Unexpected number of PHY layer StartSending calls");
3051 1,
3052 "Unexpected number of PHY layer ReceivedPacket calls");
3054 1,
3055 "Unexpected number of MAC layer SendNewPacket calls");
3057 0,
3058 "Unexpected number of MAC layer ConfirmedTransmissionOutcome calls");
3059 }
3060
3061 Reset();
3062 // Confirmed yields the correct number of unacknowledged retransmissions
3063 {
3064 uint8_t nbTrans = 7;
3065 m_mac->SetMaxNumberOfTransmissions(nbTrans);
3067 LoraFrameHeader fhdr;
3068 SendUplink(fhdr);
3069 NS_TEST_EXPECT_MSG_EQ(fhdr.GetFCnt(), 0, "Unexpected FCnt value in uplink FHDR");
3070 NS_TEST_EXPECT_MSG_EQ(m_mac->GetUplinkFrameCounter(),
3071 1,
3072 "Unexpected FCnt value in MAC layer");
3074 nbTrans,
3075 "Unexpected number of PHY layer StartSending calls");
3077 0,
3078 "Unexpected number of PHY layer ReceivedPacket calls");
3080 1,
3081 "Unexpected number of MAC layer SendNewPacket calls");
3083 1,
3084 "Unexpected number of MAC layer ConfirmedTransmissionOutcome calls");
3086 nbTrans,
3087 "Unexpected number of transmissions for confirmed packet");
3089 false,
3090 "Unexpected acknowledgment state for confirmed packet");
3091 }
3092
3093 Reset();
3094 // Confirmed send retransmissions interrupted in-between retransmissions
3095 {
3096 uint8_t nbTrans = 6;
3097 m_mac->SetMaxNumberOfTransmissions(nbTrans);
3101 m_mac,
3102 Create<Packet>(0));
3103 LoraFrameHeader fhdr;
3104 SendUplink(fhdr);
3105 NS_TEST_EXPECT_MSG_EQ(fhdr.GetFCnt(), 0, "Unexpected FCnt value in uplink FHDR");
3106 NS_TEST_EXPECT_MSG_EQ(m_mac->GetUplinkFrameCounter(),
3107 2,
3108 "Unexpected FCnt value in MAC layer");
3110 2 + nbTrans,
3111 "Unexpected number of PHY layer StartSending calls");
3113 0,
3114 "Unexpected number of PHY layer ReceivedPacket calls");
3116 2,
3117 "Unexpected number of MAC layer SendNewPacket calls");
3119 2,
3120 "Unexpected number of MAC layer ConfirmedTransmissionOutcome calls");
3122 2,
3123 "Unexpected number of transmissions for confirmed packet");
3125 false,
3126 "Unexpected acknowledgment state for confirmed packet");
3127 }
3128
3129 Reset();
3130 // Confirmed send retransmissions interrupted interrupted while MAC layer busy
3131 {
3132 uint8_t nbTrans = 9;
3133 m_mac->SetMaxNumberOfTransmissions(nbTrans);
3137 m_mac,
3138 Create<Packet>(0));
3139 LoraFrameHeader fhdr;
3140 SendUplink(fhdr);
3141 NS_TEST_EXPECT_MSG_EQ(fhdr.GetFCnt(), 0, "Unexpected FCnt value in uplink FHDR");
3142 NS_TEST_EXPECT_MSG_EQ(m_mac->GetUplinkFrameCounter(),
3143 2,
3144 "Unexpected FCnt value in MAC layer");
3146 3 + nbTrans,
3147 "Unexpected number of PHY layer StartSending calls");
3149 0,
3150 "Unexpected number of PHY layer ReceivedPacket calls");
3152 2,
3153 "Unexpected number of MAC layer SendNewPacket calls");
3155 2,
3156 "Unexpected number of MAC layer ConfirmedTransmissionOutcome calls");
3158 3,
3159 "Unexpected number of transmissions for confirmed packet");
3161 false,
3162 "Unexpected acknowledgment state for confirmed packet");
3163 }
3164
3165 Reset();
3166 // Confirmed send retransmissions not interrupted after downlink without ACK
3167 {
3168 uint8_t nbTrans = 10;
3169 m_mac->SetMaxNumberOfTransmissions(nbTrans);
3172 LoraFrameHeader fhdr;
3173 SendUplink(fhdr);
3174 NS_TEST_EXPECT_MSG_EQ(fhdr.GetFCnt(), 0, "Unexpected FCnt value in uplink FHDR");
3175 NS_TEST_EXPECT_MSG_EQ(m_mac->GetUplinkFrameCounter(),
3176 1,
3177 "Unexpected FCnt value in MAC layer");
3179 nbTrans,
3180 "Unexpected number of PHY layer StartSending calls");
3182 1,
3183 "Unexpected number of PHY layer ReceivedPacket calls");
3185 1,
3186 "Unexpected number of MAC layer SendNewPacket calls");
3188 1,
3189 "Unexpected number of MAC layer ConfirmedTransmissionOutcome calls");
3191 nbTrans,
3192 "Unexpected number of transmissions for confirmed packet");
3194 false,
3195 "Unexpected acknowledgment state for confirmed packet");
3196 }
3197
3198 Reset();
3199 // Confirmed send retransmissions interrupted after downlink with ACK
3200 {
3201 uint8_t nbTrans = 14;
3202 m_mac->SetMaxNumberOfTransmissions(nbTrans);
3204 ScheduleRx1Downlink(Seconds(43.749), true);
3205 LoraFrameHeader fhdr;
3206 SendUplink(fhdr);
3207 NS_TEST_EXPECT_MSG_EQ(fhdr.GetFCnt(), 0, "Unexpected FCnt value in uplink FHDR");
3208 NS_TEST_EXPECT_MSG_EQ(m_mac->GetUplinkFrameCounter(),
3209 1,
3210 "Unexpected FCnt value in MAC layer");
3212 10,
3213 "Unexpected number of PHY layer StartSending calls");
3215 1,
3216 "Unexpected number of PHY layer ReceivedPacket calls");
3218 1,
3219 "Unexpected number of MAC layer SendNewPacket calls");
3221 1,
3222 "Unexpected number of MAC layer ConfirmedTransmissionOutcome calls");
3224 10,
3225 "Unexpected number of transmissions for confirmed packet");
3227 true,
3228 "Unexpected acknowledgment state for confirmed packet");
3229 }
3230}
3231
3232/**
3233 * @ingroup lorawan
3234 *
3235 * It tests that LoRa device correctly turning OFF on energy depletion
3236 */
3238{
3239 using State = EndDeviceLoraPhy::State; //!< PHY state
3240
3241 public:
3242 EnergyDepletionTest(); //!< Default constructor
3243 ~EnergyDepletionTest() override; //!< Destructor
3244
3245 /**
3246 * Reset device for new sub test case.
3247 *
3248 * @param energyJ Initial battery energy in Joule
3249 * @param batteryTh Battery depletion threshold (0-1 percentage)
3250 * @param rxTime (optional) Schedule a PHY RX at provided time > 0
3251 */
3252 void Reset(double energyJ, double batteryTh, Time rxTime = Time());
3253
3254 private:
3255 /**
3256 * Callback for tracing changes in the LoRa PHY state
3257 *
3258 * @param prev old PHY state
3259 * @param curr new PHY state
3260 */
3262
3263 /**
3264 * Callback for tracing a device PHY's energy model energy consumption
3265 *
3266 * @param prev old value of total energy consumption in Joules
3267 * @param curr new value of total energy consumption in Joules
3268 */
3269 void OnTotalEnergyConsumptionChange(double prev, double curr);
3270
3271 void DoRun() override;
3272
3273 Ptr<Node> m_node; //!< LoRaWAN end device node used in tests
3274
3275 std::vector<State> m_expectedStates; //!< States the PHY must go through
3276
3277 double m_totalEnergyConsumption; //!< Track PHY energy consumption in Joules
3278 size_t m_currentDeviceStateIndex; //!< Track current PHY state of the device
3279};
3280
3282 : TestCase("Test the energy depletion of a LoRaWAN device")
3283{
3284}
3285
3290
3291void
3292EnergyDepletionTest::Reset(double energyJ, double batteryTh, Time rxTime)
3293{
3294 // Reset simulation engine and tracing
3298
3299 // Configure LoRaWAN device
3302 auto dev = CreateObject<LoraNetDevice>();
3304 phy->SetChannel(CreateObject<LoraChannel>());
3305 phy->SetDevice(dev);
3306 dev->SetPhy(phy);
3307 LorawanMacHelper macHelper;
3310 auto mac = DynamicCast<ClassAEndDeviceLorawanMac>(macHelper.Install(m_node, dev));
3311 mac->SetPhy(phy);
3312 dev->SetMac(mac);
3313 m_node->AddDevice(dev);
3314 auto app = CreateObject<PeriodicSender>();
3315 app->SetInterval(Seconds(1200));
3316 app->SetInitialDelay(Time());
3317 app->SetPacketSize(0);
3318 app->SetNode(m_node);
3319 m_node->AddApplication(app);
3320
3321 // Configure and install energy source model on device
3322 BasicEnergySourceHelper basicSourceHelper;
3323 basicSourceHelper.Set("BasicEnergySourceInitialEnergyJ", DoubleValue(energyJ));
3324 basicSourceHelper.Set("BasicEnergySupplyVoltageV", DoubleValue(3.3));
3325 basicSourceHelper.Set("BasicEnergyLowBatteryThreshold", DoubleValue(batteryTh));
3326 basicSourceHelper.Set("PeriodicEnergyUpdateInterval", TimeValue(Time::Max()));
3327 auto source = basicSourceHelper.Install(m_node).Get(0);
3328
3329 // Configure and install energy consumption model on device
3330 LoraRadioEnergyModelHelper radioEnergyHelper;
3331 radioEnergyHelper.Set("SleepCurrentA", DoubleValue(0.1e-6));
3332 radioEnergyHelper.Set("StandbyCurrentA", DoubleValue(1.4e-3));
3333 radioEnergyHelper.Set("RxCurrentA", DoubleValue(10.8e-3));
3334 radioEnergyHelper.SetTxCurrentModel("ns3::LinearLoraTxCurrentModel",
3335 "Eta",
3336 DoubleValue(0.452750),
3337 "Voltage",
3338 DoubleValue(3.3),
3339 "BaseCurrent",
3340 DoubleValue(0.014646));
3341 auto model = radioEnergyHelper.Install(dev, source).Get(0);
3342
3343 if (rxTime.IsStrictlyPositive())
3344 {
3345 // Force uplinks on 1st channel for deterministic RX1 params
3346 const auto channels = mac->GetLogicalLoraChannelHelper()->GetRawChannelArray();
3347 channels.at(1)->DisableForUplink();
3348 channels.at(2)->DisableForUplink();
3349
3350 const auto rx1Frequency = channels.at(0)->GetFrequency();
3351 const auto rx2Frequency = mac->GetSecondReceiveWindowFrequency();
3352
3353 auto rxPkt = Create<Packet>(0); // empty lorawan packet
3354 LoraFrameHeader fHdr;
3355 fHdr.SetAsDownlink();
3356 rxPkt->AddHeader(fHdr);
3357 LorawanMacHeader mHdr;
3359 rxPkt->AddHeader(mHdr);
3360 rxPkt->AddPaddingAtEnd(4); // MIC
3361
3362 // Schedule downlink reception
3363 auto params = LoraTxParameters();
3364 params.spreadingFactor = 12;
3365 params.lowDataRateOptimize = true;
3366 const auto pktToA = LoraPhy::GetTimeOnAir(rxPkt->GetSize(), params);
3368 rxTime,
3370 phy,
3371 rxPkt,
3372 (rxTime < pktToA + Seconds(2)) ? rx1Frequency : rx2Frequency,
3374 params.spreadingFactor,
3375 -100,
3376 pktToA);
3377 }
3378
3379 // Connect trace sources
3380 phy->TraceConnectWithoutContext(
3381 "EndDeviceState",
3383 model->TraceConnectWithoutContext(
3384 "TotalEnergyConsumption",
3386
3387 // Set maximum simulation time
3388 Simulator::Stop(Seconds(1300));
3389}
3390
3391void
3396
3397void
3399{
3401 m_expectedStates.size() - 1,
3402 "Too many state transitions");
3405 "Unexpected previous state after transition");
3408 "Unexpected current state after transition");
3410}
3411
3412void
3414{
3415 NS_LOG_DEBUG("EnergyDepletionTest");
3416
3417 /* Pre-compute expected test values */
3418
3419 // LoRaWAN defaults
3420 auto params = LoraTxParameters();
3421 params.spreadingFactor = 12;
3422 params.lowDataRateOptimize = true;
3423 const double txPowerDbm = 14;
3424 const uint8_t rxWinSymN = 8;
3425
3426 const auto pktInterval = Seconds(1200);
3427 const uint32_t phyPayloadLen = 13; // empty lorawan packet
3428 const auto pktToA = LoraPhy::GetTimeOnAir(phyPayloadLen, params);
3429
3430 // Energy model parameters
3431 const double voltageV = 3.3;
3432 const double txEta = 0.452750;
3433 const double txBaseCurrentA = 0.014646;
3434 const double sleepCurrentA = 0.1e-6;
3435 const double rxCurrentA = 10.8e-3;
3436
3437 /// @see LinearLoraTxCurrentModel
3438 const double txCurrentA = DbmToW(txPowerDbm) / (voltageV * txEta) + txBaseCurrentA;
3439 const double txEnergy = txCurrentA * voltageV * pktToA.GetSeconds();
3440
3441 const auto rxWinTime = rxWinSymN * LoraPhy::GetTSym(params.spreadingFactor, params.bandwidthHz);
3442 const double rxWinEnergy = rxCurrentA * voltageV * rxWinTime.GetSeconds();
3443 const double rxEnergy = rxCurrentA * voltageV * pktToA.GetSeconds();
3444
3445 // between TX and RX1
3446 const auto sleepTime1 = Seconds(1);
3447 const double sleepEnergy1 = sleepCurrentA * voltageV * sleepTime1.GetSeconds();
3448 // between RX1 and RX2
3449 const auto sleepTime2 = Seconds(1) - rxWinTime;
3450 const double sleepEnergy2 = sleepCurrentA * voltageV * sleepTime2.GetSeconds();
3451 // between RX in RX1 and next TX
3452 const auto sleepTime3 = pktInterval - pktToA - Seconds(1) - .5 * rxWinTime - pktToA;
3453 const double sleepEnergy3 = sleepCurrentA * voltageV * sleepTime3.GetSeconds();
3454 // between RX in RX2 and next TX
3455 const auto sleepTime4 = pktInterval - pktToA - Seconds(2) - .5 * rxWinTime - pktToA;
3456 const double sleepEnergy4 = sleepCurrentA * voltageV * sleepTime4.GetSeconds();
3457 // between RX2 (no RX) and next TX
3458 const auto sleepTime5 = pktInterval - pktToA - Seconds(2) - rxWinTime;
3459 const double sleepEnergy5 = sleepCurrentA * voltageV * sleepTime3.GetSeconds();
3460
3461 static constexpr auto ENERGY_DEPLETION_SCHEDULING_TOLERANCE_J =
3463
3464 // Die during TX
3465 {
3466 const double initialEnergy = txEnergy / 2;
3467 const double lowBatteryTh = .1 * txEnergy / initialEnergy; // anything works
3469 State::STANDBY,
3470 State::SLEEP,
3471 State::TX,
3472 State::OFF,
3473 };
3474 Reset(initialEnergy, lowBatteryTh);
3477 m_expectedStates.size() - 1,
3478 "Unexpected number of state transitions");
3480 ENERGY_DEPLETION_SCHEDULING_TOLERANCE_J,
3481 "Unexpected energy consumption");
3482 }
3483
3484 // Low battery detected at TX end
3485 {
3486 const double initialEnergy = txEnergy + sleepEnergy1;
3487 const double lowBatteryTh = (txEnergy / 2 + sleepEnergy1) / initialEnergy;
3489 State::STANDBY,
3490 State::SLEEP,
3491 State::TX,
3492 State::STANDBY,
3493 State::OFF,
3494 };
3495 Reset(initialEnergy, lowBatteryTh);
3498 m_expectedStates.size() - 1,
3499 "Unexpected number of state transitions");
3501 initialEnergy * (1 - lowBatteryTh),
3502 "Unexpected energy consumption");
3503 }
3504
3505 // Die during SLEEP between TX and RX1
3506 {
3507 const double initialEnergy = txEnergy + sleepEnergy1 / 2;
3508 const double lowBatteryTh = .1 * sleepEnergy1 / initialEnergy;
3510 State::STANDBY,
3511 State::SLEEP,
3512 State::TX,
3513 State::STANDBY,
3514 State::SLEEP,
3515 State::OFF,
3516 };
3517 Reset(initialEnergy, lowBatteryTh);
3520 m_expectedStates.size() - 1,
3521 "Unexpected number of state transitions");
3523 ENERGY_DEPLETION_SCHEDULING_TOLERANCE_J,
3524 "Unexpected energy consumption");
3525 }
3526
3527 // Low battery detected at RX1 start
3528 {
3529 const double initialEnergy = txEnergy + sleepEnergy1 + rxWinEnergy;
3530 const double lowBatteryTh = (sleepEnergy1 / 2 + rxWinEnergy) / initialEnergy;
3532 State::STANDBY,
3533 State::SLEEP,
3534 State::TX,
3535 State::STANDBY,
3536 State::SLEEP,
3537 State::RX_ENABLED,
3538 State::OFF,
3539 };
3540 Reset(initialEnergy, lowBatteryTh);
3543 m_expectedStates.size() - 1,
3544 "Unexpected number of state transitions");
3546 initialEnergy * (1 - lowBatteryTh),
3547 "Unexpected energy consumption");
3548 }
3549
3550 // Die during RX1
3551 {
3552 const double initialEnergy = txEnergy + sleepEnergy1 + rxWinEnergy / 2;
3553 const double lowBatteryTh = .1 * rxWinEnergy / initialEnergy;
3555 State::STANDBY,
3556 State::SLEEP,
3557 State::TX,
3558 State::STANDBY,
3559 State::SLEEP,
3560 State::RX_ENABLED,
3561 State::OFF,
3562 };
3563 Reset(initialEnergy, lowBatteryTh);
3566 m_expectedStates.size() - 1,
3567 "Unexpected number of state transitions");
3569 ENERGY_DEPLETION_SCHEDULING_TOLERANCE_J,
3570 "Unexpected energy consumption");
3571 }
3572
3573 // Low battery detected upon preamble lock in RX1
3574 {
3575 const double initialEnergy = txEnergy + sleepEnergy1 + rxWinEnergy;
3576 const double lowBatteryTh = (rxWinEnergy / 2) / initialEnergy;
3577 const auto rxDelay = pktToA + Seconds(1) + .75 * rxWinTime;
3579 State::STANDBY,
3580 State::SLEEP,
3581 State::TX,
3582 State::STANDBY,
3583 State::SLEEP,
3584 State::RX_ENABLED,
3585 State::RX_ACTIVE,
3586 State::OFF,
3587 };
3588 Reset(initialEnergy, lowBatteryTh, rxDelay);
3591 m_expectedStates.size() - 1,
3592 "Unexpected number of state transitions");
3594 initialEnergy * (1 - lowBatteryTh),
3595 "Unexpected energy consumption");
3596 }
3597
3598 // Die during reception started in RX1
3599 {
3600 const double initialEnergy = txEnergy + sleepEnergy1 + .5 * rxWinEnergy + rxEnergy / 2;
3601 const double lowBatteryTh = .1 * rxEnergy / initialEnergy;
3602 const auto rxDelay = pktToA + Seconds(1) + .5 * rxWinTime;
3604 State::STANDBY,
3605 State::SLEEP,
3606 State::TX,
3607 State::STANDBY,
3608 State::SLEEP,
3609 State::RX_ENABLED,
3610 State::RX_ACTIVE,
3611 State::OFF,
3612 };
3613 Reset(initialEnergy, lowBatteryTh, rxDelay);
3616 m_expectedStates.size() - 1,
3617 "Unexpected number of state transitions");
3619 ENERGY_DEPLETION_SCHEDULING_TOLERANCE_J,
3620 "Unexpected energy consumption");
3621 }
3622
3623 // Low battery detected on RX termination (RX started in RX1)
3624 {
3625 const double initialEnergy =
3626 txEnergy + sleepEnergy1 + .5 * rxWinEnergy + rxEnergy + sleepEnergy3;
3627 const double lowBatteryTh = (rxEnergy / 2 + sleepEnergy3) / initialEnergy;
3628 const auto rxDelay = pktToA + Seconds(1) + .5 * rxWinTime;
3630 State::STANDBY,
3631 State::SLEEP,
3632 State::TX,
3633 State::STANDBY,
3634 State::SLEEP,
3635 State::RX_ENABLED,
3636 State::RX_ACTIVE,
3637 State::STANDBY,
3638 State::OFF,
3639 };
3640 Reset(initialEnergy, lowBatteryTh, rxDelay);
3643 m_expectedStates.size() - 1,
3644 "Unexpected number of state transitions");
3646 initialEnergy * (1 - lowBatteryTh),
3647 "Unexpected energy consumption");
3648 }
3649
3650 // Die during SLEEP after RX in RX1
3651 {
3652 const double initialEnergy =
3653 txEnergy + sleepEnergy1 + .5 * rxWinEnergy + rxEnergy + sleepEnergy3 / 2;
3654 const double lowBatteryTh = .1 * sleepEnergy3 / initialEnergy;
3655 const auto rxDelay = pktToA + Seconds(1) + .5 * rxWinTime;
3657 State::STANDBY,
3658 State::SLEEP,
3659 State::TX,
3660 State::STANDBY,
3661 State::SLEEP,
3662 State::RX_ENABLED,
3663 State::RX_ACTIVE,
3664 State::STANDBY,
3665 State::SLEEP,
3666 State::OFF,
3667 };
3668 Reset(initialEnergy, lowBatteryTh, rxDelay);
3671 m_expectedStates.size() - 1,
3672 "Unexpected number of state transitions");
3674 ENERGY_DEPLETION_SCHEDULING_TOLERANCE_J,
3675 "Unexpected energy consumption");
3676 }
3677
3678 // Low battery detected at RX1 end (no RX)
3679 {
3680 const double initialEnergy = txEnergy + sleepEnergy1 + rxWinEnergy + sleepEnergy2;
3681 const double lowBatteryTh = (rxWinEnergy / 2 + sleepEnergy2) / initialEnergy;
3683 State::STANDBY,
3684 State::SLEEP,
3685 State::TX,
3686 State::STANDBY,
3687 State::SLEEP,
3688 State::RX_ENABLED,
3689 State::STANDBY,
3690 State::OFF,
3691 };
3692 Reset(initialEnergy, lowBatteryTh);
3695 m_expectedStates.size() - 1,
3696 "Unexpected number of state transitions");
3698 initialEnergy * (1 - lowBatteryTh),
3699 "Unexpected energy consumption");
3700 }
3701
3702 // Die during SLEEP between RX1 and RX2
3703 {
3704 const double initialEnergy = txEnergy + sleepEnergy1 + rxWinEnergy + sleepEnergy2 / 2;
3705 const double lowBatteryTh = .1 * sleepEnergy2 / initialEnergy;
3707 State::STANDBY,
3708 State::SLEEP,
3709 State::TX,
3710 State::STANDBY,
3711 State::SLEEP,
3712 State::RX_ENABLED,
3713 State::STANDBY,
3714 State::SLEEP,
3715 State::OFF,
3716 };
3717 Reset(initialEnergy, lowBatteryTh);
3720 m_expectedStates.size() - 1,
3721 "Unexpected number of state transitions");
3723 ENERGY_DEPLETION_SCHEDULING_TOLERANCE_J,
3724 "Unexpected energy consumption");
3725 }
3726
3727 // Low battery detected at RX2 start
3728 {
3729 const double initialEnergy =
3730 txEnergy + sleepEnergy1 + rxWinEnergy + sleepEnergy2 + rxWinEnergy;
3731 const double lowBatteryTh = (sleepEnergy2 / 2 + rxWinEnergy) / initialEnergy;
3733 State::STANDBY,
3734 State::SLEEP,
3735 State::TX,
3736 State::STANDBY,
3737 State::SLEEP,
3738 State::RX_ENABLED,
3739 State::STANDBY,
3740 State::SLEEP,
3741 State::RX_ENABLED,
3742 State::OFF,
3743 };
3744 Reset(initialEnergy, lowBatteryTh);
3747 m_expectedStates.size() - 1,
3748 "Unexpected number of state transitions");
3750 initialEnergy * (1 - lowBatteryTh),
3751 "Unexpected energy consumption");
3752 }
3753
3754 // Low battery detected upon preamble lock in RX2
3755 {
3756 const double initialEnergy =
3757 txEnergy + sleepEnergy1 + rxWinEnergy + sleepEnergy2 + rxWinEnergy;
3758 const double lowBatteryTh = (rxWinEnergy / 2) / initialEnergy;
3759 const auto rxDelay = pktToA + Seconds(2) + .75 * rxWinTime;
3761 State::STANDBY,
3762 State::SLEEP,
3763 State::TX,
3764 State::STANDBY,
3765 State::SLEEP,
3766 State::RX_ENABLED,
3767 State::STANDBY,
3768 State::SLEEP,
3769 State::RX_ENABLED,
3770 State::RX_ACTIVE,
3771 State::OFF,
3772 };
3773 Reset(initialEnergy, lowBatteryTh, rxDelay);
3776 m_expectedStates.size() - 1,
3777 "Unexpected number of state transitions");
3779 initialEnergy * (1 - lowBatteryTh),
3780 "Unexpected energy consumption");
3781 }
3782
3783 // Die during reception started in RX2
3784 {
3785 const double initialEnergy =
3786 txEnergy + sleepEnergy1 + rxWinEnergy + sleepEnergy2 + .5 * rxWinEnergy + rxEnergy / 2;
3787 const double lowBatteryTh = .1 * rxEnergy / initialEnergy;
3788 const auto rxDelay = pktToA + Seconds(2) + .5 * rxWinTime;
3790 State::STANDBY,
3791 State::SLEEP,
3792 State::TX,
3793 State::STANDBY,
3794 State::SLEEP,
3795 State::RX_ENABLED,
3796 State::STANDBY,
3797 State::SLEEP,
3798 State::RX_ENABLED,
3799 State::RX_ACTIVE,
3800 State::OFF,
3801 };
3802 Reset(initialEnergy, lowBatteryTh, rxDelay);
3805 m_expectedStates.size() - 1,
3806 "Unexpected number of state transitions");
3808 ENERGY_DEPLETION_SCHEDULING_TOLERANCE_J,
3809 "Unexpected energy consumption");
3810 }
3811
3812 // Low battery detected on RX termination (RX started in RX2)
3813 {
3814 const double initialEnergy = txEnergy + sleepEnergy1 + rxWinEnergy + sleepEnergy2 +
3815 .5 * rxWinEnergy + rxEnergy + sleepEnergy4;
3816 const double lowBatteryTh = (rxEnergy / 2 + sleepEnergy4) / initialEnergy;
3817 const auto rxDelay = pktToA + Seconds(2) + .5 * rxWinTime;
3819 State::STANDBY,
3820 State::SLEEP,
3821 State::TX,
3822 State::STANDBY,
3823 State::SLEEP,
3824 State::RX_ENABLED,
3825 State::STANDBY,
3826 State::SLEEP,
3827 State::RX_ENABLED,
3828 State::RX_ACTIVE,
3829 State::STANDBY,
3830 State::OFF,
3831 };
3832 Reset(initialEnergy, lowBatteryTh, rxDelay);
3835 m_expectedStates.size() - 1,
3836 "Unexpected number of state transitions");
3838 initialEnergy * (1 - lowBatteryTh),
3839 "Unexpected energy consumption");
3840 }
3841
3842 // Die during SLEEP after RX in RX2
3843 {
3844 const double initialEnergy = txEnergy + sleepEnergy1 + rxWinEnergy + sleepEnergy2 +
3845 .5 * rxWinEnergy + rxEnergy + sleepEnergy4 / 2;
3846 const double lowBatteryTh = .1 * sleepEnergy4 / initialEnergy;
3847 const auto rxDelay = pktToA + Seconds(2) + .5 * rxWinTime;
3849 State::STANDBY,
3850 State::SLEEP,
3851 State::TX,
3852 State::STANDBY,
3853 State::SLEEP,
3854 State::RX_ENABLED,
3855 State::STANDBY,
3856 State::SLEEP,
3857 State::RX_ENABLED,
3858 State::RX_ACTIVE,
3859 State::STANDBY,
3860 State::SLEEP,
3861 State::OFF,
3862 };
3863 Reset(initialEnergy, lowBatteryTh, rxDelay);
3866 m_expectedStates.size() - 1,
3867 "Unexpected number of state transitions");
3869 ENERGY_DEPLETION_SCHEDULING_TOLERANCE_J,
3870 "Unexpected energy consumption");
3871 }
3872
3873 // Die during RX2 (no RX)
3874 {
3875 const double initialEnergy =
3876 txEnergy + sleepEnergy1 + rxWinEnergy + sleepEnergy2 + rxWinEnergy / 2;
3877 const double lowBatteryTh = .1 * rxWinEnergy / initialEnergy;
3879 State::STANDBY,
3880 State::SLEEP,
3881 State::TX,
3882 State::STANDBY,
3883 State::SLEEP,
3884 State::RX_ENABLED,
3885 State::STANDBY,
3886 State::SLEEP,
3887 State::RX_ENABLED,
3888 State::OFF,
3889 };
3890 Reset(initialEnergy, lowBatteryTh);
3893 m_expectedStates.size() - 1,
3894 "Unexpected number of state transitions");
3896 ENERGY_DEPLETION_SCHEDULING_TOLERANCE_J,
3897 "Unexpected energy consumption");
3898 }
3899
3900 // Low battery detected at RX2 end
3901 {
3902 const double initialEnergy =
3903 txEnergy + sleepEnergy1 + rxWinEnergy + sleepEnergy2 + rxWinEnergy + sleepEnergy5;
3904 const double lowBatteryTh = (rxWinEnergy / 2 + sleepEnergy5) / initialEnergy;
3906 State::STANDBY,
3907 State::SLEEP,
3908 State::TX,
3909 State::STANDBY,
3910 State::SLEEP,
3911 State::RX_ENABLED,
3912 State::STANDBY,
3913 State::SLEEP,
3914 State::RX_ENABLED,
3915 State::STANDBY,
3916 State::OFF,
3917 };
3918 Reset(initialEnergy, lowBatteryTh);
3921 m_expectedStates.size() - 1,
3922 "Unexpected number of state transitions");
3924 initialEnergy * (1 - lowBatteryTh),
3925 "Unexpected energy consumption");
3926 }
3927
3928 // Die during SLEEP
3929 {
3930 const double initialEnergy =
3931 txEnergy + sleepEnergy1 + rxWinEnergy + sleepEnergy2 + rxWinEnergy + sleepEnergy5 / 2;
3932 const double lowBatteryTh = .1 * sleepEnergy5 / initialEnergy;
3934 State::STANDBY,
3935 State::SLEEP,
3936 State::TX,
3937 State::STANDBY,
3938 State::SLEEP,
3939 State::RX_ENABLED,
3940 State::STANDBY,
3941 State::SLEEP,
3942 State::RX_ENABLED,
3943 State::STANDBY,
3944 State::SLEEP,
3945 State::OFF,
3946 };
3947 Reset(initialEnergy, lowBatteryTh);
3950 m_expectedStates.size() - 1,
3951 "Unexpected number of state transitions");
3953 ENERGY_DEPLETION_SCHEDULING_TOLERANCE_J,
3954 "Unexpected energy consumption");
3955 }
3956
3957 // Low battery detected at TX start
3958 {
3959 const double initialEnergy = txEnergy + sleepEnergy1 + rxWinEnergy + sleepEnergy2 +
3960 rxWinEnergy + sleepEnergy5 + .1 * txEnergy;
3961 const double lowBatteryTh = (sleepEnergy5 / 2 + .1 * txEnergy) / initialEnergy;
3963 State::STANDBY,
3964 State::SLEEP,
3965 State::TX,
3966 State::STANDBY,
3967 State::SLEEP,
3968 State::RX_ENABLED,
3969 State::STANDBY,
3970 State::SLEEP,
3971 State::RX_ENABLED,
3972 State::STANDBY,
3973 State::SLEEP,
3974 State::TX,
3975 State::OFF,
3976 };
3977 Reset(initialEnergy, lowBatteryTh);
3980 m_expectedStates.size() - 1,
3981 "Unexpected number of state transitions");
3983 initialEnergy * (1 - lowBatteryTh),
3984 "Unexpected energy consumption");
3985 }
3986}
3987
3988/**
3989 * @ingroup lorawan
3990 *
3991 * The TestSuite class names the TestSuite, identifies what type of TestSuite, and enables the
3992 * TestCases to be run. Typically, only the constructor for this class must be defined
3993 */
3995{
3996 public:
3997 LorawanTestSuite(); //!< Default constructor
3998};
3999
4001 : TestSuite("lorawan", Type::UNIT)
4002{
4003 // LogComponentEnable("LorawanTestSuite", LOG_LEVEL_DEBUG);
4004 // LogComponentEnable("LorawanMac", LOG_LEVEL_DEBUG);
4005 // LogComponentEnable("EndDeviceLorawanMac", LOG_LEVEL_DEBUG);
4006 // LogComponentEnable("ClassAEndDeviceLorawanMac", LOG_LEVEL_DEBUG);
4007 // LogComponentEnable("SimpleEndDeviceLoraPhy", LOG_LEVEL_DEBUG);
4008 // LogComponentEnable("EndDeviceLoraPhy", LOG_LEVEL_DEBUG);
4009 // LogComponentEnable("LoraPhy", LOG_LEVEL_DEBUG);
4010 // LogComponentEnable("LoraChannel", LOG_LEVEL_DEBUG);
4011 // LogComponentEnable("LoraFrameHeader", LOG_LEVEL_DEBUG);
4012 // LogComponentEnable("BasicEnergySource", LOG_LEVEL_DEBUG);
4013 // LogComponentEnable("LoraRadioEnergyModel", LOG_LEVEL_DEBUG);
4014 // LogComponentEnableAll(LOG_PREFIX_FUNC);
4015 // LogComponentEnableAll(LOG_PREFIX_NODE);
4016 // LogComponentEnableAll(LOG_PREFIX_TIME);
4017
4029}
4030
4031// Do not forget to allocate an instance of this TestSuite
It tests the correct execution of the ADR backoff procedure of LoRaWAN devices.
AdrBackoffTest()
Default constructor.
void DoRun() override
Implementation to actually run this TestCase.
Ptr< ClassAEndDeviceLorawanMac > m_mac
The end device's MAC layer used in tests.
~AdrBackoffTest() override
Destructor.
void ScheduleRx1Downlink(Time after)
Create and schedule the PHY reception of a downlink transmission configured for the LoRaWAN MAC first...
void Reset()
This function resets the simulation and device MAC layer, use before test sub-cases.
void SendUplink(Time after, LoraFrameHeader &fhdr)
Create and send an empty app payload unconfirmed frame through the MAC layer to increment of the FCnt...
It tests that LoRa device correctly turning OFF on energy depletion.
Ptr< Node > m_node
LoRaWAN end device node used in tests.
size_t m_currentDeviceStateIndex
Track current PHY state of the device.
EndDeviceLoraPhy::State State
PHY state.
std::vector< State > m_expectedStates
States the PHY must go through.
void OnTotalEnergyConsumptionChange(double prev, double curr)
Callback for tracing a device PHY's energy model energy consumption.
~EnergyDepletionTest() override
Destructor.
void OnEndDeviceStateChange(State prev, State curr)
Callback for tracing changes in the LoRa PHY state.
double m_totalEnergyConsumption
Track PHY energy consumption in Joules.
void Reset(double energyJ, double batteryTh, Time rxTime=Time())
Reset device for new sub test case.
void DoRun() override
Implementation to actually run this TestCase.
EnergyDepletionTest()
Default constructor.
It tests serialization/deserialization of LoRaWAN headers (the LorawanMacHeader and LoraFrameHeader c...
void DoRun() override
Implementation to actually run this TestCase.
HeaderTest()
Default constructor.
~HeaderTest() override
Destructor.
It tests interference computations in a number of possible scenarios using the LoraInterferenceHelper...
~InterferenceTest() override
Destructor.
void DoRun() override
Implementation to actually run this TestCase.
InterferenceTest()
Default constructor.
It tests functionality of the LogicalLoraChannel, SubBand and LogicalLoraChannelHelper classes.
LogicalLoraChannelTest()
Default constructor.
~LogicalLoraChannelTest() override
Destructor.
void DoRun() override
Implementation to actually run this TestCase.
It tests LoraDeviceAddress comparison operators overrides and generation of new addresses with LoraDe...
LorawanAddressTest()
Default constructor.
~LorawanAddressTest() override
Destructor.
void DoRun() override
Implementation to actually run this TestCase.
~LorawanMacTest() override
Destructor.
LorawanMacTest()
Default constructor.
void DoRun() override
Implementation to actually run this TestCase.
The TestSuite class names the TestSuite, identifies what type of TestSuite, and enables the TestCases...
LorawanTestSuite()
Default constructor.
It tests the functionalities of LoRaWAN MAC commands received by devices.
~MacCommandTest() override
Destructor.
MacCommandTest()
Default constructor.
void Reset()
This function resets the state of the MAC layer used for tests.
void DoRun() override
Implementation to actually run this TestCase.
Ptr< ClassAEndDeviceLorawanMac > m_mac
The end device's MAC layer used in tests.
std::vector< Ptr< MacCommand > > RunMacCommand(Ts &&... args)
Have this class' MAC layer receive a downlink packet carrying the input MAC command.
It tests sending packets over a LoRa physical channel between multiple devices and the resulting poss...
int m_interferenceCalls
Counter for LostPacketBecauseInterference calls.
void Reset()
Reset counters and end devices' PHYs for new sub test case.
Ptr< SimpleEndDeviceLoraPhy > edPhy2
The second end device's PHY layer used in tests.
void WrongFrequency(Ptr< const Packet > packet, uint32_t node)
Callback for tracing LostPacketBecauseWrongFrequency.
void DoRun() override
Implementation to actually run this TestCase.
void UnderSensitivity(Ptr< const Packet > packet, uint32_t node)
Callback for tracing LostPacketBecauseUnderSensitivity.
bool IsSamePacket(Ptr< Packet > packet1, Ptr< Packet > packet2)
Compare two packets to check if they are equal.
Ptr< SimpleEndDeviceLoraPhy > edPhy3
The third end device's PHY layer used in tests.
Ptr< SimpleEndDeviceLoraPhy > edPhy1
The first end device's PHY layer used in tests.
int m_wrongSfCalls
Counter for LostPacketBecauseWrongSpreadingFactor calls.
int m_wrongFrequencyCalls
Counter for LostPacketBecauseWrongFrequency calls.
~PhyConnectivityTest() override
Destructor.
int m_underSensitivityCalls
Counter for LostPacketBecauseUnderSensitivity calls.
int m_receivedPacketCalls
Counter for ReceivedPacket calls.
void WrongSf(Ptr< const Packet > packet, uint32_t node)
Callback for tracing LostPacketBecauseWrongSpreadingFactor.
Ptr< LoraChannel > channel
The LoRa channel used for tests.
PhyConnectivityTest()
Default constructor.
void Interference(Ptr< const Packet > packet, uint32_t node)
Callback for tracing LostPacketBecauseInterference.
Ptr< Packet > m_latestReceivedPacket
Pointer to track the last received packet.
void ReceivedPacket(Ptr< const Packet > packet, uint32_t node)
Callback for tracing ReceivedPacket.
It tests a number of cases related to SimpleGatewayLoraPhy's parallel reception paths.
~ReceivePathTest() override
Destructor.
void Reset(uint8_t rxPathNb)
Reset counters and gateway PHY for new sub test case.
ReceivePathTest()
Default constructor.
int m_receivedPacketCalls
Counter for ReceivedPacket calls.
void OccupiedReceptionPaths(int oldValue, int newValue)
Callback for tracing OccupiedReceptionPaths.
Ptr< SimpleGatewayLoraPhy > gatewayPhy
PHY layer of a gateway to be tested.
void ReceivedPacket(Ptr< const Packet > packet, uint32_t node)
Callback for tracing ReceivedPacket.
void Interference(Ptr< const Packet > packet, uint32_t node)
Callback for tracing LostPacketBecauseInterference.
void NoMoreDemodulators(Ptr< const Packet > packet, uint32_t node)
Callback for tracing LostPacketBecauseNoMoreReceivers.
void DoRun() override
Implementation to actually run this TestCase.
int m_noMoreDemodulatorsCalls
Counter for LostPacketBecauseNoMoreReceivers calls.
int m_interferenceCalls
Counter for LostPacketBecauseInterference calls.
int m_maxOccupiedReceptionPaths
Max number of concurrent OccupiedReceptionPaths.
It tests the correct execution of the retransmissions in LoRaWAN devices.
int m_macConfirmedTxOutcome
Counter for MacConfirmedTransmissionOutcome calls.
RetransmissionTest()
Default constructor.
int m_phyStartSendingCalls
Counter for PhyStartSending calls.
Ptr< Packet > m_packet
Target packet for tracing.
void DoRun() override
Implementation to actually run this TestCase.
Ptr< ClassAEndDeviceLorawanMac > m_mac
The end device's MAC layer used in tests.
int m_macSentNewPacketCalls
Counter for MacSentNewPacket calls.
uint8_t m_numTransmissions
Number of confirmed packet transmissions.
void PhyStartSending(Ptr< const Packet > packet, uint32_t node)
Callback for tracing PHY layer StartSending.
~RetransmissionTest() override
Destructor.
int m_phyReceivedPacketCalls
Counter for PhyReceivedPacket calls.
bool m_successfullyAcked
Acknowledgement of confirmed packet.
void SendUplink(LoraFrameHeader &fhdr)
Create and send an empty app payload unconfirmed frame through the MAC layer NbTrans times.
void PhyReceivedPacket(Ptr< const Packet > packet, uint32_t node)
Callback for tracing PHY layer ReceivedPacket.
void ScheduleRx1Downlink(Time after, bool ack=false)
Create and schedule the PHY reception of a downlink transmission configured for the LoRaWAN MAC first...
void MacConfirmedTransmissionOutcome(uint8_t txCount, bool ack, Time firstAttempt, Ptr< Packet > packet)
Callback for tracing the outcome of MAC layer's confirmed packet retransmission and acknowledgement.
void MacSentNewPacket(Ptr< const Packet > packet)
Callback for tracing MAC layer SentNewPacket.
void Reset()
This function resets the simulation and device MAC layer, use before test sub-cases.
It tests the correctness of the LoraPhy::GetTimeOnAir calculator against a number of pre-sourced time...
void DoRun() override
Implementation to actually run this TestCase.
~TimeOnAirTest() override
Destructor.
TimeOnAirTest()
Default constructor.
Creates a BasicEnergySource object.
void Set(std::string name, const AttributeValue &v) override
iterator in a Buffer instance
Definition buffer.h:109
automatically resized byte buffer
Definition buffer.h:103
void AddAtStart(uint32_t start)
Definition buffer.cc:303
Buffer::Iterator Begin() const
Definition buffer.h:1137
energy::DeviceEnergyModelContainer Install(Ptr< NetDevice > device, Ptr< energy::EnergySource > source) const
This class can be used to hold variables of floating point type such as 'double' or 'float'.
Definition double.h:31
energy::EnergySourceContainer Install(Ptr< Node > node) const
Smart pointer class similar to boost::intrusive_ptr.
Definition ptr.h:70
static EventId Schedule(const Time &delay, FUNC f, Ts &&... args)
Schedule an event to expire after delay.
Definition simulator.h:580
static void Destroy()
Execute the events scheduled with ScheduleDestroy().
Definition simulator.cc:125
static void ScheduleWithContext(uint32_t context, const Time &delay, FUNC f, Ts &&... args)
Schedule an event with the given context.
Definition simulator.h:597
static void Run()
Run the simulation.
Definition simulator.cc:161
static EventId ScheduleNow(FUNC f, Ts &&... args)
Schedule an event to expire Now.
Definition simulator.h:614
static void Stop()
Tell the Simulator the calling event should be the last one executed.
Definition simulator.cc:169
void AddTestCase(TestCase *testCase, Duration duration=Duration::QUICK)
Add an individual child TestCase to this test suite.
Definition test.cc:296
@ QUICK
Fast test.
Definition test.h:1057
TestCase(const TestCase &)=delete
Caller graph was not generated because of its size.
Type
Type of test.
Definition test.h:1271
TestSuite(std::string name, Type type=Type::UNIT)
Construct a new test suite.
Definition test.cc:494
Simulation virtual time values and global simulation resolution.
Definition nstime.h:95
double GetSeconds() const
Get an approximation of the time stored in this instance in the indicated unit.
Definition nstime.h:398
bool IsStrictlyPositive() const
Exactly equivalent to t > 0.
Definition nstime.h:341
static Time Max()
Maximum representable Time Not to be confused with Max(Time,Time).
Definition nstime.h:287
Ptr< DeviceEnergyModel > Get(uint32_t i) const
Get the i-th Ptr<DeviceEnergyModel> stored in this container.
Ptr< EnergySource > Get(uint32_t i) const
Get the i-th Ptr<EnergySource> stored in this container.
void ReceiveSingle(uint32_t frequencyHz, IQPolarity iqPolarity, uint8_t spreadingFactor, uint32_t bandwidthHz, uint8_t symbNumTimeout, RxTimeoutCallback rxTimeoutCallback)
This function starts a reception attempt that will time-out if no transmission preamble is detected.
Callback< void > RxTimeoutCallback
Type definition for a callback for when a packet reception hardware timeout expires.
State
An enumeration of the possible internal states of an EndDeviceLoraPhy.
@ STANDBY
The PHY layer is in standby mode.
static constexpr uint16_t ADR_ACK_DELAY
ADRACKCnt threshold for ADR backoff action.
void Send(Ptr< Packet > packet) override
Send a packet.
static constexpr uint16_t ADR_ACK_LIMIT
ADRACKCnt threshold for setting ADRACKReq.
This class generates sequential LoraDeviceAddress instances.
LoraDeviceAddress NextAddress()
Allocate the next LoraDeviceAddress.
LoraDeviceAddress GetNextAddress()
Get the LoraDeviceAddress that will be allocated upon a call to NextAddress.
This class represents the device address of a LoraWAN end device.
static LoraDeviceAddress Deserialize(const uint8_t buf[4])
Convert the input buffer into a new address.
void Serialize(uint8_t buf[4]) const
Convert this address to a buffer.
This class represents the Frame header (FHDR) used in a LoraWAN network.
std::vector< Ptr< MacCommand > > GetCommands()
Return a vector of pointers to all the MAC commands saved in this header.
bool GetAck() const
Get the value of the ACK bit field.
uint32_t Deserialize(Buffer::Iterator start) override
Deserialize the contents of the buffer into a LoraFrameHeader object.
void AddCommand(Ptr< MacCommand > macCommand)
Add a predefined command to the vector in this frame header.
void SetFCnt(uint16_t fCnt)
Set the FCnt value.
bool GetAdr() const
Get the value of the ADR bit field.
void SetAck(bool ack)
Set the value of the ACK bit field.
void SetAdr(bool adr)
Set the value of the ADR bit field.
void SetAddress(LoraDeviceAddress address)
Set the address.
uint16_t GetFCnt() const
Get the FCnt value.
bool GetAdrAckReq() const
Get the value of the ADRACKReq bit field.
void SetAsUplink()
State that this is an uplink message.
LoraDeviceAddress GetAddress() const
Get this header's device address value.
void Serialize(Buffer::Iterator start) const override
Serialize the header.
void AddLinkCheckAns(uint8_t margin, uint8_t gwCnt)
Add a LinkCheckAns command.
void SetAsDownlink()
State that this is a downlink message.
Helper for LoraPhy that manages interference calculations.
Time GetOverlapTime(Ptr< LoraInterferenceHelper::Event > event1, Ptr< LoraInterferenceHelper::Event > event2)
Compute the time duration in which two given events are overlapping.
Ptr< LoraInterferenceHelper::Event > Add(Time duration, double rxPower, uint8_t spreadingFactor, Ptr< Packet > packet, uint32_t frequencyHz)
Add an event to the InterferenceHelper.
void ClearAllEvents()
Delete all events in the LoraInterferenceHelper.
static CollisionMatrix collisionMatrix
Collision matrix type set by the constructor.
uint8_t IsDestroyedByInterference(Ptr< LoraInterferenceHelper::Event > event)
Determine whether the event was destroyed by interference or not.
static Time GetTimeOnAir(uint32_t phyPayloadLen, const LoraTxParameters &txParams)
Compute the total transmission time for a physical packet based on modulation parameters.
Definition lora-phy.cc:111
static Time GetTSym(uint8_t spreadingFactor, uint32_t bandwidthHz)
Compute the symbol time from spreading factor and bandwidth.
Definition lora-phy.cc:103
Installs LoraRadioEnergyModel on devices.
void Set(std::string name, const AttributeValue &v) override
void SetTxCurrentModel(std::string name, Ts &&... args)
static constexpr double ENERGY_EPSILON_J
Small constant in Joules, subtracted from remaining energy of the source while scheduling for the fut...
This class represents the Mac header of a LoRaWAN packet.
void SetMajor(uint8_t major)
Set the major version of this header.
uint32_t Deserialize(Buffer::Iterator start) override
Deserialize the header.
void SetFType(enum FType fType)
Set the frame type.
FType GetFType() const
Get the frame type from the header.
void Serialize(Buffer::Iterator start) const override
Serialize the header.
uint8_t GetMajor() const
Get the major version from the header.
Helper class for configuring and installing the LorawanMac class on devices and gateways.
void SetDeviceType(enum DeviceType dt)
Set the kind of MAC this helper will create.
void SetRegion(enum Regions region)
Set the region in which the device is to operate.
Ptr< LorawanMac > Install(Ptr< Node > node, Ptr< NetDevice > device) const
Create the LorawanMac instance and connect it to a device.
void StartReceive(Ptr< Packet > packet, uint32_t frequencyHz, IQPolarity iqPolarity, uint8_t spreadingFactor, double rxPowerDbm, Time duration) override
Start receiving a packet.
void Send(Ptr< Packet > packet, uint32_t frequencyHz, IQPolarity iqPolarity, const LoraTxParameters &txParams, double txPowerDbm) override
Instruct the PHY to send a packet according to some parameters.
void StartReceive(Ptr< Packet > packet, uint32_t frequencyHz, IQPolarity iqPolarity, uint8_t spreadingFactor, double rxPowerDbm, Time duration) override
Start receiving a packet.
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:690
#define NS_LOG_COMPONENT_DEFINE(name)
Define a Log component with a specific name.
Definition log.h:201
#define NS_LOG_DEBUG(msg)
Use NS_LOG to output a message of level LOG_DEBUG.
Definition log.h:267
#define NS_LOG_LOGIC(msg)
Use NS_LOG to output a message of level LOG_LOGIC.
Definition log.h:281
#define NS_LOG_FUNCTION(parameters)
If log level LOG_FUNCTION is enabled, this macro will output all input parameters separated by ",...
@ CR_4_5
Coding rate 4/5.
Definition lora-phy.h:50
@ CR_4_6
Coding rate 4/6.
Definition lora-phy.h:51
@ DOWN
Downlink / Downchirp / Inverted polarity.
Definition lora-phy.h:35
@ UP
Uplink / Upchirp / Normal polarity.
Definition lora-phy.h:34
Ptr< T > CreateObject(Args &&... args)
Create an object by type, with varying number of constructor parameters.
Definition object.h:627
Ptr< T > Create(Ts &&... args)
Create class instances by constructors with varying numbers of arguments and return them by Ptr.
Definition ptr.h:492
#define NS_TEST_EXPECT_MSG_GT_OR_EQ(actual, limit, msg)
Test that an actual value is greater than or equal to limit and report if not.
Definition test.h:985
#define NS_TEST_ASSERT_MSG_EQ(actual, limit, msg)
Test that an actual and expected (limit) value are equal and report and abort if not.
Definition test.h:133
#define NS_TEST_EXPECT_MSG_LT(actual, limit, msg)
Test that an actual value is less than a limit and report if not.
Definition test.h:779
#define NS_TEST_EXPECT_MSG_NE(actual, limit, msg)
Test that an actual and expected (limit) value are not equal and report if not.
Definition test.h:655
#define NS_TEST_EXPECT_MSG_EQ(actual, limit, msg)
Test that an actual and expected (limit) value are equal and report if not.
Definition test.h:240
#define NS_TEST_ASSERT_MSG_NE(actual, limit, msg)
Test that an actual and expected (limit) value are not equal and report and abort if not.
Definition test.h:553
#define NS_TEST_EXPECT_MSG_EQ_TOL(actual, limit, tol, msg)
Test that actual and expected (limit) values are equal to plus or minus some tolerance and report if ...
Definition test.h:499
Time NanoSeconds(uint64_t value)
Construct a Time in the indicated unit.
Definition nstime.h:1364
Time Seconds(double value)
Construct a Time in the indicated unit.
Definition nstime.h:1313
Time Hours(double value)
Construct a Time in the indicated unit.
Definition nstime.h:1284
Time Minutes(double value)
Construct a Time in the indicated unit.
Definition nstime.h:1296
Time MilliSeconds(uint64_t value)
Construct a Time in the indicated unit.
Definition nstime.h:1330
static LorawanTestSuite lorawanTestSuite
double DbmToW(double dBm)
Convert from dBm to Watts.
Definition lora-utils.cc:26
Every class exported by the ns3 library is enclosed in the ns3 namespace.
Ptr< T1 > DynamicCast(const Ptr< T2 > &p)
Cast a Ptr.
Definition ptr.h:643
Structure to collect all parameters that are used to compute the duration of a packet (excluding payl...
Definition lora-phy.h:73
CodingRate codingRate
Transmission coding rate.
Definition lora-phy.h:77
uint32_t bandwidthHz
Transmission bandwidth in Hz.
Definition lora-phy.h:76
bool implicitHeader
Whether to use implicit header mode.
Definition lora-phy.h:81
uint8_t spreadingFactor
Symbol Spreading Factor (SF).
Definition lora-phy.h:75
bool crcEnabled
Whether Cyclic Redundancy Check (CRC) is enabled.
Definition lora-phy.h:82
bool lowDataRateOptimize
Low Data Rate Optimization (mandated for SF11 and SF12).
Definition lora-phy.h:78
uint16_t preambleLenSymb
Number of symbols in the packet preamble.
Definition lora-phy.h:80
uint32_t prev