File: tracing.rst

package info (click to toggle)
ns3 3.17%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 95,192 kB
  • ctags: 56,763
  • sloc: cpp: 324,361; python: 291,824; perl: 8,720; ansic: 2,097; xml: 2,000; makefile: 1,447; sh: 458; cs: 89
file content (4448 lines) | stat: -rw-r--r-- 225,711 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
.. include:: replace.txt

..
	========================================================================================
	Translated for portuguese by the students of the inter-institutional doctorate program of IME-USP/UTFPR-CM.
	
	Traduzido para o portugus pelos alunos do programa de doutorado inter institucional do Instituto de Matemtica e Estatstica da Universidade de So Paulo --- IME-USP em parceria com a Universidade Tecnolgica Federal do Paran - Campus Campo Mouro --- UTFPR-CM:
	
	* Frank Helbert (frank@ime.usp.br);
	* Luiz Arthur Feitosa dos Santos (luizsan@ime.usp.br);
	* Rodrigo Campiolo (campiolo@ime.usp.br).
	========================================================================================

..
	Tracing

Rastreamento
------------

..
	Background

Introduo
**********

..
	As mentioned in the Using the Tracing System section, the whole point of running
	an |ns3| simulation is to generate output for study.  You have two basic 
	strategies to work with in |ns3|: using generic pre-defined bulk output 
	mechanisms and parsing their content to extract interesting information; or 
	somehow developing an output mechanism that conveys exactly (and perhaps only) 
	the information wanted.

Como abordado na seo Usando o Sistema de Rastreamento, o objetivo principal de uma
simulao no |ns3|  a gerao de sada para estudo. H duas estratgias bsicas: 
usar mecanismos predefinidos de sada e processar o contedo para extrair informaes
relevantes; ou desenvolver mecanismos de sada que resultam somente ou exatamente na
informao pretendida.

..
	Using pre-defined bulk output mechanisms has the advantage of not requiring any
	changes to |ns3|, but it does require programming.  Often, pcap or NS_LOG
	output messages are gathered during simulation runs and separately run through 
	scripts that use grep, sed or awk to parse the messages and reduce and transform
	the data to a manageable form.  Programs must be written to do the 
	transformation, so this does not come for free.  Of course, if the information
	of interest in does not exist in any of the pre-defined output mechanisms,
	this approach fails.

Usar mecanismos predefinidos de sada possui a vantagem de no necessitar modificaes 
no |ns3|, mas requer programao. Geralmente, as mensagens de sada do pcap ou ``NS_LOG``
so coletadas durante a execuo da simulao e processadas separadamente por cdigos (`scripts`) que usam `grep`, `sed` ou `awk` para reduzir e transformar os dados para uma forma mais simples de gerenciar. H o custo do desenvolvimento de programas para realizar as transformaes e em algumas situaes a informao de interesse pode no estar contida em nenhuma das sadas, logo, a abordagem falha.

..
	If you need to add some tidbit of information to the pre-defined bulk mechanisms,
	this can certainly be done; and if you use one of the |ns3| mechanisms, 
	you may get your code added as a contribution.

Se precisarmos adicionar o mnimo de informao para os mecanismos predefinidos de sada, isto certamente pode ser feito e se usarmos os mecanismos do |ns3|, podemos
ter nosso cdigo adicionado como uma contribuio.

..
	|ns3| provides another mechanism, called Tracing, that avoids some of the 
	problems inherent in the bulk output mechanisms.  It has several important 
	advantages.  First, you can reduce the amount of data you have to manage by only
	tracing the events of interest to you (for large simulations, dumping everything
	to disk for post-processing can create I/O bottlenecks).  Second, if you use this
	method, you can control the format of the output directly so you avoid the 
	postprocessing step with sed or awk script.  If you desire, your output can be 
	formatted directly into a form acceptable by gnuplot, for example.  You can add 
	hooks in the core which can then be accessed by other users, but which will 
	produce no information unless explicitly asked to do so.  For these reasons, we 
	believe that the |ns3| tracing system is the best way to get information 
	out of a simulation and is also therefore one of the most important mechanisms
	to understand in |ns3|.

O |ns3| fornece outro mecanismo, chamado Rastreamento (*Tracing*), que evita alguns dos
problemas associados com os mecanismos de sada predefinidos. H vrias vantagens. Primeiro, reduo da quantidade de dados para gerenciar (em simulaes grandes, armazenar toda sada no disco pode gerar gargalos de Entrada/Sada). Segundo, o formato da sada pode ser controlado diretamente evitando o ps-processamento com cdigos `sed` ou `awk`. Se desejar,
a sada pode ser processada diretamente para um formato reconhecido pelo `gnuplot`, por exemplo. Podemos adicionar ganchos ("`hooks`") no ncleo, os quais podem ser acessados por outros usurios, mas que no produziro nenhuma informao exceto que sejam explicitamente solicitados a produzir. Por essas razes, acreditamos que o sistema de rastreamento do |ns3|  a melhor forma de obter informaes fora da simulao, portanto  um dos mais importantes mecanismos para ser compreendido no |ns3|.

..
	Blunt Instruments

Mtodos Simples
+++++++++++++++

..
	There are many ways to get information out of a program.  The most 
	straightforward way is to just directly print the information to the standard 
	output, as in,

H vrias formas de obter informao aps a finalizao de um programa. A mais direta
 imprimir a informao na sada padro, como no exemplo,

::

  #include <iostream>
  ...
  void
  SomeFunction (void)
  {
    uint32_t x = SOME_INTERESTING_VALUE;
    ...
    std::cout << "The value of x is " << x << std::endl;
    ...
  } 

..
	Nobody is going to prevent you from going deep into the core of |ns3| and
	adding print statements.  This is insanely easy to do and, after all, you have 
	complete control of your own |ns3| branch.  This will probably not turn 
	out to be very satisfactory in the long term, though.

Ningum impedir que editemos o ncleo do |ns3| e adicionemos cdigos de impresso. Isto  simples de fazer, alm disso temos controle e acesso total ao cdigo fonte do |ns3|. Entretanto, pensando no futuro, isto no  muito interessante.

..
	As the number of print statements increases in your programs, the task of 
	dealing with the large number of outputs will become more and more complicated.  
	Eventually, you may feel the need to control what information is being printed 
	in some way; perhaps by turning on and off certain categories of prints, or 
	increasing or decreasing the amount of information you want.  If you continue 
	down this path you may discover that you have re-implemented the ``NS_LOG``
	mechanism.  In order to avoid that, one of the first things you might consider
	is using ``NS_LOG`` itself.

Conforme aumentarmos o nmero de comandos de impresso em nossos programas, ficar mais difcil tratar a grande quantidade de sadas. Eventualmente, precisaremos controlar de alguma maneira qual a informao ser impressa; talvez habilitando ou no determinadas categorias de sadas, ou aumentando ou diminuindo a quantidade de informao desejada. Se continuarmos com esse processo, descobriremos depois de um tempo que, reimplementamos o mecanismo ``NS_LOG``. Para evitar isso, utilize o prprio ``NS_LOG``.

..
	We mentioned above that one way to get information out of |ns3| is to 
	parse existing NS_LOG output for interesting information.  If you discover that 
	some tidbit of information you need is not present in existing log output, you 
	could edit the core of |ns3| and simply add your interesting information
	to the output stream.  Now, this is certainly better than adding your own
	print statements since it follows |ns3| coding conventions and could 
	potentially be useful to other people as a patch to the existing core.

Como abordado anteriormente, uma maneira de obter informao de sada do |ns3|  
processar a sada do ``NS_LOG``, filtrando as informaes relevantes. Se a informao
no est presente nos registros existentes, pode-se editar o ncleo do |ns3| e 
adicionar ao fluxo de sada a informao desejada. Claro, isto  muito melhor
que adicionar comandos de impresso, desde que seguindo as convenes de codificao
do |ns3|, alm do que isto poderia ser potencialmente til a outras pessoas.

..
	Let's pick a random example.  If you wanted to add more logging to the 
	|ns3| TCP socket (``tcp-socket-base.cc``) you could just add a new 
	message down in the implementation.  Notice that in TcpSocketBase::ReceivedAck()
	there is no log message for the no ack case.  You could simply add one, 
	changing the code from:

Vamos analisar um exemplo, adicionando mais informaes de registro ao `socket` TCP do arquivo ``tcp-socket-base.cc``, para isto vamos acrescentando uma nova mensagem de registro na implementao. Observe que em ``TcpSocketBase::ReceivedAck()`` no existem mensagem de registro para casos sem o ACK, ento vamos adicionar uma da seguinte forma:

::

  /** Processa o mais recente ACK recebido */
  void
  TcpSocketBase::ReceivedAck (Ptr<Packet> packet, const TcpHeader& tcpHeader)
  {
    NS_LOG_FUNCTION (this << tcpHeader);

    // ACK Recebido. Compara o nmero ACK com o mais alto seqno no confirmado
    if (0 == (tcpHeader.GetFlags () & TcpHeader::ACK))
      { // Ignora se no h flag ACK 
      }
    ...

.. 
	to add a new ``NS_LOG_LOGIC`` in the appropriate statement:

para adicionar um novo ``NS_LOG_LOGIC`` na sentena apropriada:

::

  /** Processa o mais recente ACK recebido */
  void
  TcpSocketBase::ReceivedAck (Ptr<Packet> packet, const TcpHeader& tcpHeader)
  {
    NS_LOG_FUNCTION (this << tcpHeader);

    // ACK Recebido. Compara o nmero ACK com o mais alto seqno no confirmado
    if (0 == (tcpHeader.GetFlags () & TcpHeader::ACK))
      { // Ignora se no h flag ACK 
        NS_LOG_LOGIC ("TcpSocketBase " << this << " sem flag ACK");
      }
    ...

..
	This may seem fairly simple and satisfying at first glance, but something to
	consider is that you will be writing code to add the ``NS_LOG`` statement 
	and you will also have to write code (as in grep, sed or awk scripts) to parse
	the log output in order to isolate your information.  This is because even 
	though you have some control over what is output by the logging system, you 
	only have control down to the log component level.  

Isto pode parecer simples e satisfatrio a primeira vista, mas lembre-se que ns escreveremos
cdigo para adicionar ao ``NS_LOG`` e para processar a sada com a finalidade de isolar
a informao de interesse. Isto porque o controle  limitado ao nvel do componente de registro.

..
	If you are adding code to an existing module, you will also have to live with the
	output that every other developer has found interesting.  You may find that in 
	order to get the small amount of information you need, you may have to wade 
	through huge amounts of extraneous messages that are of no interest to you.  You
	may be forced to save huge log files to disk and process them down to a few lines
	whenever you want to do anything.

Se cada desenvolvedor adicionar cdigos de sada para um mdulo existente, logo conviveremos com a sada que outro desenvolvedor achou interessante.  descobriremos que para obter uma pequena quantidade de informao, precisaremos produzir uma volumosa quantidade de mensagens sem nenhuma relevncia (devido aos comandos de sada de vrios desenvolvedores). Assim seremos forados a gerar arquivos de registros gigantescos no disco e process-los para obter poucas linhas de nosso interesse.

..
	Since there are no guarantees in |ns3| about the stability of ``NS_LOG``
	output, you may also discover that pieces of log output on which you depend 
	disappear or change between releases.  If you depend on the structure of the 
	output, you may find other messages being added or deleted which may affect your
	parsing code.

Como no h nenhuma garantia no |ns3| sobre a estabilidade da sada do ``NS_LOG``, podemos descobrir que partes do registro de sada, que dependamos, desapareceram ou mudaram entre verses. Se dependermos da estrutura da sada, podemos encontrar outras mensagens sendo adicionadas ou removidas que podem afetar seu cdigo de processamento.

..
	For these reasons, we consider prints to ``std::cout`` and NS_LOG messages 
	to be quick and dirty ways to get more information out of |ns3|.

Por estas razes, devemos considerar o uso do ``std::cout`` e as mensagens ``NS_LOG`` como formas rpidas e porm sujas de obter informao da sada no |ns3|.

..
	It is desirable to have a stable facility using stable APIs that allow one to 
	reach into the core system and only get the information required.  It is
	desirable to be able to do this without having to change and recompile the
	core system.  Even better would be a system that notified the user when an item
	of interest changed or an interesting event happened so the user doesn't have 
	to actively poke around in the system looking for things.

Na grande maioria dos casos desejamos ter um mecanismo estvel, usando APIs que permitam acessar o ncleo do sistema e obter somente informaes interessantes. Isto deve ser possvel sem que exista a necessidade de alterar e recompilar o ncleo do sistema. Melhor ainda seria se um sistema notificasse o usurio quando um item de interesse fora modificado ou um evento de interesse aconteceu, pois o usurio no teria que constantemente vasculhar o sistema procurando por coisas.

..
	The |ns3| tracing system is designed to work along those lines and is 
	well-integrated with the Attribute and Config subsystems allowing for relatively
	simple use scenarios.

O sistema de rastreamento do |ns3|  projetado para trabalhar seguindo essas premissas e  
integrado com os subsistemas de Atributos (*Attribute*) e Configurao (*Config*) permitindo cenrios de uso simples.

.. 
	Overview

Viso Geral
***********

..
	The ns-3 tracing system is built on the concepts of independent tracing sources
	and tracing sinks; along with a uniform mechanism for connecting sources to sinks.

O sistema de rastreamento do |ns3|  baseado no conceito independente origem do rastreamento e destino do rastreamento. O |ns3| utiliza um mecanismo uniforme para conectar origens a destinos.

..
	Trace sources are entities that can signal events that happen in a simulation and 
	provide access to interesting underlying data.  For example, a trace source could
	indicate when a packet is received by a net device and provide access to the 
	packet contents for interested trace sinks.  A trace source might also indicate 
	when an interesting state change happens in a model.  For example, the congestion
	window of a TCP model is a prime candidate for a trace source.

As origens do rastreamento (*trace source*) so entidades que podem assinalar eventos que ocorrem na simulao e fornecem acesso a dados de baixo nvel. Por exemplo, uma origem do rastreamento poderia indicar quando um pacote  recebido por um dispositivo de rede e prove acesso ao contedo do pacote aos interessados no destino do rastreamento. Uma origem do rastreamento pode tambm indicar quando uma mudana de estado ocorre em um modelo. Por exemplo, a janela de congestionamento do modelo TCP  um forte candidato para uma origem do rastreamento.

..
	Trace sources are not useful by themselves; they must be connected to other pieces
	of code that actually do something useful with the information provided by the source.
	The entities that consume trace information are called trace sinks.  Trace sources 
	are generators of events and trace sinks are consumers.  This explicit division 
	allows for large numbers of trace sources to be scattered around the system in 
	places which model authors believe might be useful.  

A origem do rastreamento no so teis sozinhas; elas devem ser conectadas a outras partes de cdigo que fazem algo til com a informao provida pela origem. As entidades que consomem a informao de rastreamento so chamadas de destino do rastreamento (*trace sinks*). As origens de rastreamento so geradores de eventos e destinos de rastreamento so consumidores. Esta diviso explcita permite que inmeras origens de rastreamento estejam dispersas no sistema em locais que os autores do modelo acreditam ser teis.

..
	There can be zero or more consumers of trace events generated by a trace source.  
	One can think of a trace source as a kind of point-to-multipoint information link.  
	Your code looking for trace events from a particular piece of core code could 
	happily coexist with other code doing something entirely different from the same
	information.

Pode haver zero ou mais consumidores de eventos de rastreamento gerados por uma origem do rastreamento. Podemos pensar em uma origem do rastreamento como um tipo de ligao de informao ponto-para-multiponto. Seu cdigo buscaria por eventos de rastreamento de uma parte especfica do cdigo do ncleo e poderia coexistir com outro cdigo que faz algo inteiramente diferente com a mesma informao.

..
	Unless a user connects a trace sink to one of these sources, nothing is output.  By
	using the tracing system, both you and other people at the same trace source are 
	getting exactly what they want and only what they want out of the system.  Neither
	of you are impacting any other user by changing what information is output by the 
	system.  If you happen to add a trace source, your work as a good open-source 
	citizen may allow other users to provide new utilities that are perhaps very useful
	overall, without making any changes to the |ns3| core.  

Ao menos que um usurio conecte um destino do rastreamento a uma destas origens, nenhuma sada  produzida. Usando o sistema de rastreamento, todos conectados em uma mesma origem do rastreamento esto obtendo a informao que desejam do sistema. Um usurio no afeta os outros alterando a informao provida pela origem. Se acontecer de adicionarmos uma origem do rastreamento, seu trabalho como um bom cidado utilizador de cdigo livre pode permitir que outros usurios forneam novas utilidades para todos, sem fazer qualquer modificao no ncleo do |ns3|.
	
.. 
	A Simple Low-Level Example

Um Exemplo Simples de Baixo Nvel
+++++++++++++++++++++++++++++++++

..
	Let's take a few minutes and walk through a simple tracing example.  We are going
	to need a little background on Callbacks to understand what is happening in the
	example, so we have to take a small detour right away.

Vamos gastar alguns minutos para entender um exemplo de rastreamento simples. Primeiramente
precisamos compreender o conceito de *callbacks* para entender o que est acontecendo
no exemplo.

*Callbacks*
~~~~~~~~~~~

..
	The goal of the Callback system in |ns3| is to allow one piece of code to 
	call a function (or method in C++) without any specific inter-module dependency.
	This ultimately means you need some kind of indirection -- you treat the address
	of the called function as a variable.  This variable is called a pointer-to-function
	variable.  The relationship between function and pointer-to-function pointer is 
	really no different that that of object and pointer-to-object.

O objetivo do sistema de *Callback*, no |ns3|,  permitir a uma parte do cdigo invocar
uma funo (ou mtodo em C++) sem qualquer dependncia entre mdulos. Isto  utilizado para prover algum tipo de indireo -- desta forma tratamos o endereo da chamada de funo como uma varivel. Esta varivel  denominada varivel de ponteiro-para-funo. O relacionamento entre funo e ponteiro-para-funo no  to diferente que de um objeto e ponteiro-para-objeto.

..
	In C the canonical example of a pointer-to-function is a 
	pointer-to-function-returning-integer (PFI).  For a PFI taking one int parameter,
	this could be declared like,

Em C, o exemplo clssico de um ponteiro-para-funo  um ponteiro-para-funo-retornando-inteiro (PFI). Para um PFI ter um parmetro inteiro, poderia ser declarado como,

::

  int (*pfi)(int arg) = 0;

..
	What you get from this is a variable named simply "pfi" that is initialized
	to the value 0.  If you want to initialize this pointer to something meaningful,
	you have to have a function with a matching signature.  In this case, you could
	provide a function that looks like,

O cdigo descreve uma varivel nomeada como "pfi" que  inicializada com o valor 0. Se quisermos inicializar este ponteiro com um valor significante, temos que ter uma funo com uma assinatura idntica. Neste caso, poderamos prover uma funo como,

::

  int MyFunction (int arg) {}

..
	If you have this target, you can initialize the variable to point to your
	function:

Dessa forma, podemos inicializar a varivel apontando para uma funo:

::

  pfi = MyFunction;

..
	You can then call MyFunction indirectly using the more suggestive form of
	the call,

Podemos ento chamar ``MyFunction`` indiretamente, usando uma forma mais clara da chamada,

::

  int result = (*pfi) (1234);

..
	This is suggestive since it looks like you are dereferencing the function
	pointer just like you would dereference any pointer.  Typically, however,
	people take advantage of the fact that the compiler knows what is going on
	and will just use a shorter form,

 uma forma mais clara, pois  como se estivssemos dereferenciando o ponteiro da funo como dereferenciamos qualquer outro ponteiro. Tipicamente, todavia, usa-se uma forma mais curta pois o compilador sabe o que est fazendo,

::

  int result = pfi (1234);

..
	This looks like you are calling a function named "pfi," but the compiler is
	smart enough to know to call through the variable ``pfi`` indirectly to
	the function ``MyFunction``.

Esta forma  como se estivessemos chamando uma funo nomeada "pfi", mas o compilador reconhece que  uma chamada indireta da funo ``MyFunction`` por meio da varivel ``pfi``.

..
	Conceptually, this is almost exactly how the tracing system will work.
	Basically, a trace source *is* a callback.  When a trace sink expresses
	interest in receiving trace events, it adds a Callback to a list of Callbacks
	internally held by the trace source.  When an interesting event happens, the 
	trace source invokes its ``operator()`` providing zero or more parameters.
	The ``operator()`` eventually wanders down into the system and does something
	remarkably like the indirect call you just saw.  It provides zero or more 
	parameters (the call to "pfi" above passed one parameter to the target function
	``MyFunction``.

Conceitualmente,  quase exatamente como o sistema de rastreamento funciona. Basicamente, uma origem do rastreamento ** um *callback*. Quando um destino do rastreamento expressa interesse em receber eventos de rastreamento, ela adiciona a *callback* para a lista de *callbacks*  mantida internamente pela origem do rastreamento. Quando um evento de interesse ocorre, a origem do rastreamento invoca seu ``operator()`` provendo zero ou mais parmetros. O ``operator()`` eventualmente percorre o sistema e faz uma chamada indireta com zero ou mais parmetros.
	
..
	The important difference that the tracing system adds is that for each trace
	source there is an internal list of Callbacks.  Instead of just making one 
	indirect call, a trace source may invoke any number of Callbacks.  When a trace
	sink expresses interest in notifications from a trace source, it basically just
	arranges to add its own function to the callback list.

Uma diferena importante  que o sistema de rastreamento adiciona para cada origem do rastreamento uma lista interna de *callbacks*. Ao invs de apenas fazer uma chamada indireta, uma origem do rastreamento pode invocar qualquer nmero de *callbacks*. Quando um destino do rastreamento expressa interesse em notificaes de uma origem, ela adiciona sua prpria funo para a lista de *callback*.

..
	If you are interested in more details about how this is actually arranged in 
	|ns3|, feel free to peruse the Callback section of the manual.

Estando interessado em mais detalhes sobre como  organizado o sistema de *callback* no |ns3|, leia a seo *Callback* do manual.

.. 
	Example Code

Cdigo de Exemplo
~~~~~~~~~~~~~~~~~

..
	We have provided some code to implement what is really the simplest example
	of tracing that can be assembled.  You can find this code in the tutorial
	directory as ``fourth.cc``.  Let's walk through it.

Analisaremos uma implementao simples de um exemplo de rastreamento. Este cdigo est no diretrio do tutorial, no arquivo ``fourth.cc``.

::

  /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
  /*
   * This program is free software; you can redistribute it and/or modify
   * it under the terms of the GNU General Public License version 2 as
   * published by the Free Software Foundation;
   *
   * This program is distributed in the hope that it will be useful,
   * but WITHOUT ANY WARRANTY; without even the implied warranty of
   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   * GNU General Public License for more details.
   *
   * You should have received a copy of the GNU General Public License
   * along with this program; if not, write to the Free Software
   * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   */
  
  #include "ns3/object.h"
  #include "ns3/uinteger.h"
  #include "ns3/traced-value.h"
  #include "ns3/trace-source-accessor.h"
  
  #include <iostream>
  
  using namespace ns3;

..
	Most of this code should be quite familiar to you.  As mentioned above, the
	trace system makes heavy use of the Object and Attribute systems, so you will 
	need to include them.  The first two includes above bring in the declarations
	for those systems explicitly.  You could use the core module header, but this
	illustrates how simple this all really is.  

A maior parte deste cdigo deve ser familiar, pois como j abordado, o sistema de rastreamento faz uso constante dos sistemas Objeto (*Object*) e Atributos (*Attribute*), logo  necessrio inclu-los. As duas primeiras incluses (*include*) declaram explicitamente estes dois sistemas. Poderamos usar o cabealho (*header*) do mdulo ncleo, este exemplo  simples.

..
	The file, ``traced-value.h`` brings in the required declarations for tracing
	of data that obeys value semantics.  In general, value semantics just means that
	you can pass the object around, not an address.  In order to use value semantics
	at all you have to have an object with an associated copy constructor and 
	assignment operator available.  We extend the requirements to talk about the set
	of operators that are pre-defined for plain-old-data (POD) types.  Operator=, 
	operator++, operator---, operator+, operator==, etc.

O arquivo ``traced-value.h``  uma declarao obrigatria para rastreamento de dados que usam passagem por valor. Na passagem por valor  passada uma cpia do objeto e no um endereo. Com a finalidade de usar passagem por valor, precisa-se de um objeto com um construtor de cpia associado e um operador de atribuio. O conjunto de operadores predefinidos para tipos de dados primitivos (*plain-old-data*) so ++, ---, +, ==, etc.

..
	What this all really means is that you will be able to trace changes to a C++
	object made using those operators.

Isto significa que somos capazes de rastrear alteraes em um objeto C++ usando estes operadores.

..
	Since the tracing system is integrated with Attributes, and Attributes work
	with Objects, there must be an |ns3| ``Object`` for the trace source
	to live in.  The next code snippet declares and defines a simple Object we can
	work with.

Como o sistema de rastreamento  integrado com Atributos e este trabalham com Objetos, deve obrigatoriamente existir um ``Object`` |ns3| para cada origem do rastreamento. O prximo cdigo define e declara um Objeto.

::

  class MyObject : public Object
  {
  public:
    static TypeId GetTypeId (void)
    {
      static TypeId tid = TypeId ("MyObject")
        .SetParent (Object::GetTypeId ())
        .AddConstructor<MyObject> ()
        .AddTraceSource ("MyInteger",
                         "An integer value to trace.",
                         MakeTraceSourceAccessor (&MyObject::m_myInt))
        ;
      return tid;
    }
    
    MyObject () {}
    TracedValue<int32_t> m_myInt;
  };

..
	The two important lines of code, above, with respect to tracing are the 
	``.AddTraceSource`` and the ``TracedValue`` declaration of ``m_myInt``.

As duas linhas mais importantes com relao ao rastreamento so ``.AddTraceSource`` e a declarao ``TracedValue`` do ``m_myInt``.


..
	The ``.AddTraceSource`` provides the "hooks" used for connecting the trace
	source to the outside world through the config system.  The ``TracedValue`` 
	declaration provides the infrastructure that overloads the operators mentioned 
	above and drives the callback process.

O mtodo ``.AddTraceSource`` prov a "ligao" usada para conectar a origem do rastreamento com o mundo externo, por meio do sistema de configurao. A declarao ``TracedValue`` prov a infraestrutura que sobrecarrega os operadores abordados anteriormente e  gerencia o processo de *callback*.

::

  void
  IntTrace (int32_t oldValue, int32_t newValue)
  {
    std::cout << "Traced " << oldValue << " to " << newValue << std::endl;
  }

..
	This is the definition of the trace sink.  It corresponds directly to a callback
	function.  Once it is connected, this function will be called whenever one of the
	overloaded operators of the ``TracedValue`` is executed.

Esta  a definio do destino do rastreamento. Isto corresponde diretamente a funo de *callback*. Uma vez que est conectada, esta funo ser chamada sempre que um dos operadores sobrecarregados de ``TracedValue``  executado.

..
	We have now seen the trace source and the trace sink.  What remains is code to
	connect the source to the sink.

Ns temos a origem e o destino do rastreamento. O restante  o cdigo para conectar a origem ao destino.

::

  int
  main (int argc, char *argv[])
  {
    Ptr<MyObject> myObject = CreateObject<MyObject> ();
    myObject->TraceConnectWithoutContext ("MyInteger", MakeCallback(&IntTrace));
  
    myObject->m_myInt = 1234;
  }

..
	Here we first create the Object in which the trace source lives.

Criamos primeiro o Objeto no qual est a origem do rastreamento.

..
	The next step, the ``TraceConnectWithoutContext``, forms the connection
	between the trace source and the trace sink.  Notice the ``MakeCallback``
	template function.  This function does the magic required to create the
	underlying |ns3| Callback object and associate it with the function
	``IntTrace``.  TraceConnect makes the association between your provided
	function and the overloaded ``operator()`` in the traced variable referred 
	to by the "MyInteger" Attribute.  After this association is made, the trace
	source will "fire" your provided callback function.

No prximo passo, o ``TraceConnectWithoutContext`` conecta a origem ao destino do rastreamento. Observe que a funo ``MakeCallback`` cria o objeto *callback* e associa com a funo ``IntTrace``. ``TraceConnectWithoutContext`` faz a associao entre a sua funo e o ``operator()``, sobrecarregado a varivel rastreada referenciada pelo Atributo ``"MyInteger"``. Depois disso, a origem do rastreamento "disparar" sua funo de callback.

..
	The code to make all of this happen is, of course, non-trivial, but the essence
	is that you are arranging for something that looks just like the ``pfi()``
	example above to be called by the trace source.  The declaration of the 
	``TracedValue<int32_t> m_myInt;`` in the Object itself performs the magic 
	needed to provide the overloaded operators (++, ---, etc.) that will use the
	``operator()`` to actually invoke the Callback with the desired parameters.
	The ``.AddTraceSource`` performs the magic to connect the Callback to the 
	Config system, and ``TraceConnectWithoutContext`` performs the magic to
	connect your function to the trace source, which is specified by Attribute
	name.

O cdigo para fazer isto acontecer no  trivial, mas a essncia  a mesma que se a origem do rastreamento chamasse a funo ``pfi()`` do exemplo anterior. A declarao ``TracedValue<int32_t> m_myInt;`` no Objeto  responsvel pela mgica dos operadores sobrecarregados que usaro o ``operator()`` para invocar o *callback*  com os parmetros desejados. O mtodo ``.AddTraceSource`` conecta o *callback* ao sistema de configurao, e ``TraceConnectWithoutContext`` conecta sua funo a fonte de rastreamento, a qual  especificada por um nome 
Atributo.

.. 
	Let's ignore the bit about context for now.

Vamos ignorar um pouco o contexto.

.. 
	Finally, the line,

Finalmente a linha,

::

   myObject->m_myInt = 1234;

..
	should be interpreted as an invocation of ``operator=`` on the member 
	variable ``m_myInt`` with the integer ``1234`` passed as a parameter.

deveria ser interpretada como uma invocao do operador ``=`` na varivel membro ``m_myInt`` com o inteiro ``1234`` passado como parmetro.

..
	It turns out that this operator is defined (by ``TracedValue``) to execute
	a callback that returns void and takes two integer values as parameters --- 
	an old value and a new value for the integer in question.  That is exactly 
	the function signature for the callback function we provided --- ``IntTrace``.

Por sua vez este operador  definido (por ``TracedValue``) para executar um *callback* que retorna ``void`` e possui dois inteiros como parmetros --- um valor antigo e um novo valor para o inteiro em questo. Isto  exatamente a assinatura da funo para a funo de *callback* que ns fornecemos --- ``IntTrace``.

..
	To summarize, a trace source is, in essence, a variable that holds a list of
	callbacks.  A trace sink is a function used as the target of a callback.  The
	Attribute and object type information systems are used to provide a way to 
	connect trace sources to trace sinks.  The act of "hitting" a trace source
	is executing an operator on the trace source which fires callbacks.  This 
	results in the trace sink callbacks registering interest in the source being 
	called with the parameters provided by the source.

Para resumir, uma origem do rastreamento , em essncia, uma varivel que mantm uma lista de *callbacks*. Um destino do rastreamento  uma funo usada como alvo da *callback*. O Atributo e os sistemas de informao de tipo de objeto so usados para fornecer uma maneira de conectar origens e destinos do rastreamento. O ao de "acionar" uma origem do rastreamento  executar um operador na origem, que dispara os *callbacks*. Isto resulta na execuo das *callbacks* dos destinos do rastreamento registrados na origem com os parmetros providos pela origem.

.. 
	If you now build and run this example,

Se compilarmos e executarmos este exemplo,

::

  ./waf --run fourth

..
	you will see the output from the ``IntTrace`` function execute as soon as the
	trace source is hit:

observaremos que a sada da funo ``IntTrace``  processada logo aps a execuo da
origem do rastreamento:

::

  Traced 0 to 1234

..
	When we executed the code, ``myObject->m_myInt = 1234;``, the trace source 
	fired and automatically provided the before and after values to the trace sink.
	The function ``IntTrace`` then printed this to the standard output.  No 
	problem.

Quando executamos o cdigo,  ``myObject->m_myInt = 1234;`` a origem do rastreamento disparou e automaticamente forneceu os valores anteriores e posteriores para o destino do rastreamento. A funo ``IntTrace`` ento imprimiu na sada padro, sem maiores problemas.

.. 
	Using the Config Subsystem to Connect to Trace Sources

Usando o Subsistema de Configurao para Conectar as Origens de Rastreamento
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

..
	The ``TraceConnectWithoutContext`` call shown above in the simple example is
	actually very rarely used in the system.  More typically, the ``Config``
	subsystem is used to allow selecting a trace source in the system using what is
	called a *config path*.  We saw an example of this in the previous section
	where we hooked the "CourseChange" event when we were playing with 
	``third.cc``.

A chamada ``TraceConnectWithoutContext`` apresentada anteriormente  raramente usada no sistema. Geralmente, o subsistema ``Config``  usado para selecionar uma origem do rastreamento no sistema usando um caminho de configurao (*config path*). Ns estudamos um exemplo onde ligamos o evento "CourseChange", quando estvamos brincando com ``third.cc``.

..
	Recall that we defined a trace sink to print course change information from the
	mobility models of our simulation.  It should now be a lot more clear to you 
	what this function is doing.

Ns definimos um destino do rastreamento para imprimir a informao de mudana de rota dos modelos de mobilidade de nossa simulao. Agora est mais claro o que est funo realizava.

::

  void
  CourseChange (std::string context, Ptr<const MobilityModel> model)
  {
    Vector position = model->GetPosition ();
    NS_LOG_UNCOND (context << 
      " x = " << position.x << ", y = " << position.y);
  }

..
	When we connected the "CourseChange" trace source to the above trace sink,
	we used what is called a "Config Path" to specify the source when we
	arranged a connection between the pre-defined trace source and the new trace 
	sink:

Quando conectamos a origem do rastreamento "CourseChange" para o destino do rastreamento anteriormente, usamos o que  chamado de caminho de configurao ("`Config Path`") para especificar a origem e o novo destino do rastreamento.

::

  std::ostringstream oss;
  oss <<
    "/NodeList/" << wifiStaNodes.Get (nWifi - 1)->GetId () <<
    "/$ns3::MobilityModel/CourseChange";

  Config::Connect (oss.str (), MakeCallback (&CourseChange));

..
	Let's try and make some sense of what is sometimes considered relatively
	mysterious code.  For the purposes of discussion, assume that the node 
	number returned by the ``GetId()`` is "7".  In this case, the path
	above turns out to be,

Para entendermos melhor o cdigo, suponha que o nmero do n retornado por ``GetId()``  "7". Neste caso, o caminho seria,

::

  "/NodeList/7/$ns3::MobilityModel/CourseChange"

..
	The last segment of a config path must be an ``Attribute`` of an 
	``Object``.  In fact, if you had a pointer to the ``Object`` that has the
	"CourseChange" ``Attribute`` handy, you could write this just like we did 
	in the previous example.  You know by now that we typically store pointers to 
	our nodes in a NodeContainer.  In the ``third.cc`` example, the Nodes of
	interest are stored in the ``wifiStaNodes`` NodeContainer.  In fact, while
	putting the path together, we used this container to get a Ptr<Node> which we
	used to call GetId() on.  We could have used this Ptr<Node> directly to call
	a connect method directly:

O ltimo segmento de um caminho de configurao deve ser um Atributo de um 
Objeto. Na verdade, se tnhamos um ponteiro para o Objeto que tem o Atributo
"CourseChange" ``, poderamos escrever como no exemplo anterior.
Ns j sabemos que guardamos tipicamente ponteiros para outros ns em um ``NodeContainer``. No exemplo ``third.cc``, os ns de rede de interesse esto armazenados no ``wifiStaNodes`` ``NodeContainer``. De fato enquanto colocamos o caminho junto usamos este continer para obter um ``Ptr<Node>``, usado na chamada ``GetId()``. Poderamos usar diretamente o ``Ptr<Node>`` para chamar um mtodo de conexo.

::

  Ptr<Object> theObject = wifiStaNodes.Get (nWifi - 1);
  theObject->TraceConnectWithoutContext ("CourseChange", MakeCallback (&CourseChange));

..
	In the ``third.cc`` example, we actually want an additional "context" to 
	be delivered along with the Callback parameters (which will be explained below) so we 
	could actually use the following equivalent code,

No exemplo ``third.cc``, queremos um "contexto" adicional para ser encaminhado com os parmetros do *callback* (os quais so explicados a seguir) ento podemos usar o cdigo equivalente,

::

  Ptr<Object> theObject = wifiStaNodes.Get (nWifi - 1);
  theObject->TraceConnect ("CourseChange", MakeCallback (&CourseChange));

..
	It turns out that the internal code for ``Config::ConnectWithoutContext`` and
	``Config::Connect`` actually do find a Ptr<Object> and call the appropriate
	TraceConnect method at the lowest level.

Acontece que o cdigo interno para ``Config::ConnectWithoutContext`` e ``Config::Connect`` permite localizar um Ptr<Object> e chama o mtodo ``TraceConnect``, no nvel mais baixo.

..
	The ``Config`` functions take a path that represents a chain of ``Object`` 
	pointers.  Each segment of a path corresponds to an Object Attribute.  The last 
	segment is the Attribute of interest, and prior segments must be typed to contain
	or find Objects.  The ``Config`` code parses and "walks" this path until it 
	gets to the final segment of the path.  It then interprets the last segment as
	an ``Attribute`` on the last Object it found while walking the path.  The  
	``Config`` functions then call the appropriate ``TraceConnect`` or 
	``TraceConnectWithoutContext`` method on the final Object.  Let's see what 
	happens in a bit more detail when the above path is walked.

As funes ``Config`` aceitam um caminho que representa uma cadeia de ponteiros de Objetos. Cada segmento do caminho corresponde a um Atributo Objeto. O ltimo segmento  o Atributo de interesse e os seguimentos anteriores devem ser definidos para conter ou encontrar Objetos. O  cdigo ``Config`` processa o caminho at obter o segmento final. Ento, interpreta o ltimo segmento como um Atributo no ltimo Objeto ele encontrou no caminho. Ento as funes ``Config`` chamam o mtodo ``TraceConnect`` ou ``TraceConnectWithoutContext`` adequado no Objeto final.

Vamos analisar com mais detalhes o processo descrito.

..
	The leading "/" character in the path refers to a so-called namespace.  One 
	of the predefined namespaces in the config system is "NodeList" which is a 
	list of all of the nodes in the simulation.  Items in the list are referred to
	by indices into the list, so "/NodeList/7" refers to the eighth node in the
	list of nodes created during the simulation.  This reference is actually a 
	``Ptr<Node>`` and so is a subclass of an ``ns3::Object``.  

O primeiro caractere "/" no caminho faz referncia a um *namespace*. Um dos *namespaces* predefinidos no sistema de configurao  "NodeList" que  uma lista de todos os ns na simulao. Itens na lista so referenciados por ndices , logo "/NodeList/7" refere-se ao oitavo n na lista de ns criados durante a simulao. Esta referncia  um ``Ptr<Node>``, por consequncia  uma subclasse de um ``ns3::Object``.

..
	As described in the Object Model section of the |ns3| manual, we support
	Object Aggregation.  This allows us to form an association between different 
	Objects without any programming.  Each Object in an Aggregation can be reached 
	from the other Objects.  

Como descrito na seo Modelo de Objeto do manual |ns3|, h suporte para Agregao de Objeto. Isto permite realizar associao entre diferentes Objetos sem qualquer programao. Cada Objeto em uma Agregao pode ser acessado a partir de outros Objetos.

..
	The next path segment being walked begins with the "$" character.  This 
	indicates to the config system that a ``GetObject`` call should be made 
	looking for the type that follows.  It turns out that the MobilityHelper used in 
	``third.cc`` arranges to Aggregate, or associate, a mobility model to each of 
	the wireless Nodes.  When you add the "$" you are asking for another Object that
	has presumably been previously aggregated.  You can think of this as switching
	pointers from the original Ptr<Node> as specified by "/NodeList/7" to its 
	associated mobility model --- which is of type "$ns3::MobilityModel".  If you
	are familiar with ``GetObject``, we have asked the system to do the following:

O prximo segmento no caminho inicia com o carcter "$". O cifro indica ao sistema de configurao que uma chamada ``GetObject`` deveria ser realizada procurando o tipo especificado em seguida.  diferente do que o ``MobilityHelper`` usou em ``third.cc`` gerenciar a Agregao, ou associar, um modelo de mobilidade para cada dos ns de rede sem fio. Quando adicionamos o "$", significa que estamos pedindo por outro Objeto que tinha sido presumidamente agregado anteriormente. Podemos pensar nisso como ponteiro de comutao do ``Ptr<Node>`` original como especificado por "/NodeList/7" para os modelos de mobilidade associados --- quais so do tipo "$ns3::MobilityModel". Se estivermos familiarizados com ``GetObject``, solicitamos ao sistema para fazer o 
seguinte:

::

  Ptr<MobilityModel> mobilityModel = node->GetObject<MobilityModel> ()

..
	We are now at the last Object in the path, so we turn our attention to the 
	Attributes of that Object.  The ``MobilityModel`` class defines an Attribute 
	called "CourseChange".  You can see this by looking at the source code in
	``src/mobility/model/mobility-model.cc`` and searching for "CourseChange" in your
	favorite editor.  You should find,

Estamos no ltimo Objeto do caminho e neste verificamos os Atributos daquele Objeto. A classe ``MobilityModel`` define um Atributo chamado "CourseChange". Observando o cdigo fonte em ``src/mobility/model/mobility-model.cc`` e procurando por "CourseChange", encontramos,

::

  .AddTraceSource ("CourseChange",
                   "The value of the position and/or velocity vector changed",
                   MakeTraceSourceAccessor (&MobilityModel::m_courseChangeTrace))

.. 
	which should look very familiar at this point.  

o qual parece muito familiar neste momento.

..
	If you look for the corresponding declaration of the underlying traced variable 
	in ``mobility-model.h`` you will find

Se procurarmos por declaraes semelhantes das variveis rastreadas em ``mobility-model.h``
encontraremos,

::

  TracedCallback<Ptr<const MobilityModel> > m_courseChangeTrace;

..
	The type declaration ``TracedCallback`` identifies ``m_courseChangeTrace``
	as a special list of Callbacks that can be hooked using the Config functions 
	described above.

A declarao de tipo ``TracedCallback`` identifica ``m_courseChangeTrace`` como um lista especial de *callbacks* que pode ser ligada usando as funes de Configurao descritas anteriormente.

..
	The ``MobilityModel`` class is designed to be a base class providing a common
	interface for all of the specific subclasses.  If you search down to the end of 
	the file, you will see a method defined called ``NotifyCourseChange()``:

A classe ``MobilityModel``  projetada para ser a classe base provendo uma interface comum para todas as subclasses. No final do arquivo, encontramos um mtodo chamado ``NotifyCourseChange()``:

::

  void
  MobilityModel::NotifyCourseChange (void) const
  {
    m_courseChangeTrace(this);
  }

..
	Derived classes will call into this method whenever they do a course change to
	support tracing.  This method invokes ``operator()`` on the underlying 
	``m_courseChangeTrace``, which will, in turn, invoke all of the registered
	Callbacks, calling all of the trace sinks that have registered interest in the
	trace source by calling a Config function.

Classes derivadas chamaro este mtodo toda vez que fizerem uma alterao na rota para 
suportar rastreamento. Este mtodo invoca ``operator()`` em ``m_courseChangeTrace``, 
que invocar todos os *callbacks* registrados, chamando todos os *trace sinks* que tem 
interesse registrado na origem do rastreamento usando a funo de Configurao.

..
	So, in the ``third.cc`` example we looked at, whenever a course change is 
	made in one of the ``RandomWalk2dMobilityModel`` instances installed, there
	will be a ``NotifyCourseChange()`` call which calls up into the 
	``MobilityModel`` base class.  As seen above, this invokes ``operator()``
	on ``m_courseChangeTrace``, which in turn, calls any registered trace sinks.
	In the example, the only code registering an interest was the code that provided
	the config path.  Therefore, the ``CourseChange`` function that was hooked 
	from Node number seven will be the only Callback called.

No exemplo ``third.cc`` ns vimos que sempre que uma mudana de rota  realizada em uma das instncias ``RandomWalk2dMobilityModel`` instaladas, haver uma chamada ``NotifyCourseChange()`` da classe base ``MobilityModel``. Como observado, isto invoca ``operator()`` em ``m_courseChangeTrace``, que por sua vez, chama qualquer destino do rastreamento registrados. No exemplo, o nico cdigo que registrou interesse foi aquele que forneceu o caminho de configurao. Consequentemente, a funo ``CourseChange`` que foi ligado no Node de nmero sete ser a nica *callback* chamada.

..
	The final piece of the puzzle is the "context".  Recall that we saw an output 
	looking something like the following from ``third.cc``:

A pea final do quebra-cabea  o "contexto". Lembre-se da sada de ``third.cc``:

::

  /NodeList/7/$ns3::MobilityModel/CourseChange x = 7.27897, y = 2.22677

..
	The first part of the output is the context.  It is simply the path through
	which the config code located the trace source.  In the case we have been looking at
	there can be any number of trace sources in the system corresponding to any number
	of nodes with mobility models.  There needs to be some way to identify which trace
	source is actually the one that fired the Callback.  An easy way is to request a 
	trace context when you ``Config::Connect``.

A primeira parte da sada  o contexto.  simplesmente o caminho pelo qual o cdigo de configurao localizou a origem do rastreamento. No caso, poderamos ter qualquer nmero de origens de rastreamento no sistema correspondendo a qualquer nmero de ns com modelos de mobilidade.  necessrio uma maneira de identificar qual origem do rastreamento disparou o *callback*. Uma forma simples  solicitar um contexto de rastreamento quando  usado o ``Config::Connect``.

.. 
	How to Find and Connect Trace Sources, and Discover Callback Signatures

Como Localizar e Conectar Origens de Rastreamento, e Descobrir Assinaturas de *Callback*
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

..
	The first question that inevitably comes up for new users of the Tracing system is,
	"okay, I know that there must be trace sources in the simulation core, but how do
	I find out what trace sources are available to me"?  
	
	The second question is, "okay, I found a trace source, how do I figure out the
	config path to use when I connect to it"? 

	The third question is, "okay, I found a trace source, how do I figure out what 
	the return type and formal arguments of my callback function need to be"?

	The fourth question is, "okay, I typed that all in and got this incredibly bizarre
	error message, what in the world does it mean"?

As questes que inevitavelmente os novos usurios do sistema de Rastreamento fazem, so:

1. "Eu sei que existem origens do rastreamento no ncleo da simulao, mas como 
   eu descubro quais esto disponveis para mim?"
2. "Eu encontrei uma origem do rastreamento, como eu defino o caminho de configurao para 
   usar quando eu conectar a origem?"
3. "Eu encontrei uma origem do rastreamento, como eu  defino o tipo de retorno e os 
   argumentos formais da minha funo de *callback*?"
4. "Eu fiz tudo corretamente e obtive uma mensagem de erro bizarra, o que isso significa?"

.. 
	What Trace Sources are Available?

Quais Origens de Rastreamento so Disponibilizadas
++++++++++++++++++++++++++++++++++++++++++++++++++

..
	The answer to this question is found in the |ns3| Doxygen.  If you go to 
	the project web site, 
	`ns-3 project
	<http://www.nsnam.org>`_, you will find a link to "Documentation" in the navigation bar.  If you select this link, you will be
	taken to our documentation page. There 
	is a link to "Latest Release" that will take you to the documentation
	for the latest stable release of |ns3|.
	If you select the "API Documentation" link, you will be
	taken to the |ns3| API documentation page.

A resposta  encontrada no Doxygen do |ns3|. Acesse o stio Web do projeto, `ns-3 project <http://www.nsnam.org>`_, em seguida, "Documentation" na barra de navegao. Logo aps, "Latest Release" e "API Documentation".

Acesse o item "Modules" na documentao do NS-3. Agora, selecione o item "C++ Constructs Used by All Modules". Sero exibidos quatro tpicos extremamente teis:

* The list of all trace sources
* The list of all attributes
* The list of all global values
* Debugging

..
	The list of interest to us here is "the list of all trace sources".  Go 
	ahead and select that link.  You will see, perhaps not too surprisingly, a
	list of all of the trace sources available in the |ns3| core.

Estamos interessados em "*the list of all trace sources*" - a lista de todas origens do rastreamento. Selecionando este item,  exibido uma lista com todas origens disponveis no ncleo do |ns3|.

..
	As an example, scroll down to ``ns3::MobilityModel``.  You will find
	an entry for

Como exemplo, ``ns3::MobilityModel``, ter uma entrada para

::

  CourseChange: The value of the position and/or velocity vector changed 

..
	You should recognize this as the trace source we used in the ``third.cc``
	example.  Perusing this list will be helpful.

No caso, esta foi a origem do rastreamento usada no exemplo ``third.cc``, esta lista ser muito til.

.. 
	What String do I use to Connect?

Qual String eu uso para Conectar?
+++++++++++++++++++++++++++++++++

..
	The easiest way to do this is to grep around in the |ns3| codebase for someone
	who has already figured it out,  You should always try to copy someone else's
	working code before you start to write your own.  Try something like:

A forma mais simples  procurar na base de cdigo do |ns3| por algum que j fez uso do caminho de configurao que precisamos para ligar a fonte de rastreamento. Sempre deveramos primeiro copiar um cdigo que funciona antes de escrever nosso prprio cdigo. Tente usar os comandos:

::

  find . -name '*.cc' | xargs grep CourseChange | grep Connect

..
	and you may find your answer along with working code.  For example, in this
	case, ``./ns-3-dev/examples/wireless/mixed-wireless.cc`` has something
	just waiting for you to use:

e poderemos encontrar um cdigo operacional que atenda nossas necessidades. Por exemplo, neste caso, ``./ns-3-dev/examples/wireless/mixed-wireless.cc`` tem algo que podemos usar:

::

  Config::Connect ("/NodeList/*/$ns3::MobilityModel/CourseChange", 
    MakeCallback (&CourseChangeCallback));

..
	If you cannot find any examples in the distribution, you can find this out
	from the |ns3| Doxygen.  It will probably be simplest just to walk 
	through the "CourseChanged" example.

Se no localizamos nenhum exemplo na distribuio, podemos tentar o Doxygen do |ns3|.  provavelmente mais simples que percorrer o exemplo "CourseChanged".

..
	Let's assume that you have just found the "CourseChanged" trace source in 
	"The list of all trace sources" and you want to figure out how to connect to
	it.  You know that you are using (again, from the ``third.cc`` example) an
	``ns3::RandomWalk2dMobilityModel``.  So open the "Class List" book in
	the NS-3 documentation tree by clicking its "+" box.  You will now see a
	list of all of the classes in |ns3|.  Scroll down until you see the
	entry for ``ns3::RandomWalk2dMobilityModel`` and follow that link.
	You should now be looking at the "ns3::RandomWalk2dMobilityModel Class 
	Reference".

Suponha que encontramos a origem do rastreamento "CourseChanged" na "The list of all trace sources" e queremos resolver como nos conectar a ela. Voc sabe que est usando um ``ns3::RandomWalk2dMobilityModel``. Logo, acesse o item "Class List" na documentao do |ns3|. Ser exibida a lista de todas as classes. Selecione a entrada para ``ns3::RandomWalk2dMobilityModel`` para exibir a documentao da classe.

..
	If you now scroll down to the "Member Function Documentation" section, you
	will see documentation for the ``GetTypeId`` function.  You constructed one
	of these in the simple tracing example above:

Acesse a seo "Member Function Documentation" e obter a documentao para a funo ``GetTypeId``. Voc construiu uma dessas em um exemplo anterior:
	
::

    static TypeId GetTypeId (void)
    {
      static TypeId tid = TypeId ("MyObject")
        .SetParent (Object::GetTypeId ())
        .AddConstructor<MyObject> ()
        .AddTraceSource ("MyInteger",
                         "An integer value to trace.",
                         MakeTraceSourceAccessor (&MyObject::m_myInt))
        ;
      return tid;
    }

..
	As mentioned above, this is the bit of code that connected the Config 
	and Attribute systems to the underlying trace source.  This is also the
	place where you should start looking for information about the way to 
	connect. 

Como abordado, este cdigo conecta os sistemas *Config* e Atributos  origem do rastreamento.  tambm o local onde devemos iniciar a busca por informao sobre como conectar.

..
	You are looking at the same information for the RandomWalk2dMobilityModel; and
	the information you want is now right there in front of you in the Doxygen:

Voc est observando a mesma informao para ``RandomWalk2dMobilityModel``; e a informao que voc precisa est explcita no Doxygen:
	
::

  This object is accessible through the following paths with Config::Set 
  		and Config::Connect: 

  /NodeList/[i]/$ns3::MobilityModel/$ns3::RandomWalk2dMobilityModel 

..
	The documentation tells you how to get to the ``RandomWalk2dMobilityModel`` 
	Object.  Compare the string above with the string we actually used in the 
	example code:

A documentao apresenta como obter o Objeto ``RandomWalk2dMobilityModel``. Compare o texto anterior com o texto que ns usamos no cdigo do exemplo:

::

  "/NodeList/7/$ns3::MobilityModel"

..
	The difference is due to the fact that two ``GetObject`` calls are implied 
	in the string found in the documentation.  The first, for ``$ns3::MobilityModel``
	will query the aggregation for the base class.  The second implied 
	``GetObject`` call, for ``$ns3::RandomWalk2dMobilityModel``, is used to "cast"
	the base class to the concrete implementation class.  The documentation shows 
	both of these operations for you.  It turns out that the actual Attribute you are
	going to be looking for is found in the base class as we have seen.

A diferena  que h duas chamadas ``GetObject`` inclusas no texto da documentao. A primeira, para ``$ns3::MobilityModel`` solicita a agregao para a classe base. A segunda, para ``$ns3::RandomWalk2dMobilityModel``  usada como *cast* da classe base para a 
implementao concreta da classe.  

.. 
	Look further down in the ``GetTypeId`` doxygen.  You will find,

Analisando ainda mais o ``GetTypeId`` no Doxygen, temos

::

  No TraceSources defined for this type.
  TraceSources defined in parent class ns3::MobilityModel:

  CourseChange: The value of the position and/or velocity vector changed 
  Reimplemented from ns3::MobilityModel

..
	This is exactly what you need to know.  The trace source of interest is found in
	``ns3::MobilityModel`` (which you knew anyway).  The interesting thing this
	bit of Doxygen tells you is that you don't need that extra cast in the config
	path above to get to the concrete class, since the trace source is actually in
	the base class.  Therefore the additional ``GetObject`` is not required and
	you simply use the path:

Isto  exatamente o que precisamos saber. A origem do rastreamento de interesse  encontrada em ``ns3::MobilityModel``.  O interessante  que pela documentao no  necessrio o *cast* extra para obter a classe concreta, pois a origem do rastreamento est na classe base. Por consequncia, o ``GetObject`` adicional no  necessrio e podemos usar o caminho:

::

  /NodeList/[i]/$ns3::MobilityModel

.. 
	which perfectly matches the example path:

que  idntico ao caminho do exemplo:

::

  /NodeList/7/$ns3::MobilityModel

.. 
	What Return Value and Formal Arguments?

Quais so os Argumentos Formais e o Valor de Retorno?
+++++++++++++++++++++++++++++++++++++++++++++++++++++

..
	The easiest way to do this is to grep around in the |ns3| codebase for someone
	who has already figured it out,  You should always try to copy someone else's
	working code.  Try something like:

A forma mais simples  procurar na base de cdigo do |ns3| por um cdigo existente. Voc sempre deveria primeiro copiar um cdigo que funciona antes de escrever seu prprio. Tente usar os comandos:
	
::

  find . -name '*.cc' | xargs grep CourseChange | grep Connect

..
	and you may find your answer along with working code.  For example, in this
	case, ``./ns-3-dev/examples/wireless/mixed-wireless.cc`` has something
	just waiting for you to use.  You will find

e voc poder encontrar cdigo operacional. Por exemplo, neste caso, ``./ns-3-dev/examples/wireless/mixed-wireless.cc`` tem cdigo para ser reaproveitado.

::

  Config::Connect ("/NodeList/*/$ns3::MobilityModel/CourseChange", 
    MakeCallback (&CourseChangeCallback));

..
	as a result of your grep.  The ``MakeCallback`` should indicate to you that
	there is a callback function there which you can use.  Sure enough, there is:

como resultado, ``MakeCallback`` indicaria que h uma funo *callback* que pode ser usada.
Para reforar:

::

  static void
  CourseChangeCallback (std::string path, Ptr<const MobilityModel> model)
  {
    ...
  }

.. 
	Take my Word for It

Acredite em Minha Palavra
~~~~~~~~~~~~~~~~~~~~~~~~~

..
	If there are no examples to work from, this can be, well, challenging to 
	actually figure out from the source code.

Se no h exemplos, pode ser desafiador descobrir por meio da anlise do cdigo fonte.

..
	Before embarking on a walkthrough of the code, I'll be kind and just tell you
	a simple way to figure this out:  The return value of your callback will always 
	be void.  The formal parameter list for a ``TracedCallback`` can be found 
	from the template parameter list in the declaration.  Recall that for our
	current example, this is in ``mobility-model.h``, where we have previously
	found:

Antes de aventurar-se no cdigo, diremos algo importante: O valor de retorno de sua *callback* sempre ser *void*. A lista de parmetros formais para uma ``TracedCallback`` pode ser encontrada no lista de parmetro padro na declarao. Recorde do exemplo atual, isto est em ``mobility-model.h``, onde encontramos:

::

  TracedCallback<Ptr<const MobilityModel> > m_courseChangeTrace;

..
	There is a one-to-one correspondence between the template parameter list in 
	the declaration and the formal arguments of the callback function.  Here,
	there is one template parameter, which is a ``Ptr<const MobilityModel>``.
	This tells you that you need a function that returns void and takes a
	a ``Ptr<const MobilityModel>``.  For example,

No h uma correspondncia de um-para-um entre a lista de parmetro padro na declarao e os argumentos formais da funo *callback*. Aqui, h um parmetro padro, que  um ``Ptr<const MobilityModel>``. Isto significa que precisamos de uma funo que retorna *void* e possui um parmetro ``Ptr<const MobilityModel>``. Por exemplo,

::

  void
  CourseChangeCallback (Ptr<const MobilityModel> model)
  {
    ...
  }

..
	That's all you need if you want to ``Config::ConnectWithoutContext``.  If
	you want a context, you need to ``Config::Connect`` and use a Callback 
	function that takes a string context, then the required argument.

Isto  tudo que precisamos para ``Config::ConnectWithoutContext``. Se voc quer um contexto, use ``Config::Connect`` e uma funo *callback* que possui como um parmetro uma `string` de contexto, seguido pelo argumento.

::

  void
  CourseChangeCallback (std::string path, Ptr<const MobilityModel> model)
  {
    ...
  }

..
	If you want to ensure that your ``CourseChangeCallback`` is only visible
	in your local file, you can add the keyword ``static`` and come up with:

Para garantir que ``CourseChangeCallback`` seja somente visvel em seu arquivo, voc pode adicionar a palavra chave ``static``, como no exemplo:

::

  static void
  CourseChangeCallback (std::string path, Ptr<const MobilityModel> model)
  {
    ...
  }

.. 
	which is exactly what we used in the ``third.cc`` example.

exatamente o que  usado no exemplo ``third.cc``.

..
	The Hard Way

A Forma Complicada
~~~~~~~~~~~~~~~~~~

..
	This section is entirely optional.  It is going to be a bumpy ride, especially
	for those unfamiliar with the details of templates.  However, if you get through
	this, you will have a very good handle on a lot of the |ns3| low level
	idioms.

Esta seo  opcional. Pode ser bem penosa para aqueles que conhecem poucos detalhes de tipos parametrizados de dados (*templates*). Entretanto, se continuarmos nessa seo, mergulharemos em detalhes de baixo nvel do |ns3|.

..
	So, again, let's figure out what signature of callback function is required for
	the "CourseChange" Attribute.  This is going to be painful, but you only need
	to do this once.  After you get through this, you will be able to just look at
	a ``TracedCallback`` and understand it.

Vamos novamente descobrir qual assinatura da funo de *callback*  necessria para o Atributo "CourseChange". Isto pode ser doloroso, mas precisamos faz-lo apenas uma vez. Depois de tudo, voc ser capaz de entender um ``TracedCallback``.

..
	The first thing we need to look at is the declaration of the trace source.
	Recall that this is in ``mobility-model.h``, where we have previously
	found:

Primeiro, verificamos a declarao da origem do rastreamento. Recorde que isto est em ``mobility-model.h``:
	
::

  TracedCallback<Ptr<const MobilityModel> > m_courseChangeTrace;

..
	This declaration is for a template.  The template parameter is inside the
	angle-brackets, so we are really interested in finding out what that
	``TracedCallback<>`` is.  If you have absolutely no idea where this might
	be found, grep is your friend.	

Esta declarao  para um *template*. O parmetro do *template* est entre ``<>``, logo estamos interessados em descobrir o que  ``TracedCallback<>``. Se no tem nenhuma ideia de onde pode ser encontrado, use o utilitrio *grep*.

..
	We are probably going to be interested in some kind of declaration in the 
	|ns3| source, so first change into the ``src`` directory.  Then, 
	we know this declaration is going to have to be in some kind of header file,
	so just grep for it using:

Estamos interessados em uma declarao similar no cdigo fonte do |ns3|, logo buscamos no diretrio ``src``. Ento, sabemos que esta declarao tem um arquivo de cabealho, e procuramos por ele usando:

::

  find . -name '*.h' | xargs grep TracedCallback

..
	You'll see 124 lines fly by (I piped this through wc to see how bad it was).
	Although that may seem like it, that's not really a lot.  Just pipe the output
	through more and start scanning through it.  On the first page, you will see
	some very suspiciously template-looking stuff.

Obteremos 124 linhas, com este comando. Analisando a sada, encontramos alguns *templates* que podem ser teis.

::

  TracedCallback<T1,T2,T3,T4,T5,T6,T7,T8>::TracedCallback ()
  TracedCallback<T1,T2,T3,T4,T5,T6,T7,T8>::ConnectWithoutContext (c ...
  TracedCallback<T1,T2,T3,T4,T5,T6,T7,T8>::Connect (const CallbackB ...
  TracedCallback<T1,T2,T3,T4,T5,T6,T7,T8>::DisconnectWithoutContext ...
  TracedCallback<T1,T2,T3,T4,T5,T6,T7,T8>::Disconnect (const Callba ...
  TracedCallback<T1,T2,T3,T4,T5,T6,T7,T8>::operator() (void) const ...
  TracedCallback<T1,T2,T3,T4,T5,T6,T7,T8>::operator() (T1 a1) const ...
  TracedCallback<T1,T2,T3,T4,T5,T6,T7,T8>::operator() (T1 a1, T2 a2 ...
  TracedCallback<T1,T2,T3,T4,T5,T6,T7,T8>::operator() (T1 a1, T2 a2 ...
  TracedCallback<T1,T2,T3,T4,T5,T6,T7,T8>::operator() (T1 a1, T2 a2 ...
  TracedCallback<T1,T2,T3,T4,T5,T6,T7,T8>::operator() (T1 a1, T2 a2 ...
  TracedCallback<T1,T2,T3,T4,T5,T6,T7,T8>::operator() (T1 a1, T2 a2 ...
  TracedCallback<T1,T2,T3,T4,T5,T6,T7,T8>::operator() (T1 a1, T2 a2 ...

..
	It turns out that all of this comes from the header file 
	``traced-callback.h`` which sounds very promising.  You can then take a
	look at ``mobility-model.h`` and see that there is a line which confirms
	this hunch:

Observamos que todas linhas so do arquivo de cabealho ``traced-callback.h``, logo ele parece muito promissor. Para confirmar, verifique o arquivo ``mobility-model.h``  e procure uma linha que corrobore esta suspeita.

::

  #include "ns3/traced-callback.h"

..
	Of course, you could have gone at this from the other direction and started
	by looking at the includes in ``mobility-model.h`` and noticing the 
	include of ``traced-callback.h`` and inferring that this must be the file
	you want.

Observando as incluses em ``mobility-model.h``, verifica-se a incluso do ``traced-callback.h`` e conclui-se que este deve ser o arquivo.

..
	In either case, the next step is to take a look at ``src/core/model/traced-callback.h``
	in your favorite editor to see what is happening.

O prximo passo  analisar o arquivo ``src/core/model/traced-callback.h`` e entender sua funcionalidade.

.. 
	You will see a comment at the top of the file that should be comforting:

H um comentrio no topo do arquivo que deveria ser animador:

::

  An ns3::TracedCallback has almost exactly the same API as a normal ns3::Callback but
  instead of forwarding calls to a single function (as an ns3::Callback normally does),
  it forwards calls to a chain of ns3::Callback.

.. 
	This should sound very familiar and let you know you are on the right track.

Isto deveria ser familiar e confirma que estamos no caminho correto.

.. 
	Just after this comment, you will find,

Depois deste comentrio, encontraremos

::

  template<typename T1 = empty, typename T2 = empty, 
           typename T3 = empty, typename T4 = empty,
           typename T5 = empty, typename T6 = empty,
           typename T7 = empty, typename T8 = empty>
  class TracedCallback 
  {
    ...

..
	This tells you that TracedCallback is a templated class.  It has eight possible
	type parameters with default values.  Go back and compare this with the 
	declaration you are trying to understand:

Isto significa que TracedCallback  uma classe genrica (*templated class*). Possui oito possveis tipos de parmetros com valores padres. Retorne e compare com a declarao que voc est tentando entender:

::

  TracedCallback<Ptr<const MobilityModel> > m_courseChangeTrace;

..
	The ``typename T1`` in the templated class declaration corresponds to the 
	``Ptr<const MobilityModel>`` in the declaration above.  All of the other
	type parameters are left as defaults.  Looking at the constructor really
	doesn't tell you much.  The one place where you have seen a connection made
	between your Callback function and the tracing system is in the ``Connect``
	and ``ConnectWithoutContext`` functions.  If you scroll down, you will see
	a ``ConnectWithoutContext`` method here:

O ``typename T1`` na declarao da classe corresponde a ``Ptr<const MobilityModel>`` da declarao anterior. Todos os outros parmetros so padres. Observe que o construtor no contribui com muita informao. O nico lugar onde h uma conexo entre a funo *callback* e o sistema de rastreamento  nas funes ``Connect`` e ``ConnectWithoutContext``. Como mostrado a seguir:
	
::

  template<typename T1, typename T2, 
           typename T3, typename T4,
           typename T5, typename T6,
           typename T7, typename T8>
  void 
  TracedCallback<T1,T2,T3,T4,T5,T6,T7,T8>::ConnectWithoutContext ...
  {
    Callback<void,T1,T2,T3,T4,T5,T6,T7,T8> cb;
    cb.Assign (callback);
    m_callbackList.push_back (cb);
  }

..
	You are now in the belly of the beast.  When the template is instantiated for
	the declaration above, the compiler will replace ``T1`` with 
	``Ptr<const MobilityModel>``.  

Voc est no olho do furao. Quando o *template*  instanciado pela declarao anterior, o compilador substitui ``T1`` por ``Ptr<const MobilityModel>``.

::

  void 
  TracedCallback<Ptr<const MobilityModel>::ConnectWithoutContext ... cb
  {
    Callback<void, Ptr<const MobilityModel> > cb;
    cb.Assign (callback);
    m_callbackList.push_back (cb);
  }

..
	You can now see the implementation of everything we've been talking about.  The
	code creates a Callback of the right type and assigns your function to it.  This
	is the equivalent of the ``pfi = MyFunction`` we discussed at the start of
	this section.  The code then adds the Callback to the list of Callbacks for 
	this source.  The only thing left is to look at the definition of Callback.
	Using the same grep trick as we used to find ``TracedCallback``, you will be
	able to find that the file ``./core/callback.h`` is the one we need to look at.

Podemos observar a implementao de tudo que foi explicado at este ponto. O cdigo cria uma *callback* do tipo adequado e atribui sua funo para ela. Isto  equivalente a ``pfi = MyFunction`` discutida anteriormente. O cdigo ento adiciona a *callback* para a lista de *callbacks* para esta origem. O que no observamos ainda  a definio da *callback*. Usando o utilitrio *grep* podemos encontrar o arquivo ``./core/callback.h`` e verificar a definio.

..
	If you look down through the file, you will see a lot of probably almost
	incomprehensible template code.  You will eventually come to some Doxygen for
	the Callback template class, though.  Fortunately, there is some English:

No arquivo h muito cdigo incompreensvel. Felizmente h algum em Ingls. 

::

  This class template implements the Functor Design Pattern.
  It is used to declare the type of a Callback:
   - the first non-optional template argument represents
     the return type of the callback.
   - the second optional template argument represents
     the type of the first argument to the callback.
   - the third optional template argument represents
     the type of the second argument to the callback.
   - the fourth optional template argument represents
     the type of the third argument to the callback.
   - the fifth optional template argument represents
     the type of the fourth argument to the callback.
   - the sixth optional template argument represents
     the type of the fifth argument to the callback.

.. 
	We are trying to figure out what the

Ns estamos tentando descobrir o que significa a declarao 

::

    Callback<void, Ptr<const MobilityModel> > cb;

..
	declaration means.  Now we are in a position to understand that the first
	(non-optional) parameter, ``void``, represents the return type of the 
	Callback.  The second (non-optional) parameter, ``Ptr<const MobilityModel>``
	represents the first argument to the callback.

Agora entendemos que o primeiro parmetro, ``void``, indica o tipo de retorno da *callback*. O segundo parmetro, ``Ptr<const MobilityModel>`` representa o primeiro argumento da *callback*.

..
	The Callback in question is your function to receive the trace events.  From
	this you can infer that you need a function that returns ``void`` and takes
	a ``Ptr<const MobilityModel>``.  For example,

A *callback* em questo  a sua funo que recebe os eventos de rastreamento. Logo, podemos deduzir que precisamos de uma funo que retorna ``void`` e possui um parmetro ``Ptr<const MobilityModel>``. Por exemplo,

::

  void
  CourseChangeCallback (Ptr<const MobilityModel> model)
  {
    ...
  }

..
	That's all you need if you want to ``Config::ConnectWithoutContext``.  If
	you want a context, you need to ``Config::Connect`` and use a Callback 
	function that takes a string context.  This is because the ``Connect``
	function will provide the context for you.  You'll need:

Isto  tudo que precisamos no ``Config::ConnectWithoutContext``. Se voc quer um contexto, use ``Config::Connect`` e uma funo *callback* que possui como um parmetro uma `string` de contexto, seguido pelo argumento.

::

  void
  CourseChangeCallback (std::string path, Ptr<const MobilityModel> model)
  {
    ...
  }

..
	If you want to ensure that your ``CourseChangeCallback`` is only visible
	in your local file, you can add the keyword ``static`` and come up with:

Se queremos garantir que ``CourseChangeCallback``  visvel somente 
em seu arquivo, voc pode adicionar a palavra chave ``static``, como no exemplo:

::

  static void
  CourseChangeCallback (std::string path, Ptr<const MobilityModel> model)
  {
    ...
  }

..
	which is exactly what we used in the ``third.cc`` example.  Perhaps you
	should now go back and reread the previous section (Take My Word for It).

o que  exatamente usado no exemplo ``third.cc``. Talvez seja interessante reler a seo (Acredite em Minha Palavra).

..
	If you are interested in more details regarding the implementation of 
	Callbacks, feel free to take a look at the |ns3| manual.  They are one
	of the most frequently used constructs in the low-level parts of |ns3|.
	It is, in my opinion, a quite elegant thing.

H mais detalhes sobre a implementao de *callbacks* no manual do |ns3|. Elas esto entre os mais usados construtores das partes de baixo-nvel do |ns3|. Em minha opinio, algo bastante elegante.

.. 
	What About TracedValue?

E quanto a TracedValue?
+++++++++++++++++++++++

..
	Earlier in this section, we presented a simple piece of code that used a
	``TracedValue<int32_t>`` to demonstrate the basics of the tracing code.
	We just glossed over the way to find the return type and formal arguments
	for the ``TracedValue``.  Rather than go through the whole exercise, we
	will just point you at the correct file, ``src/core/model/traced-value.h`` and
	to the important piece of code:

No incio desta seo, ns apresentamos uma parte de cdigo simples que usou um ``TracedValue<int32_t>`` para demonstrar o bsico sobre cdigo de rastreamento. Ns desprezamos os mtodos para encontrar o tipo de retorno e os argumentos formais para o ``TracedValue``. Acelerando o processo, indicamos o arquivo ``src/core/model/traced-value.h`` e a parte relevante do cdigo:

::

  template <typename T>
  class TracedValue
  {
  public:
    ...
    void Set (const T &v) {
      if (m_v != v)
        {
  	m_cb (m_v, v);
  	m_v = v;
        }
    }
    ...
  private:
    T m_v;
    TracedCallback<T,T> m_cb;
  };

..
	Here you see that the ``TracedValue`` is templated, of course.  In the simple
	example case at the start of the section, the typename is int32_t.  This means 
	that the member variable being traced (``m_v`` in the private section of the 
	class) will be an ``int32_t m_v``.  The ``Set`` method will take a 
	``const int32_t &v`` as a parameter.  You should now be able to understand 
	that the ``Set`` code will fire the ``m_cb`` callback with two parameters:
	the first being the current value of the ``TracedValue``; and the second 
	being the new value being set.

Verificamos que ``TracedValue``  uma classe parametrizada. No caso simples do incio da seo, o nome do tipo  int32_t. Isto significa que  a varivel membro sendo rastreada (``m_v`` na seo privada da classe) ser ``int32_t m_v``. O mtodo ``Set`` possui um argumento ``const int32_t &v``. Voc deveria ser capaz de entender que o cdigo ``Set`` dispar o *callback* ``m_cb`` com dois parmetros: o primeiro sendo o valor atual do ``TracedValue``; e o segundo sendo o novo valor.

..
	The callback, ``m_cb`` is declared as a ``TracedCallback<T, T>`` which
	will correspond to a ``TracedCallback<int32_t, int32_t>`` when the class is 
	instantiated.

A *callback* ``m_cb``  declarada como um ``TracedCallback<T, T>`` que corresponder a um ``TracedCallback<int32_t, int32_t>`` quando a classe  instanciada.

..
	Recall that the callback target of a TracedCallback always returns ``void``.  
	Further recall that there is a one-to-one correspondence between the template 
	parameter list in the declaration and the formal arguments of the callback 
	function.  Therefore the callback will need to have a function signature that 
	looks like:

Lembre-se que o destino da *callback* de um TracedCallback sempre retorna ``void``. Lembre tambm que h uma correspondncia de um-para-um entre a lista de parmetros polimrfica e os argumentos formais da funo *callback*. Logo, a *callback* precisa ter uma assinatura de funo similar a:

::

  void
  MyCallback (int32_t oldValue, int32_t newValue)
  {
    ...
  }

..
	It probably won't surprise you that this is exactly what we provided in that 
	simple example we covered so long ago:

Isto  exatamente o que ns apresentamos no exemplo simples abordado anteriormente.

::

  void
  IntTrace (int32_t oldValue, int32_t newValue)
  {
    std::cout << "Traced " << oldValue << " to " << newValue << std::endl;
  }

.. 
	A Real Example

Um Exemplo Real
***************

..
	Let's do an example taken from one of the best-known books on TCP around.  
	"TCP/IP Illustrated, Volume 1: The Protocols," by W. Richard Stevens is a 
	classic.  I just flipped the book open and ran across a nice plot of both the 
	congestion window and sequence numbers versus time on page 366.  Stevens calls 
	this, "Figure 21.10. Value of cwnd and send sequence number while data is being 
	transmitted."  Let's just recreate the cwnd part of that plot in |ns3|
	using the tracing system and ``gnuplot``.

Vamos fazer um exemplo retirado do livro "TCP/IP Illustrated, Volume 1: The Protocols" escrito por W. Richard Stevens. Localizei na pgina 366 do livro um grfico da janela de congestionamento e nmeros de sequncia versus tempo. Stevens denomina de "Figure 21.10. Value of cwnd and send sequence number while data is being transmitted." Vamos recriar a parte *cwnd* daquele grfico em |ns3| usando o sistema de rastreamento e ``gnuplot``.

.. 
	Are There Trace Sources Available?

H Fontes de Rastreamento Disponibilizadas?
+++++++++++++++++++++++++++++++++++++++++++

..
	The first thing to think about is how we want to get the data out.  What is it
	that we need to trace?  The first thing to do is to consult "The list of all
	trace sources" to see what we have to work with.  Recall that this is found
	in the |ns3| Doxygen in the "C++ Constructs Used by All Modules" Module section.  If you scroll
	through the list, you will eventually find:

Primeiro devemos pensar sobre como queremos obter os dados de sada. O que  que  ns precisamos rastrear? Consultamos ento *"The list of all trace sources"* para sabermos o que temos para trabalhar. Essa seo encontra-se na documentao na seo *"Module"*, no item *"C++ Constructs Used by All Modules"*. Procurando na lista, encontraremos:

::

  ns3::TcpNewReno
  CongestionWindow: The TCP connection's congestion window

..
	It turns out that the |ns3| TCP implementation lives (mostly) in the 
	file ``src/internet/model/tcp-socket-base.cc`` while congestion control
	variants are in files such as ``src/internet/model/tcp-newreno.cc``.  
	If you don't know this a priori, you can use the recursive grep trick:

A maior parte da implementao do TCP no |ns3| est no arquivo ``src/internet/model/tcp-socket-base.cc`` enquanto variantes do controle de congestionamento esto em arquivos como ``src/internet/model/tcp-newreno.cc``. Se no sabe a priori dessa informao, use:

::

  find . -name '*.cc' | xargs grep -i tcp

.. 
	You will find page after page of instances of tcp pointing you to that file. 

Haver pginas de respostas apontando para aquele arquivo.

..
	If you open ``src/internet/model/tcp-newreno.cc`` in your favorite 
	editor, you will see right up at the top of the file, the following declarations:

No incio do arquivo ``src/internet/model/tcp-newreno.cc`` h as seguintes declaraes:

::

  TypeId
  TcpNewReno::GetTypeId ()
  {
    static TypeId tid = TypeId("ns3::TcpNewReno")
      .SetParent<TcpSocketBase> ()
      .AddConstructor<TcpNewReno> ()
      .AddTraceSource ("CongestionWindow",
                       "The TCP connection's congestion window",
                       MakeTraceSourceAccessor (&TcpNewReno::m_cWnd))
      ;
    return tid;
  }

..
	This should tell you to look for the declaration of ``m_cWnd`` in the header
	file ``src/internet/model/tcp-newreno.h``.  If you open this file in your
	favorite editor, you will find:

Isto deveria gui-lo para localizar a declarao de ``m_cWnd`` no arquivo de cabealho ``src/internet/model/tcp-newreno.h``. Temos nesse arquivo:

::

  TracedValue<uint32_t> m_cWnd; //Congestion window

..
	You should now understand this code completely.  If we have a pointer to the 
	``TcpNewReno``, we can ``TraceConnect`` to the "CongestionWindow" trace 
	source if we provide an appropriate callback target.  This is the same kind of
	trace source that we saw in the simple example at the start of this section,
	except that we are talking about ``uint32_t`` instead of ``int32_t``.

Voc deveria entender este cdigo. Se ns temos um ponteiro para ``TcpNewReno``, podemos fazer ``TraceConnect`` para a origem do rastreamento "CongestionWindow" se fornecermos uma *callback* adequada.  o mesmo tipo de origem do rastreamento que ns abordamos no exemplo simples no incio da seo, exceto que estamos usando ``uint32_t`` ao invs de ``int32_t``.

..
	We now know that we need to provide a callback that returns void and takes 
	two ``uint32_t`` parameters, the first being the old value and the second 
	being the new value:

Precisamos prover uma *callback* que retorne ``void`` e receba dois parmetros ``uint32_t``, o primeiro representando o valor antigo e o segundo o novo valor:

::

  void
  CwndTrace (uint32_t oldValue, uint32_t newValue)
  {
    ...
  }

.. 
	What Script to Use?

Qual cdigo Usar?
+++++++++++++++++

..
	It's always best to try and find working code laying around that you can 
	modify, rather than starting from scratch.  So the first order of business now
	is to find some code that already hooks the "CongestionWindow" trace source
	and see if we can modify it.  As usual, grep is your friend:

 sempre melhor localizar e modificar um cdigo operacional que iniciar do zero. Portanto, vamos procurar uma origem do rastreamento da "CongestionWindow" e verificar se  possvel modificar. Para tal, usamos novamente o *grep*:

::

  find . -name '*.cc' | xargs grep CongestionWindow

..
	This will point out a couple of promising candidates: 
	``examples/tcp/tcp-large-transfer.cc`` and 
	``src/test/ns3tcp/ns3tcp-cwnd-test-suite.cc``.

Encontramos alguns candidatos:
``examples/tcp/tcp-large-transfer.cc`` e
``src/test/ns3tcp/ns3tcp-cwnd-test-suite.cc``.

..
	We haven't visited any of the test code yet, so let's take a look there.  You
	will typically find that test code is fairly minimal, so this is probably a
	very good bet.  Open ``src/test/ns3tcp/ns3tcp-cwnd-test-suite.cc`` in your
	favorite editor and search for "CongestionWindow".  You will find,

Ns no visitamos nenhum cdigo de teste ainda, ento vamos fazer isto agora. Cdigo de teste  pequeno, logo  uma tima escolha. Acesse o arquivo ``src/test/ns3tcp/ns3tcp-cwnd-test-suite.cc`` e localize "CongestionWindow". Como resultado, temos

::

  ns3TcpSocket->TraceConnectWithoutContext ("CongestionWindow", 
    MakeCallback (&Ns3TcpCwndTestCase1::CwndChange, this));

..
	This should look very familiar to you.  We mentioned above that if we had a
	"CongestionWindow" trace source.  That's exactly what we have here; so it
	pointer to the ``TcpNewReno``, we could ``TraceConnect`` to the 
	turns out that this line of code does exactly what we want.  Let's go ahead
	and extract the code we need from this function 
	(``Ns3TcpCwndTestCase1::DoRun (void)``).  If you look at this function,
	you will find that it looks just like an |ns3| script.  It turns out that
	is exactly what it is.  It is a script run by the test framework, so we can just
	pull it out and wrap it in ``main`` instead of in ``DoRun``.  Rather than
	walk through this, step, by step, we have provided the file that results from
	porting this test back to a native |ns3| script --
	``examples/tutorial/fifth.cc``.  

Como abordado, temos uma origem do rastreamento  "CongestionWindow"; ento ela aponta para ``TcpNewReno``, poderamos alterar o ``TraceConnect`` para o que ns desejamos. Vamos extrair o cdigo que precisamos desta funo (``Ns3TcpCwndTestCase1::DoRun (void)``). Se voc observar, perceber que parece como um cdigo |ns3|. E descobre-se exatamente que realmente  um cdigo.  um cdigo executado pelo `framework` de teste, logo podemos apenas coloc-lo no ``main`` ao invs de ``DoRun``.  A traduo deste teste para um cdigo nativo do |ns3|  apresentada no arquivo ``examples/tutorial/fifth.cc``.


.. 
	A Common Problem and Solution

Um Problema Comum e a Soluo
+++++++++++++++++++++++++++++

..
	The ``fifth.cc`` example demonstrates an extremely important rule that you 
	must understand before using any kind of ``Attribute``:  you must ensure 
	that the target of a ``Config`` command exists before trying to use it.
	This is no different than saying an object must be instantiated before trying
	to call it.  Although this may seem obvious when stated this way, it does
	trip up many people trying to use the system for the first time.

O exemplo ``fifth.cc`` demonstra um importante regra que devemos entender antes de usar qualquer tipo de  Atributo: devemos garantir que o alvo de um comando ``Config`` existe antes de tentar us-lo.  a mesma ideia que um objeto no pode ser usado sem ser primeiro instanciado. Embora parea bvio, muitas pessoas erram ao usar o sistema pela primeira vez.

..
	Let's return to basics for a moment.  There are three basic time periods that
	exist in any |ns3| script.  The first time period is sometimes called 
	"Configuration Time" or "Setup Time," and is in force during the period 
	when the ``main`` function of your script is running, but before 
	``Simulator::Run`` is called.  The second time period  is sometimes called
	"Simulation Time" and is in force during the time period when 
	``Simulator::Run`` is actively executing its events.  After it completes
	executing the simulation,  ``Simulator::Run`` will return control back to 
	the ``main`` function.  When this happens, the script enters what can be 
	called "Teardown Time," which is when the structures and objects created 
	during setup and taken apart and released.

H trs fases bsicas em qualquer cdigo |ns3|. A primeira  a chamada de "Configuration Time" ou "Setup Time" e ocorre durante a execuo da funo ``main``, mas antes da chamada ``Simulator::Run``. O segunda fase  chamada de "Simulation Time" e  quando o ``Simulator::Run`` est executando seus eventos. Aps completar a execuo da simulao, ``Simulator::Run`` devolve o controle a funo ``main``. Quando isto acontece, o cdigo entra na terceira fase, o "Teardown Time", que   quando estruturas e objetos criados durante a configurao so analisados e liberados.

..
	Perhaps the most common mistake made in trying to use the tracing system is 
	assuming that entities constructed dynamically during simulation time are
	available during configuration time.  In particular, an |ns3|
	``Socket`` is a dynamic object often created by ``Applications`` to
	communicate between ``Nodes``.  An |ns3| ``Application`` 
	always has a "Start Time" and a "Stop Time" associated with it.  In the
	vast majority of cases, an ``Application`` will not attempt to create 
	a dynamic object until its ``StartApplication`` method is called at some
	"Start Time".  This is to ensure that the simulation is completely 
	configured before the app tries to do anything (what would happen if it tried
	to connect to a node that didn't exist yet during configuration time). 
	The answer to this issue is to 1) create a simulator event that is run after the 
	dynamic object is created and hook the trace when that event is executed; or
	2) create the dynamic object at configuration time, hook it then, and give 
	the object to the system to use during simulation time.  We took the second 
	approach in the ``fifth.cc`` example.  This decision required us to create
	the ``MyApp`` ``Application``, the entire purpose of which is to take 
	a ``Socket`` as a parameter.  

Talvez o erro mais comum em tentar usar o sistema de rastreamento  supor que entidades construdas dinamicamente durante a fase de simulao esto acessveis durante  a fase de configurao. Em particular, um ``Socket`` |ns3|  um objeto dinmico frequentemente criado por Aplicaes (``Applications``) para comunicao entre ns de redes.  Uma Aplicao |ns3| tem um "Start Time" e "Stop Time" associado a ela. Na maioria dos casos, uma Aplicao no tentar criar um objeto dinmico at que seu mtodo ``StartApplication``  chamado
em algum "Start Time". Isto  para garantir que a simulao est completamente configurada antes que a aplicao tente fazer alguma coisa (o que aconteceria se tentasse conectar a um n que no existisse durante a fase de configurao). A resposta para esta questo :
	
1. criar um evento no simulador que  executado depois que o objeto dinmico 
    criado e ativar o rastreador quando aquele evento  executado; ou 
2. criar o objeto dinmico na fase de configurao, ativ-lo,
   e passar o objeto para o sistema usar durante a fase de simulao. 

Ns consideramos a segunda abordagem no exemplo ``fifth.cc``. A deciso implicou na criao da Aplicao ``MyApp``, com o propsito de passar um ``Socket`` como parmetro.

.. 
	A fifth.cc Walkthrough

Analisando o exemplo fifth.cc
+++++++++++++++++++++++++++++

..
	Now, let's take a look at the example program we constructed by dissecting
	the congestion window test.  Open ``examples/tutorial/fifth.cc`` in your
	favorite editor.  You should see some familiar looking code:

Agora, vamos analisar o programa exemplo detalhando o teste da janela de congestionamento.
Segue o cdigo do arquivo localizado em ``examples/tutorial/fifth.cc``:

::

  /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
  /*
   * This program is free software; you can redistribute it and/or modify
   * it under the terms of the GNU General Public License version 2 as
   * published by the Free Software Foundation;
   *
   * This program is distributed in the hope that it will be useful,
   * but WITHOUT ANY WARRANTY; without even the implied warranty of
   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   * GNU General Public License for more details.
   *
   * You should have received a copy of the GNU General Public License
   * along with this program; if not, write to the Free Software
   * Foundation, Include., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   */
  
  #include <fstream>
  #include "ns3/core-module.h"
  #include "ns3/network-module.h"
  #include "ns3/internet-module.h"
  #include "ns3/point-to-point-module.h"
  #include "ns3/applications-module.h"
  
  using namespace ns3;
  
  NS_LOG_COMPONENT_DEFINE ("FifthScriptExample");

..
	This has all been covered, so we won't rehash it.  The next lines of source are
	the network illustration and a comment addressing the problem described above
	with ``Socket``.

Todo o cdigo apresentado j foi discutido. As prximas linhas so comentrios apresentando
a estrutura da rede e comentrios abordando o problema descrito com o ``Socket``.

::

  // ===========================================================================
  //
  //         node 0                 node 1
  //   +----------------+    +----------------+
  //   |    ns-3 TCP    |    |    ns-3 TCP    |
  //   +----------------+    +----------------+
  //   |    10.1.1.1    |    |    10.1.1.2    |
  //   +----------------+    +----------------+
  //   | point-to-point |    | point-to-point |
  //   +----------------+    +----------------+
  //           |                     |
  //           +---------------------+
  //                5 Mbps, 2 ms
  //
  //
  // We want to look at changes in the ns-3 TCP congestion window.  We need
  // to crank up a flow and hook the CongestionWindow attribute on the socket
  // of the sender.  Normally one would use an on-off application to generate a
  // flow, but this has a couple of problems.  First, the socket of the on-off
  // application is not created until Application Start time, so we wouldn't be
  // able to hook the socket (now) at configuration time.  Second, even if we
  // could arrange a call after start time, the socket is not public so we
  // couldn't get at it.
  //
  // So, we can cook up a simple version of the on-off application that does what
  // we want.  On the plus side we don't need all of the complexity of the on-off
  // application.  On the minus side, we don't have a helper, so we have to get
  // a little more involved in the details, but this is trivial.
  //
  // So first, we create a socket and do the trace connect on it; then we pass
  // this socket into the constructor of our simple application which we then
  // install in the source node.
  // ===========================================================================
  //

.. 
	This should also be self-explanatory.  

..
	The next part is the declaration of the ``MyApp`` ``Application`` that
	we put together to allow the ``Socket`` to be created at configuration time.

A prxima parte  a declarao da Aplicao ``MyApp`` que permite que o ``Socket`` seja criado na fase de configurao.

::

  class MyApp : public Application
  {
  public:
  
    MyApp ();
    virtual ~MyApp();
  
    void Setup (Ptr<Socket> socket, Address address, uint32_t packetSize, 
      uint32_t nPackets, DataRate dataRate);
  
  private:
    virtual void StartApplication (void);
    virtual void StopApplication (void);
  
    void ScheduleTx (void);
    void SendPacket (void);
  
    Ptr<Socket>     m_socket;
    Address         m_peer;
    uint32_t        m_packetSize;
    uint32_t        m_nPackets;
    DataRate        m_dataRate;
    EventId         m_sendEvent;
    bool            m_running;
    uint32_t        m_packetsSent;
  };

..
	You can see that this class inherits from the |ns3| ``Application``
	class.  Take a look at ``src/network/model/application.h`` if you are interested in 
	what is inherited.  The ``MyApp`` class is obligated to override the 
	``StartApplication`` and ``StopApplication`` methods.  These methods are
	automatically called when ``MyApp`` is required to start and stop sending
	data during the simulation.

A classe ``MyApp`` herda a classe ``Application`` do |ns3|. Acesse  o arquivo ``src/network/model/application.h`` se estiver interessado sobre detalhes dessa herana. A classe ``MyApp``  obrigada sobrescrever os mtodos ``StartApplication`` e ``StopApplication``. Estes mtodos so automaticamente chamado quando ``MyApp``  solicitada iniciar e parar de enviar dados durante a simulao.

.. 
	How Applications are Started and Stopped (optional)

Como Aplicaes so Iniciadas e Paradas (Opcional)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

..
	It is worthwhile to spend a bit of time explaining how events actually get 
	started in the system.  This is another fairly deep explanation, and can be
	ignored if you aren't planning on venturing down into the guts of the system.
	It is useful, however, in that the discussion touches on how some very important
	parts of |ns3| work and exposes some important idioms.  If you are 
	planning on implementing new models, you probably want to understand this
	section.

Nesta seo  explicado como eventos tem incio no sistema.  uma explicao mais detalhada e no  necessria se no planeja entender detalhes do sistema.  interessante, por outro lado, pois aborda como partes do |ns3| trabalham e mostra alguns detalhes de implementao importantes. Se voc planeja implementar novos modelos, ento deve entender essa seo.

..
	The most common way to start pumping events is to start an ``Application``.
	This is done as the result of the following (hopefully) familar lines of an 
	|ns3| script:

A maneira mais comum de iniciar eventos  iniciar uma Aplicao. Segue as linhas de um cdigo |ns3| que faz exatamente isso:

::

  ApplicationContainer apps = ...
  apps.Start (Seconds (1.0));
  apps.Stop (Seconds (10.0));

..
	The application container code (see ``src/network/helper/application-container.h`` if
	you are interested) loops through its contained applications and calls,

O cdigo do continer aplicao (``src/network/helper/application-container.h``) itera pelas aplicaes no continer e chama,

::

  app->SetStartTime (startTime);

.. 
	as a result of the ``apps.Start`` call and

como um resultado da chamada ``apps.Start`` e

::

  app->SetStopTime (stopTime);

.. 
	as a result of the ``apps.Stop`` call.

como um resultado da chamada  ``apps.Stop``.

..
	The ultimate result of these calls is that we want to have the simulator 
	automatically make calls into our ``Applications`` to tell them when to
	start and stop.  In the case of ``MyApp``, it inherits from class
	``Application`` and overrides ``StartApplication``, and 
	``StopApplication``.  These are the functions that will be called by
	the simulator at the appropriate time.  In the case of ``MyApp`` you
	will find that ``MyApp::StartApplication`` does the initial ``Bind``,
	and ``Connect`` on the socket, and then starts data flowing by calling
	``MyApp::SendPacket``.  ``MyApp::StopApplication`` stops generating
	packets by cancelling any pending send events and closing the socket.

O ltimo resultado destas chamadas queremos ter o simulador executando chamadas em nossa ``Applications`` para controlar o inicio e a parada. No caso ``MyApp``, herda da classe ``Application`` e sobrescreve ``StartApplication`` e ``StopApplication``. Estas so as funes invocadas pelo simulador no momento certo. No caso de ``MyApp``, o ``MyApp::StartApplication`` faz o ``Bind`` e ``Connect`` no `socket`, em seguida, inicia o fluxo de dados chamando ``MyApp::SendPacket``. ``MyApp::StopApplication`` interrompe a gerao de pacotes cancelando qualquer evento pendente de envio e tambm fechando o socket.

..
	One of the nice things about |ns3| is that you can completely 
	ignore the implementation details of how your ``Application`` is 
	"automagically" called by the simulator at the correct time.  But since
	we have already ventured deep into |ns3| already, let's go for it.

Uma das coisas legais sobre o |ns3|  que podemos ignorar completamente os detalhes de implementao de como sua Aplicao  "automaticamente" chamada pelo simulador no momento correto. De qualquer forma, detalhamos como isso acontece a seguir.

..
	If you look at ``src/network/model/application.cc`` you will find that the
	``SetStartTime`` method of an ``Application`` just sets the member 
	variable ``m_startTime`` and the ``SetStopTime`` method just sets 
	``m_stopTime``.  From there, without some hints, the trail will probably
	end.

Se observarmos em ``src/network/model/application.cc``, descobriremos que o 
mtodo ``SetStartTime`` de uma ``Application`` apenas altera a varivel ``m_startTime`` e o mtodo ``SetStopTime`` apenas altera a varivel ``m_stopTime``.  

..
	The key to picking up the trail again is to know that there is a global 
	list of all of the nodes in the system.  Whenever you create a node in 
	a simulation, a pointer to that node is added to the global ``NodeList``.

Para continuar e entender o processo, precisamos saber que h uma lista global de todos os ns no sistema. Sempre que voc cria um n em uma simulao, um ponteiro para aquele n  adicionado para a lista global ``NodeList``.

..
	Take a look at ``src/network/model/node-list.cc`` and search for 
	``NodeList::Add``.  The public static implementation calls into a private
	implementation called ``NodeListPriv::Add``.  This is a relatively common
	idom in |ns3|.  So, take a look at ``NodeListPriv::Add``.  There
	you will find,

Observe em ``src/network/model/node-list.cc`` e procure por ``NodeList::Add``. A implementao ``public static`` chama uma implementao privada denominada ``NodeListPriv::Add``. Isto  comum no |ns3|. Ento, observe ``NodeListPriv::Add`` e encontrar,

::

  Simulator::ScheduleWithContext (index, TimeStep (0), &Node::Start, node);

..
	This tells you that whenever a ``Node`` is created in a simulation, as
	a side-effect, a call to that node's ``Start`` method is scheduled for
	you that happens at time zero.  Don't read too much into that name, yet.
	It doesn't mean that the node is going to start doing anything, it can be
	interpreted as an informational call into the ``Node`` telling it that 
	the simulation has started, not a call for action telling the ``Node``
	to start doing something.

Isto significa que sempre que um ``Node``  criado em uma simulao, como uma implicao, uma chamada para o mtodo ``Start`` do n  agendada para que ocorra no tempo zero. Isto no significa que o n vai iniciar fazendo alguma coisa, pode ser interpretado como uma chamada informacional no ``Node`` dizendo a ele que a simulao teve incio, no uma chamada para ao dizendo ao ``Node`` iniciar alguma coisa.

..
	So, ``NodeList::Add`` indirectly schedules a call to ``Node::Start``
	at time zero to advise a new node that the simulation has started.  If you 
	look in ``src/network/model/node.h`` you will, however, not find a method called
	``Node::Start``.  It turns out that the ``Start`` method is inherited
	from class ``Object``.  All objects in the system can be notified when
	the simulation starts, and objects of class ``Node`` are just one kind
	of those objects.

Ento, o ``NodeList::Add`` indiretamente agenda uma chamada para ``Node::Start`` no tempo zero, para informar ao novo n que a simulao foi iniciada. Se olharmos em ``src/network/model/node.h`` no acharemos um mtodo chamado ``Node::Start``. Acontece que o mtodo ``Start``  herdado da classe ``Object``. Todos objetos no sistema podem ser avisados que a simulao iniciou e objetos da classe ``Node`` so exemplos.

..
	Take a look at ``src/core/model/object.cc`` next and search for ``Object::Start``.
	This code is not as straightforward as you might have expected since 
	|ns3| ``Objects`` support aggregation.  The code in 
	``Object::Start`` then loops through all of the objects that have been
	aggregated together and calls their ``DoStart`` method.  This is another
	idiom that is very common in |ns3|.  There is a public API method,
	that stays constant across implementations, that calls a private implementation
	method that is inherited and implemented by subclasses.  The names are typically
	something like ``MethodName`` for the public API and ``DoMethodName`` for
	the private API.

Observe em seguida ``src/core/model/object.cc``. Localize por ``Object::Start``. Este cdigo no  to simples como voc esperava desde que ``Objects`` |ns3| suportam agregao. O cdigo em ``Object::Start`` ento percorre todos os objetos que esto agregados e chama o mtodo ``DoStart`` de cada um. Este  uma outra prtica muito comum em |ns3|. H um mtodo pblica na API, que permanece constante entre implementaes, que chama um mtodo de implementao privada que  herdado e implementado por subclasses. Os nomes so tipicamente
algo como ``MethodName`` para os da API pblica e ``DoMethodName`` para os da API privada.

..
	This tells us that we should look for a ``Node::DoStart`` method in 
	``src/network/model/node.cc`` for the method that will continue our trail.  If you
	locate the code, you will find a method that loops through all of the devices
	in the node and then all of the applications in the node calling 
	``device->Start`` and ``application->Start`` respectively.

Logo, deveramos procurar por um mtodo ``Node::DoStart`` em  ``src/network/model/node.cc``. Ao localizar o mtodo, descobrir um mtodo que percorre todos os dispositivos e aplicaes no n chamando respectivamente ``device->Start`` e ``application->Start``.

..
	You may already know that classes ``Device`` and ``Application`` both
	inherit from class ``Object`` and so the next step will be to look at
	what happens when ``Application::DoStart`` is called.  Take a look at
	``src/network/model/application.cc`` and you will find:

As classes ``Device`` e ``Application`` herdam da classe ``Object``, ento o prximo passo  entender o que acontece quando ``Application::DoStart``  executado. Observe o cdigo em ``src/network/model/application.cc``:

::

  void
  Application::DoStart (void)
  {
    m_startEvent = Simulator::Schedule (m_startTime, &Application::StartApplication, this);
    if (m_stopTime != TimeStep (0))
      {
        m_stopEvent = Simulator::Schedule (m_stopTime, &Application::StopApplication, this);
      }
    Object::DoStart ();
  }

..
	Here, we finally come to the end of the trail.  If you have kept it all straight,
	when you implement an |ns3| ``Application``, your new application 
	inherits from class ``Application``.  You override the ``StartApplication``
	and ``StopApplication`` methods and provide mechanisms for starting and 
	stopping the flow of data out of your new ``Application``.  When a ``Node``
	is created in the simulation, it is added to a global ``NodeList``.  The act
	of adding a node to this ``NodeList`` causes a simulator event to be scheduled
	for time zero which calls the ``Node::Start`` method of the newly added 
	``Node`` to be called when the simulation starts.  Since a ``Node`` inherits
	from ``Object``, this calls the ``Object::Start`` method on the ``Node``
	which, in turn, calls the ``DoStart`` methods on all of the ``Objects``
	aggregated to the ``Node`` (think mobility models).  Since the ``Node``
	``Object`` has overridden ``DoStart``, that method is called when the 
	simulation starts.  The ``Node::DoStart`` method calls the ``Start`` methods
	of all of the ``Applications`` on the node.  Since ``Applications`` are
	also ``Objects``, this causes ``Application::DoStart`` to be called.  When
	``Application::DoStart`` is called, it schedules events for the 
	``StartApplication`` and ``StopApplication`` calls on the ``Application``.
	These calls are designed to start and stop the flow of data from the 
	``Application``

Aqui finalizamos nosso detalhamento. Ao implementar uma Aplicao do |ns3|, sua nova aplicao herda da classe ``Application``. Voc sobrescreve os mtodos ``StartApplication`` e ``StopApplication`` e prov mecanismos para iniciar e finalizar o fluxo de dados de sua nova ``Application``. Quando um ``Node``  criado na simulao, ele  adicionado a uma lista global ``NodeList``. A ao de adicionar um n na lista faz com que um evento do simulador seja agendado para o tempo zero e que chama o mtodo ``Node::Start`` do ``Node`` recentemente adicionado para ser chamado quando a simulao inicia. Como um ``Node`` herda de ``Object``,
a chamada invoca o mtodo ``Object::Start`` no ``Node``, o qual, por sua vez, chama os mtodos ``DoStart`` em todos os ``Objects`` agregados ao ``Node`` (pense em modelos mveis).  Como o ``Node`` ``Object`` 
tem sobrescritos ``DoStart``, o mtodo  chamado quando a simulao inicia. O mtodo ``Node::DoStart`` chama o mtodo ``Start`` de todas as ``Applications`` no n. Por sua vez, ``Applications`` so tambm ``Objects``, o que resulta na invocao do ``Application::DoStart``.  Quando ``Application::DoStart``  chamada, ela agenda eventos para as chamadas ``StartApplication`` e ``StopApplication`` na ``Application``. Estas chamadas so projetadas para iniciar e parar o fluxo de dados da ``Application``.

..
	This has been another fairly long journey, but it only has to be made once, and
	you now understand another very deep piece of |ns3|.

Aps essa longa jornada, voc pode entende melhor outra parte do |ns3|.

..
	The MyApp Application

A Aplicao MyApp
~~~~~~~~~~~~~~~~~

..
	The ``MyApp`` ``Application`` needs a constructor and a destructor,
	of course:

A Aplicao ``MyApp`` precisa de um construtor e um destrutor,

::

  MyApp::MyApp ()
    : m_socket (0),
      m_peer (),
      m_packetSize (0),
      m_nPackets (0),
      m_dataRate (0),
      m_sendEvent (),
      m_running (false),
      m_packetsSent (0)
  {
  }
  
  MyApp::~MyApp()
  {
    m_socket = 0;
  }

..
	The existence of the next bit of code is the whole reason why we wrote this
	``Application`` in the first place.

O cdigo seguinte  a principal razo da existncia desta Aplicao.

::

  void
  MyApp::Setup (Ptr<Socket> socket, Address address, uint32_t packetSize, 
                       uint32_t nPackets, DataRate dataRate)
  {
    m_socket = socket;
    m_peer = address;
    m_packetSize = packetSize;
    m_nPackets = nPackets;
    m_dataRate = dataRate;
  }

..  
	This code should be pretty self-explanatory.  We are just initializing member
	variables.  The important one from the perspective of tracing is the 
	``Ptr<Socket> socket`` which we needed to provide to the application 
	during configuration time.  Recall that we are going to create the ``Socket``
	as a ``TcpSocket`` (which is implemented by ``TcpNewReno``) and hook 
	its "CongestionWindow" trace source before passing it to the ``Setup``
	method.

Neste cdigo inicializamos os atributos da classe. Do ponto de vista do rastreamento, a mais importante  ``Ptr<Socket> socket`` que deve ser passado para a aplicao durante o fase de configurao. Lembre-se que vamos criar o ``Socket`` como um ``TcpSocket`` (que  implementado por ``TcpNewReno``) e associar sua origem do rastreamento de sua *"CongestionWindow"* antes de pass-lo no mtodo ``Setup``.

::

  void
  MyApp::StartApplication (void)
  {
    m_running = true;
    m_packetsSent = 0;
    m_socket->Bind ();
    m_socket->Connect (m_peer);
    SendPacket ();
  }

..
	The above code is the overridden implementation ``Application::StartApplication``
	that will be automatically called by the simulator to start our ``Application``
	running at the appropriate time.  You can see that it does a ``Socket`` ``Bind``
	operation.  If you are familiar with Berkeley Sockets this shouldn't be a surprise.
	It performs the required work on the local side of the connection just as you might 
	expect.  The following ``Connect`` will do what is required to establish a connection 
	with the TCP at ``Address`` m_peer.  It should now be clear why we need to defer
	a lot of this to simulation time, since the ``Connect`` is going to need a fully
	functioning network to complete.  After the ``Connect``, the ``Application`` 
	then starts creating simulation events by calling ``SendPacket``.

Este cdigo sobrescreve ``Application::StartApplication`` que ser chamado automaticamente pelo simulador para iniciar a  ``Application`` no momento certo. Observamos que  realizada uma operao ``Socket`` ``Bind``. Se voc conhece Sockets de Berkeley isto no  uma novidade.  responsvel pelo conexo no lado do cliente, ou seja, o ``Connect`` estabelece uma  conexo usando TCP no endereo ``m_peer``. Por isso, precisamos de uma infraestrutura funcional de rede antes de executar a fase de simulao. Depois do ``Connect``, a ``Application`` inicia a criao dos eventos de simulao chamando ``SendPacket``.

::

  void
  MyApp::StopApplication (void)
  {
    m_running = false;
  
    if (m_sendEvent.IsRunning ())
      {
        Simulator::Cancel (m_sendEvent);
      }
  
    if (m_socket)
      {
        m_socket->Close ();
      }
  }

..
	Every time a simulation event is scheduled, an ``Event`` is created.  If the 
	``Event`` is pending execution or executing, its method ``IsRunning`` will
	return ``true``.  In this code, if ``IsRunning()`` returns true, we 
	``Cancel`` the event which removes it from the simulator event queue.  By 
	doing this, we break the chain of events that the ``Application`` is using to
	keep sending its ``Packets`` and the ``Application`` goes quiet.  After we 
	quiet the ``Application`` we ``Close`` the socket which tears down the TCP 
	connection.

A todo instante um evento da simulao  agendado, isto , um ``Event``  criado. Se o ``Event``  uma execuo pendente ou est executando, seu mtodo ``IsRunning`` retornar ``true``. Neste cdigo, se ``IsRunning()`` retorna verdadeiro (`true`), ns cancelamos (``Cancel``) o evento, e por consequncia,  removido da fila de eventos do simulador. Dessa forma, interrompemos a cadeia de eventos que a 
``Application`` est usando para enviar seus ``Packets``. A Aplicao no enviar mais pacotes e em seguida fechamos (``Close``) o `socket` encerrando a conexo TCP.

..
	The socket is actually deleted in the destructor when the ``m_socket = 0`` is
	executed.  This removes the last reference to the underlying Ptr<Socket> which 
	causes the destructor of that Object to be called.

O socket  deletado no destrutor quando ``m_socket = 0``  executado. Isto remove a ltima referncia para Ptr<Socket>  que ocasiona o destrutor daquele Objeto ser chamado.

..
	Recall that ``StartApplication`` called ``SendPacket`` to start the 
	chain of events that describes the ``Application`` behavior.

Lembre-se que ``StartApplication`` chamou ``SendPacket`` para iniciar a cadeia de eventos que descreve o comportamento da ``Application``.

::

  void
  MyApp::SendPacket (void)
  {
    Ptr<Packet> packet = Create<Packet> (m_packetSize);
    m_socket->Send (packet);
  
    if (++m_packetsSent < m_nPackets)
      {
        ScheduleTx ();
      }
  }

..
	Here, you see that ``SendPacket`` does just that.  It creates a ``Packet``
	and then does a ``Send`` which, if you know Berkeley Sockets, is probably 
	just what you expected to see.

Este cdigo apenas cria um pacote (``Packet``) e ento envia (``Send``).

..
	It is the responsibility of the ``Application`` to keep scheduling the 
	chain of events, so the next lines call ``ScheduleTx`` to schedule another
	transmit event (a ``SendPacket``) until the ``Application`` decides it
	has sent enough.

 responsabilidade da ``Application`` gerenciar o agendamento da cadeia de eventos, ento, a chamada ``ScheduleTx`` agenda outro evento de transmisso (um ``SendPacket``) at que a ``Application`` decida que enviou o suficiente.

::

  void
  MyApp::ScheduleTx (void)
  {
    if (m_running)
      {
        Time tNext (Seconds (m_packetSize * 8 / static_cast<double> (m_dataRate.GetBitRate ())));
        m_sendEvent = Simulator::Schedule (tNext, &MyApp::SendPacket, this);
      }
  }

..
	Here, you see that ``ScheduleTx`` does exactly that.  If the ``Application``
	is running (if ``StopApplication`` has not been called) it will schedule a 
	new event, which calls ``SendPacket`` again.  The alert reader will spot
	something that also trips up new users.  The data rate of an ``Application`` is
	just that.  It has nothing to do with the data rate of an underlying ``Channel``.
	This is the rate at which the ``Application`` produces bits.  It does not take
	into account any overhead for the various protocols or channels that it uses to 
	transport the data.  If you set the data rate of an ``Application`` to the same
	data rate as your underlying ``Channel`` you will eventually get a buffer overflow.

Enquanto a ``Application`` est executando, ``ScheduleTx`` agendar um novo evento, que chama ``SendPacket`` novamente. Verifica-se que a taxa de transmisso  sempre a mesma, ou seja,  a taxa que a ``Application`` produz os bits. No considera nenhuma sobrecarga de protocolos ou canais fsicos no transporte dos dados. Se alterarmos a taxa de transmisso da ``Application`` para a mesma taxa dos canais fsicos,  poderemos
ter um estouro de *buffer*.

.. 
	The Trace Sinks

Destino do Rastreamento
~~~~~~~~~~~~~~~~~~~~~~~

..
	The whole point of this exercise is to get trace callbacks from TCP indicating the
	congestion window has been updated.  The next piece of code implements the 
	corresponding trace sink:

O foco deste exerccio  obter notificaes (*callbacks*) do TCP indicando a modificao da janela de congestionamento. O cdigo a seguir implementa o destino do rastreamento.

::

  static void
  CwndChange (uint32_t oldCwnd, uint32_t newCwnd)
  {
    NS_LOG_UNCOND (Simulator::Now ().GetSeconds () << "\t" << newCwnd);
  }

..
	This should be very familiar to you now, so we won't dwell on the details.  This
	function just logs the current simulation time and the new value of the 
	congestion window every time it is changed.  You can probably imagine that you
	could load the resulting output into a graphics program (gnuplot or Excel) and
	immediately see a nice graph of the congestion window behavior over time.

Esta funo registra o tempo de simulao atual e o novo valor da janela de congestionamento toda vez que  modificada. Poderamos usar essa sada para construir um grfico  do comportamento da janela de congestionamento com relao ao tempo.

..
	We added a new trace sink to show where packets are dropped.  We are going to 
	add an error model to this code also, so we wanted to demonstrate this working.

Ns adicionamos um novo destino do rastreamento para mostrar onde pacotes so perdidos. Vamos adicionar um modelo de erro.

::

  static void
  RxDrop (Ptr<const Packet> p)
  {
    NS_LOG_UNCOND ("RxDrop at " << Simulator::Now ().GetSeconds ());
  }

..
	This trace sink will be connected to the "PhyRxDrop" trace source of the 
	point-to-point NetDevice.  This trace source fires when a packet is dropped
	by the physical layer of a ``NetDevice``.  If you take a small detour to the
	source (``src/point-to-point/model/point-to-point-net-device.cc``) you will
	see that this trace source refers to ``PointToPointNetDevice::m_phyRxDropTrace``.
	If you then look in ``src/point-to-point/model/point-to-point-net-device.h``
	for this member variable, you will find that it is declared as a
	``TracedCallback<Ptr<const Packet> >``.  This should tell you that the
	callback target should be a function that returns void and takes a single
	parameter which is a ``Ptr<const Packet>`` -- just what we have above.

Este destino do rastreamento ser conectado a origem do rastreamento "PhyRxDrop" do ``NetDevice`` ponto-a-ponto. Esta origem do rastreamento dispara quando um pacote  removido da camada fsica de um ``NetDevice``. Se olharmos rapidamente ``src/point-to-point/model/point-to-point-net-device.cc`` verificamos que a origem do rastreamento refere-se a ``PointToPointNetDevice::m_phyRxDropTrace``. E se procurarmos em ``src/point-to-point/model/point-to-point-net-device.h`` por essa varivel, encontraremos que ela est declarada como uma ``TracedCallback<Ptr<const Packet> >``. Isto significa que nosso *callback* deve ser uma funo que retorna ``void`` e tem um nico parmetro ``Ptr<const Packet>``.


.. 
	The Main Program

O Programa Principal
~~~~~~~~~~~~~~~~~~~~

.. 
	The following code should be very familiar to you by now:

O cdigo a seguir corresponde ao incio da funo principal:

::

  int
  main (int argc, char *argv[])
  {
    NodeContainer nodes;
    nodes.Create (2);
  
    PointToPointHelper pointToPoint;
    pointToPoint.SetDeviceAttribute ("DataRate", StringValue ("5Mbps"));
    pointToPoint.SetChannelAttribute ("Delay", StringValue ("2ms"));
  
    NetDeviceContainer devices;
    devices = pointToPoint.Install (nodes);

..
	This creates two nodes with a point-to-point channel between them, just as
	shown in the illustration at the start of the file.

So criados dois ns ligados por um canal ponto-a-ponto, como mostrado na ilustrao
no incio do arquivo.

..
	The next few lines of code show something new.  If we trace a connection that
	behaves perfectly, we will end up with a monotonically increasing congestion
	window.  To see any interesting behavior, we really want to introduce link 
	errors which will drop packets, cause duplicate ACKs and trigger the more
	interesting behaviors of the congestion window.


Nas prximas linhas, temos um cdigo com algumas informaes novas. Se ns 

rastrearmos uma conexo que comporta-se perfeitamente, terminamos com um

janela de congestionamento que aumenta monoliticamente. Para observarmos um

comportamento interessante, introduzimos erros que causaro perda de pacotes,

duplicao de ACK's e assim, introduz comportamentos mais interessantes a

janela de congestionamento.


..
	|ns3| provides ``ErrorModel`` objects which can be attached to
	``Channels``.  We are using the ``RateErrorModel`` which allows us
	to introduce errors into a ``Channel`` at a given *rate*. 


O |ns3| prov objetos de um modelo de erros (``ErrorModel``) que pode ser adicionado aos canais (``Channels``). Ns usamos o ``RateErrorModel`` que permite introduzir erros no canal dada uma *taxa*.

::

  Ptr<RateErrorModel> em = CreateObjectWithAttributes<RateErrorModel> (
    "RanVar", RandomVariableValue (UniformVariable (0., 1.)),
    "ErrorRate", DoubleValue (0.00001));
  devices.Get (1)->SetAttribute ("ReceiveErrorModel", PointerValue (em));

..
	The above code instantiates a ``RateErrorModel`` Object.  Rather than 
	using the two-step process of instantiating it and then setting Attributes,
	we use the convenience function ``CreateObjectWithAttributes`` which
	allows us to do both at the same time.  We set the "RanVar" 
	``Attribute`` to a random variable that generates a uniform distribution
	from 0 to 1.  We also set the "ErrorRate" ``Attribute``.
	We then set the resulting instantiated ``RateErrorModel`` as the error
	model used by the point-to-point ``NetDevice``.  This will give us some
	retransmissions and make our plot a little more interesting.

O cdigo instancia um objeto ``RateErrorModel``. Para simplificar usamos a funo ``CreateObjectWithAttributes`` que instancia e configura os Atributos. O Atributo "RanVar" foi configurado para uma varivel randmica que gera uma distribuio uniforme entre 0 e 1. O Atributo "ErrorRate" tambm foi alterado. Por fim, configuramos o modelo erro no ``NetDevice`` ponto-a-ponto modificando o atributo "ReceiveErrorModel".  Isto causar retransmisses e o grfico ficar mais interessante.

::

  InternetStackHelper stack;
  stack.Install (nodes);

  Ipv4AddressHelper address;
  address.SetBase ("10.1.1.0", "255.255.255.252");
  Ipv4InterfaceContainer interfaces = address.Assign (devices);

..
	The above code should be familiar.  It installs internet stacks on our two
	nodes and creates interfaces and assigns IP addresses for the point-to-point
	devices.

Neste cdigo configura a pilha de protocolos da internet nos dois ns de rede, cria interfaces e associa endereos IP para os dispositivos ponto-a-ponto.

..
	Since we are using TCP, we need something on the destination node to receive
	TCP connections and data.  The ``PacketSink`` ``Application`` is commonly
	used in |ns3| for that purpose.

Como estamos usando TCP, precisamos de um n de destino para receber as conexes e os dados.  O ``PacketSink`` ``Application``   comumente usado no |ns3| para este propsito.

::

  uint16_t sinkPort = 8080;
  Address sinkAddress (InetSocketAddress(interfaces.GetAddress (1), sinkPort));
  PacketSinkHelper packetSinkHelper ("ns3::TcpSocketFactory", 
    InetSocketAddress (Ipv4Address::GetAny (), sinkPort));
  ApplicationContainer sinkApps = packetSinkHelper.Install (nodes.Get (1));
  sinkApps.Start (Seconds (0.));
  sinkApps.Stop (Seconds (20.));

.. 
	This should all be familiar, with the exception of,

Este cdigo deveria ser familiar, com exceo de,

::

  PacketSinkHelper packetSinkHelper ("ns3::TcpSocketFactory", 
    InetSocketAddress (Ipv4Address::GetAny (), sinkPort));

..
	This code instantiates a ``PacketSinkHelper`` and tells it to create sockets
	using the class ``ns3::TcpSocketFactory``.  This class implements a design 
	pattern called "object factory" which is a commonly used mechanism for 
	specifying a class used to create objects in an abstract way.  Here, instead of 
	having to create the objects themselves, you provide the ``PacketSinkHelper``
	a string that specifies a ``TypeId`` string used to create an object which 
	can then be used, in turn, to create instances of the Objects created by the 
	factory.

Este cdigo instancia um ``PacketSinkHelper`` e cria sockets usando a classe ``ns3::TcpSocketFactory``. Esta classe implementa o padro de projeto "fbrica de objetos". Dessa forma, em vez de criar os objetos diretamente, fornecemos ao ``PacketSinkHelper`` um texto que especifica um ``TypeId`` usado para criar
um objeto que, por sua vez, pode ser usado para criar instncias de Objetos criados pela implementao da fbrica de objetos.

..
	The remaining parameter tells the ``Application`` which address and port it
	should ``Bind`` to.

O parmetro seguinte especifica o endereo e a porta para o mapeamento.

.. 
	The next two lines of code will create the socket and connect the trace source.

As prximas duas linhas do cdigo criam o `socket` e conectam a origem do rastreamento.

::

  Ptr<Socket> ns3TcpSocket = Socket::CreateSocket (nodes.Get (0), 
    TcpSocketFactory::GetTypeId ());
  ns3TcpSocket->TraceConnectWithoutContext ("CongestionWindow", 
    MakeCallback (&CwndChange));

..
	The first statement calls the static member function ``Socket::CreateSocket``
	and provides a ``Node`` and an explicit ``TypeId`` for the object factory
	used to create the socket.  This is a slightly lower level call than the 
	``PacketSinkHelper`` call above, and uses an explicit C++ type instead of 
	one referred to by a string.  Otherwise, it is conceptually the same thing.

A primeira declarao chama a funo esttica ``Socket::CreateSocket`` e passa um ``Node`` e um ``TypeId`` para o objeto fbrica usado para criar o `socket`. 

..
	Once the ``TcpSocket`` is created and attached to the ``Node``, we can
	use ``TraceConnectWithoutContext`` to connect the CongestionWindow trace 
	source to our trace sink.

Uma vez que o ``TcpSocket``  criado e adicionado ao ``Node``, ns usamos ``TraceConnectWithoutContext`` para conectar a origem do rastreamento "CongestionWindow" para o nosso destino do rastreamento.

..
	Recall that we coded an ``Application`` so we could take that ``Socket``
	we just made (during configuration time) and use it in simulation time.  We now 
	have to instantiate that ``Application``.  We didn't go to any trouble to
	create a helper to manage the ``Application`` so we are going to have to 
	create and install it "manually".  This is actually quite easy:

Codificamos uma ``Application`` ento podemos obter um ``Socket`` (durante a fase de configurao) e usar na fase de simulao. Temos agora que instanciar a ``Application``. Para tal, segue os passos:

::

  Ptr<MyApp> app = CreateObject<MyApp> ();
  app->Setup (ns3TcpSocket, sinkAddress, 1040, 1000, DataRate ("1Mbps"));
  nodes.Get (0)->AddApplication (app);
  app->Start (Seconds (1.));
  app->Stop (Seconds (20.));

..
	The first line creates an ``Object`` of type ``MyApp`` -- our
	``Application``.  The second line tells the ``Application`` what
	``Socket`` to use, what address to connect to, how much data to send 
	at each send event, how many send events to generate and the rate at which
	to produce data from those events.

A primeira linha cria um Objeto do tipo ``MyApp`` -- nossa ``Application``. A segunda linha especifica o `socket`, o endereo de conexo, a quantidade de dados a ser enviada em cada evento, a quantidade de eventos de transmisso a ser gerados e a taxa de produo de dados para estes eventos.

	Next, we manually add the ``MyApp Application`` to the source node
	and explicitly call the ``Start`` and ``Stop`` methods on the 
	``Application`` to tell it when to start and stop doing its thing.

Depois, adicionamos a ``MyApp Application`` para o n origem e chamamos os mtodos ``Start`` e ``Stop`` para dizer quando e iniciar e parar a simulao.

..
	We need to actually do the connect from the receiver point-to-point ``NetDevice``
	to our callback now.

Precisamos agora fazer a conexo entre o receptor com nossa *callback*.

::

  devices.Get (1)->TraceConnectWithoutContext("PhyRxDrop", MakeCallback (&RxDrop));

..
	It should now be obvious that we are getting a reference to the receiving 
	``Node NetDevice`` from its container and connecting the trace source defined
	by the attribute "PhyRxDrop" on that device to the trace sink ``RxDrop``.

Estamos obtendo uma referncia para o ``Node NetDevice`` receptor e conectando a origem do rastreamento pelo Atributo "PhyRxDrop" do dispositivo no destino do rastreamento ``RxDrop``.

..
	Finally, we tell the simulator to override any ``Applications`` and just
	stop processing events at 20 seconds into the simulation.

Finalmente, dizemos ao simulador para sobrescrever qualquer ``Applications`` e parar o processamento de eventos em 20 segundos na simulao.

::

    Simulator::Stop (Seconds(20));
    Simulator::Run ();
    Simulator::Destroy ();

    return 0;
  }

..
	Recall that as soon as ``Simulator::Run`` is called, configuration time
	ends, and simulation time begins.  All of the work we orchestrated by 
	creating the ``Application`` and teaching it how to connect and send
	data actually happens during this function call.

Lembre-se que quando ``Simulator::Run``  chamado, a fase de configurao termina e a fase de simulao inicia. Todo o processo descrito anteriormente ocorre durante a chamada dessa funo.

..
	As soon as ``Simulator::Run`` returns, the simulation is complete and
	we enter the teardown phase.  In this case, ``Simulator::Destroy`` takes
	care of the gory details and we just return a success code after it completes.

Aps o retorno do ``Simulator::Run``, a simulao  terminada e entramos na fase de finalizao. Neste caso, ``Simulator::Destroy`` executa a tarefa pesada e ns apenas retornamos o cdigo de sucesso.

.. 
	Running fifth.cc

Executando fifth.cc
+++++++++++++++++++

..
	Since we have provided the file ``fifth.cc`` for you, if you have built
	your distribution (in debug mode since it uses NS_LOG -- recall that optimized
	builds optimize out NS_LOGs) it will be waiting for you to run.

O arquivo ``fifth.cc``  distribudo no cdigo fonte, no diretrio ``examples/tutorial``. Para executar:

::

  ./waf --run fifth
  Waf: Entering directory `/home/craigdo/repos/ns-3-allinone-dev/ns-3-dev/build
  Waf: Leaving directory `/home/craigdo/repos/ns-3-allinone-dev/ns-3-dev/build'
  'build' finished successfully (0.684s)
  1.20919 1072
  1.21511 1608
  1.22103 2144
  ...
  1.2471  8040
  1.24895 8576
  1.2508  9112
  RxDrop at 1.25151
  ...

..
	You can probably see immediately a downside of using prints of any kind in your
	traces.  We get those extraneous waf messages printed all over our interesting
	information along with those RxDrop messages.  We will remedy that soon, but I'm
	sure you can't wait to see the results of all of this work.  Let's redirect that
	output to a file called ``cwnd.dat``:

Podemos observar o lado negativo de usar "prints" de qualquer tipo no rastreamento. Temos mensagens ``waf`` sendo impressas sobre a informao relevante. Vamos resolver esse problema, mas primeiro vamos verificar o resultado redirecionando a sada para um arquivo ``cwnd.dat``:

::

  ./waf --run fifth > cwnd.dat 2>&1

..
	Now edit up "cwnd.dat" in your favorite editor and remove the waf build status
	and drop lines, leaving only the traced data (you could also comment out the
	``TraceConnectWithoutContext("PhyRxDrop", MakeCallback (&RxDrop));`` in the
	script to get rid of the drop prints just as easily. 

Removemos as mensagens do ``waf`` e deixamos somente os dados rastreados.  Pode-se tambm comentar as mensagens de "RxDrop...".

..
	You can now run gnuplot (if you have it installed) and tell it to generate some 
	pretty pictures:

Agora podemos executar o gnuplot (se instalado) e gerar um grfico:

::

  gnuplot> set terminal png size 640,480
  gnuplot> set output "cwnd.png"
  gnuplot> plot "cwnd.dat" using 1:2 title 'Congestion Window' with linespoints
  gnuplot> exit

..
	You should now have a graph of the congestion window versus time sitting in the 
	file "cwnd.png" that looks like:

Devemos obter um grfico da janela de congestionamento pelo tempo no arquivo "cwnd.png", similar ao grfico 7.1:

figure:: figures/cwnd.png

   Grfico da janela de congestionamento versus tempo.

.. 
	Using Mid-Level Helpers

Usando Auxiliares Intermedirios
++++++++++++++++++++++++++++++++

..
	In the previous section, we showed how to hook a trace source and get hopefully
	interesting information out of a simulation.  Perhaps you will recall that we 
	called logging to the standard output using ``std::cout`` a "Blunt Instrument" 
	much earlier in this chapter.  We also wrote about how it was a problem having
	to parse the log output in order to isolate interesting information.  It may 
	have occurred to you that we just spent a lot of time implementing an example
	that exhibits all of the problems we purport to fix with the |ns3| tracing
	system!  You would be correct.  But, bear with us.  We're not done yet.

Na seo anterior, mostramos como adicionar uma origem do rastreamento e obter informaes de interesse fora da simulao. Entretanto, no incio do captulo foi comentado que imprimir informaes na sada padro no  uma boa prtica. Alm disso, comentamos que no  interessante realizar processamento sobre a sada para isolar a informao de interesse. Podemos pensar que perdemos muito tempo em um exemplo que apresenta todos os problemas que propomos resolver usando o sistema de rastreamento do |ns3|. Voc estaria correto, mas ns ainda no terminamos.

..
	One of the most important things we want to do is to is to have the ability to 
	easily control the amount of output coming out of the simulation; and we also 
	want to save those data to a file so we can refer back to it later.  We can use
	the mid-level trace helpers provided in |ns3| to do just that and complete
	the picture.

Uma da coisas mais importantes que queremos fazer  controlar a quantidade de sada da simulao. Ns podemos usar assistentes de rastreamento intermedirios fornecido pelo |ns3| para alcanar com sucesso esse objetivo.

..
	We provide a script that writes the cwnd change and drop events developed in 
	the example ``fifth.cc`` to disk in separate files.  The cwnd changes are 
	stored as a tab-separated ASCII file and the drop events are stored in a pcap
	file.  The changes to make this happen are quite small.

Fornecemos um cdigo que separa em arquivos distintos no disco os eventos de modificao da janela e os eventos de remoo. As alteraes em cwnd so armazenadas em um arquivo ASCII separadas por TAB e os eventos de remoo so armazenados em um arquivo *pcap*. As alteraes para obter esse resultado so pequenas.

.. 
	A sixth.cc Walkthrough

Analisando sixth.cc
~~~~~~~~~~~~~~~~~~~

..
	Let's take a look at the changes required to go from ``fifth.cc`` to 
	``sixth.cc``.  Open ``examples/tutorial/fifth.cc`` in your favorite 
	editor.  You can see the first change by searching for CwndChange.  You will 
	find that we have changed the signatures for the trace sinks and have added 
	a single line to each sink that writes the traced information to a stream
	representing a file.

Vamos verificar as mudanas do arquivo ``fifth.cc`` para o  ``sixth.cc``. Verificamos a primeira mudana em ``CwndChange``. Notamos que as assinaturas para o destino do rastreamento foram alteradas e que foi adicionada uma linha para cada um que escreve a informao rastreada para um fluxo (*stream*) representando um arquivo

::

  static void
  CwndChange (Ptr<OutputStreamWrapper> stream, uint32_t oldCwnd, uint32_t newCwnd)
  {
    NS_LOG_UNCOND (Simulator::Now ().GetSeconds () << "\t" << newCwnd);
    *stream->GetStream () << Simulator::Now ().GetSeconds () << "\t" 
    		<< oldCwnd << "\t" << newCwnd << std::endl;
  }
  
  static void
  RxDrop (Ptr<PcapFileWrapper> file, Ptr<const Packet> p)
  {
    NS_LOG_UNCOND ("RxDrop at " << Simulator::Now ().GetSeconds ());
    file->Write(Simulator::Now(), p);
  }

..
	We have added a "stream" parameter to the ``CwndChange`` trace sink.  
	This is an object that holds (keeps safely alive) a C++ output stream.  It 
	turns out that this is a very simple object, but one that manages lifetime 
	issues for the stream and solves a problem that even experienced C++ users 
	run into.  It turns out that the copy constructor for ostream is marked 
	private.  This means that ostreams do not obey value semantics and cannot 
	be used in any mechanism that requires the stream to be copied.  This includes
	the |ns3| callback system, which as you may recall, requires objects
	that obey value semantics.  Further notice that we have added the following 
	line in the ``CwndChange`` trace sink implementation:

Um parmetro "stream" foi adicionado para o destino do rastreamento ``CwndChange``. Este  um objeto que armazena (mantm seguramente vivo) um fluxo de sada em C++. Isto resulta em um objeto muito simples, mas que gerncia problemas no ciclo de vida para fluxos e resolve um problema que mesmo programadores experientes de C++ tem dificuldades. Resulta que o construtor de cpia para o fluxo de sada (*ostream*)  marcado como privado. Isto significa que fluxos de sada no seguem a semntica de passagem por valor e no podem ser usados em mecanismos que necessitam que o fluxo seja copiado. Isto inclui o sistema de *callback* do |ns3|. Alm disso, adicionamos a seguinte linha:

::

  *stream->GetStream () << Simulator::Now ().GetSeconds () << "\t" << oldCwnd 
  		<< "\t" << newCwnd << std::endl;

..
	This would be very familiar code if you replaced ``*stream->GetStream ()``
	with ``std::cout``, as in:

que substitui ``std::cout`` por ``*stream->GetStream ()``

::

  std::cout << Simulator::Now ().GetSeconds () << "\t" << oldCwnd << "\t" << 
  		newCwnd << std::endl;

..
	This illustrates that the ``Ptr<OutputStreamWrapper>`` is really just
	carrying around a ``std::ofstream`` for you, and you can use it here like 
	any other output stream.

Isto demostra que o ``Ptr<OutputStreamWrapper>`` est apenas encapsulando um ``std::ofstream``, logo pode ser usado como qualquer outro fluxo de sada.

..
	A similar situation happens in ``RxDrop`` except that the object being 
	passed around (a ``Ptr<PcapFileWrapper>``) represents a pcap file.  There
	is a one-liner in the trace sink to write a timestamp and the contents of the 
	packet being dropped to the pcap file:

Uma situao similar ocorre em ``RxDrop``, exceto que o objeto passado (``Ptr<PcapFileWrapper>``) representa um arquivo pcap. H uma linha no *trace sink* para escrever um marcador de tempo (*timestamp*) eo contedo do pacote perdido para o arquivo pcap.

::

  file->Write(Simulator::Now(), p);

..
	Of course, if we have objects representing the two files, we need to create
	them somewhere and also cause them to be passed to the trace sinks.  If you 
	look in the ``main`` function, you will find new code to do just that:

 claro, se ns temos objetos representando os dois arquivos, precisamos cri-los em algum lugar e tambm pass-los aos *trace sinks*. Se observarmos a funo ``main``, temos o cdigo:

::

  AsciiTraceHelper asciiTraceHelper;
  Ptr<OutputStreamWrapper> stream = asciiTraceHelper.CreateFileStream ("sixth.cwnd");
  ns3TcpSocket->TraceConnectWithoutContext ("CongestionWindow", 
  		MakeBoundCallback (&CwndChange, stream));

  ...

  PcapHelper pcapHelper;
  Ptr<PcapFileWrapper> file = pcapHelper.CreateFile ("sixth.pcap", 
  		std::ios::out, PcapHelper::DLT_PPP);
  devices.Get (1)->TraceConnectWithoutContext("PhyRxDrop", 
  		MakeBoundCallback (&RxDrop, file));

..
	In the first section of the code snippet above, we are creating the ASCII
	trace file, creating an object responsible for managing it and using a
	variant of the callback creation function to arrange for the object to be 
	passed to the sink.  Our ASCII trace helpers provide a rich set of
	functions to make using text (ASCII) files easy.  We are just going to 
	illustrate the use of the file stream creation function here.

Na primeira seo do cdigo, criamos o arquivo de rastreamento ASCII e o objeto responsvel para gerenci-lo. Em seguida, usando uma das formas da funo para criao da *callback* permitimos o objeto ser passado para o destino do rastreamento. As classes assistentes para rastreamento ASCII fornecem um vasto conjunto de funes para facilitar a manipulao de arquivos texto. Neste exemplo, focamos apenas na criao do arquivo para o fluxo de sada.

..
	The ``CreateFileStream{}`` function is basically going to instantiate
	a std::ofstream object and create a new file (or truncate an existing file).
	This ofstream is packaged up in an |ns3| object for lifetime management
	and copy constructor issue resolution.

A funo ``CreateFileStream()`` instancia um objeto ``std::ofstream`` e cria  um novo arquivo. O fluxo de sada ``ofstream``  encapsulado em um objeto do |ns3| para gerenciamento do ciclo de vida e para resolver o
problema do construtor de cpia.

..
	We then take this |ns3| object representing the file and pass it to
	``MakeBoundCallback()``.  This function creates a callback just like
	``MakeCallback()``, but it "binds" a new value to the callback.  This
	value is added to the callback before it is called.

Ento pegamos o objeto que representa o arquivo e passamos para ``MakeBoundCallback()``. Esta funo cria um *callback* como ``MakeCallback()``, mas "associa" um novo valor para o *callback*. Este valor  adicionado ao *callback* antes de sua invocao.

..
	Essentially, ``MakeBoundCallback(&CwndChange, stream)`` causes the trace 
	source to add the additional "stream" parameter to the front of the formal
	parameter list before invoking the callback.  This changes the required 
	signature of the ``CwndChange`` sink to match the one shown above, which
	includes the "extra" parameter ``Ptr<OutputStreamWrapper> stream``.

Essencialmente, ``MakeBoundCallback(&CwndChange, stream)`` faz com que a origem do rastreamento adicione um parmetro extra "fluxo" aps a lista formal de parmetros antes de invocar o *callback*. Esta mudana est de acordo com o apresentado anteriormente, a qual inclui o parmetro ``Ptr<OutputStreamWrapper> stream``.

..
	In the second section of code in the snippet above, we instantiate a 
	``PcapHelper`` to do the same thing for our pcap trace file that we did
	with the ``AsciiTraceHelper``. The line of code,

Na segunda seo de cdigo, instanciamos um ``PcapHelper`` para fazer a mesma coisa para o arquivo de rastreamento pcap. A linha de cdigo,

::

  Ptr<PcapFileWrapper> file = pcapHelper.CreateFile ("sixth.pcap", "w", 
  		PcapHelper::DLT_PPP);

..
	creates a pcap file named "sixth.pcap" with file mode "w".   This means that
	the new file is to truncated if an existing file with that name is found.  The
	final parameter is the "data link type" of the new pcap file.  These are 
	the same as the pcap library data link types defined in ``bpf.h`` if you are
	familar with pcap.  In this case, ``DLT_PPP`` indicates that the pcap file
	is going to contain packets prefixed with point to point headers.  This is true
	since the packets are coming from our point-to-point device driver.  Other
	common data link types are DLT_EN10MB (10 MB Ethernet) appropriate for csma
	devices and DLT_IEEE802_11 (IEEE 802.11) appropriate for wifi devices.  These
	are defined in ``src/network/helper/trace-helper.h"`` if you are interested in seeing
	the list.  The entries in the list match those in ``bpf.h`` but we duplicate
	them to avoid a pcap source dependence.

cria um arquivo pcap chamado "sixth.pcap" no modo "w" (escrita). O parmetro final  o "tipo da ligao de dados" do arquivo pcap. As opes esto definidas em ``bpf.h``. Neste caso, ``DLT_PPP`` indica que o arquivo pcap dever conter pacotes prefixado com cabealhos ponto-a-ponto. Isto  verdade pois os pacotes esto chegando de nosso `driver` de dispositivo ponto-a-ponto. Outros tipos de ligao de dados comuns so DLT_EN10MB (10 MB Ethernet) apropriado para dispositivos CSMA e DLT_IEEE802_11 (IEEE 802.11) apropriado para dispositivos sem fio. O arquivo ``src/network/helper/trace-helper.h"`` define uma lista com os tipos. As entradas na lista so idnticas as definidas em ``bpf.h``, pois foram duplicadas para evitar um dependncia com o pcap.

..
	A |ns3| object representing the pcap file is returned from ``CreateFile``
	and used in a bound callback exactly as it was in the ascii case.

Um objeto |ns3| representando o arquivo pcap  retornado de ``CreateFile`` e usado em uma *callback* exatamente como no caso ASCII.

..
	An important detour:  It is important to notice that even though both of these 
	objects are declared in very similar ways,

 importante observar que ambos objetos so declarados de maneiras muito similares,

::

  Ptr<PcapFileWrapper> file ...
  Ptr<OutputStreamWrapper> stream ...

..
	The underlying objects are entirely different.  For example, the 
	Ptr<PcapFileWrapper> is a smart pointer to an |ns3| Object that is a 
	fairly heaviweight thing that supports ``Attributes`` and is integrated into
	the config system.  The Ptr<OutputStreamWrapper>, on the other hand, is a smart 
	pointer to a reference counted object that is a very lightweight thing.
	Remember to always look at the object you are referencing before making any
	assumptions about the "powers" that object may have.  

Mas os objetos internos so inteiramente diferentes. Por exemplo, o Ptr<PcapFileWrapper>  um ponteiro para um objeto |ns3| que suporta ``Attributes`` e  integrado dentro do sistema de configurao. O Ptr<OutputStreamWrapper>, por outro lado,  um ponteiro para uma referncia para um simples objeto contado. Lembre-se sempre de analisar o objeto que voc est referenciando antes de fazer suposies sobre os "poderes" que o objeto pode ter.

..
	For example, take a look at ``src/network/utils/pcap-file-wrapper.h`` in the 
	distribution and notice, 

Por exemplo, acesse o arquivo ``src/network/utils/pcap-file-wrapper.h`` e observe,

::

  class PcapFileWrapper : public Object

..
	that class ``PcapFileWrapper`` is an |ns3| Object by virtue of 
	its inheritance.  Then look at ``src/network/model/output-stream-wrapper.h`` and 
	notice,

que a classe ``PcapFileWrapper``  um ``Object`` |ns3| por herana. J no arquivo ``src/network/model/output-stream-wrapper.h``, observe,

::

  class OutputStreamWrapper : public SimpleRefCount<OutputStreamWrapper>

..
	that this object is not an |ns3| Object at all, it is "merely" a
	C++ object that happens to support intrusive reference counting.

que no  um ``Object`` |ns3|, mas um objeto C++ que suporta contagem de referncia.

..
	The point here is that just because you read Ptr<something> it does not necessarily
	mean that "something" is an |ns3| Object on which you can hang |ns3|
	``Attributes``, for example.

A questo  que se voc tem um Ptr<alguma_coisa>, no necessariamente significa que "alguma_coisa"  um ``Object`` |ns3|, no qual voc pode modificar ``Attributes``, por exemplo.

..
	Now, back to the example.  If you now build and run this example,

Voltando ao exemplo. Se compilarmos e executarmos o exemplo,

::

  ./waf --run sixth

..
	you will see the same messages appear as when you ran "fifth", but two new 
	files will appear in the top-level directory of your |ns3| distribution.

Veremos as mesmas mensagens do "fifth", mas dois novos arquivos aparecero no diretrio base de sua distribuio do |ns3|.

::

  sixth.cwnd  sixth.pcap

..
	Since "sixth.cwnd" is an ASCII text file, you can view it with ``cat``
	or your favorite file viewer.

Como "sixth.cwnd"  um arquivo texto ASCII, voc pode visualizar usando *cat* ou um editor de texto.

::

  1.20919 536     1072
  1.21511 1072    1608
  ...
  9.30922 8893    8925
  9.31754 8925    8957

..
	You have a tab separated file with a timestamp, an old congestion window and a
	new congestion window suitable for directly importing into your plot program.
	There are no extraneous prints in the file, no parsing or editing is required.
	
Cada linha tem um marcador de tempo, o valor da janela de congestionamento e o valor da nova janela de congestionamento separados por tabulao, para importar diretamente para seu programa de plotagem de grficos.
No h nenhuma outra informao alm da rastreada, logo no  necessrio processamento ou edio do arquivo.

..
	Since "sixth.pcap" is a pcap file, you can view it with ``tcpdump``.

Como "sixth.pcap"  um arquivo pcap, voc pode visualizar usando o ``tcpdump`` ou ``wireshark``.

::

  reading from file ../../sixth.pcap, link-type PPP (PPP)
  1.251507 IP 10.1.1.1.49153 > 10.1.1.2.8080: . 17689:18225(536) ack 1 win 65535
  1.411478 IP 10.1.1.1.49153 > 10.1.1.2.8080: . 33808:34312(504) ack 1 win 65535
  ...
  7.393557 IP 10.1.1.1.49153 > 10.1.1.2.8080: . 781568:782072(504) ack 1 win 65535
  8.141483 IP 10.1.1.1.49153 > 10.1.1.2.8080: . 874632:875168(536) ack 1 win 65535

..
	You have a pcap file with the packets that were dropped in the simulation.  There
	are no other packets present in the file and there is nothing else present to
	make life difficult.

Voc tem um arquivo pcap com os pacotes que foram descartados na simulao. No h nenhum outro pacote presente no arquivo e nada mais para dificultar sua anlise.

..
	It's been a long journey, but we are now at a point where we can appreciate the
	|ns3| tracing system.  We have pulled important events out of the middle
	of a TCP implementation and a device driver.  We stored those events directly in
	files usable with commonly known tools.  We did this without modifying any of the
	core code involved, and we did this in only 18 lines of code:

Foi uma longa jornada, mas agora entendemos porque o sistema de rastreamento  interessante. Ns obtemos e armazenamos importantes eventos da implementao do TCP e do `driver` de dispositivo. E no modificamos nenhuma linha do cdigo do ncleo do |ns3|, e ainda fizemos isso com apenas 18 linhas de cdigo:

::

  static void
  CwndChange (Ptr<OutputStreamWrapper> stream, uint32_t oldCwnd, uint32_t newCwnd)
  {
    NS_LOG_UNCOND (Simulator::Now ().GetSeconds () << "\t" << newCwnd);
    *stream->GetStream () << Simulator::Now ().GetSeconds () << "\t" << 
    		oldCwnd << "\t" << newCwnd << std::endl;
  }

  ...

  AsciiTraceHelper asciiTraceHelper;
  Ptr<OutputStreamWrapper> stream = asciiTraceHelper.CreateFileStream ("sixth.cwnd");
  ns3TcpSocket->TraceConnectWithoutContext ("CongestionWindow", 
  		MakeBoundCallback (&CwndChange, stream));

  ...

  static void
  RxDrop (Ptr<PcapFileWrapper> file, Ptr<const Packet> p)
  {
    NS_LOG_UNCOND ("RxDrop at " << Simulator::Now ().GetSeconds ());
    file->Write(Simulator::Now(), p);
  }

  ...
  
  PcapHelper pcapHelper;
  Ptr<PcapFileWrapper> file = pcapHelper.CreateFile ("sixth.pcap", "w", 
  		PcapHelper::DLT_PPP);
  devices.Get (1)->TraceConnectWithoutContext("PhyRxDrop", 
  		MakeBoundCallback (&RxDrop, file));

.. 
	Using Trace Helpers

Usando Classes Assistentes para Rastreamento
********************************************

..
	The |ns3| trace helpers provide a rich environment for configuring and
	selecting different trace events and writing them to files.  In previous
	sections, primarily "Building Topologies," we have seen several varieties
	of the trace helper methods designed for use inside other (device) helpers.

As classes assistentes (*trace helpers*) de rastreamento do |ns3| proveem um ambiente rico para configurar, selecionar e escrever diferentes eventos de rastreamento para arquivos. Nas sees anteriores, primeiramente em "Construindo Topologias", ns vimos diversas formas de mtodos assistentes para rastreamento projetados para uso dentro de outras classes assistentes.

..
	Perhaps you will recall seeing some of these variations: 

Segue alguns desses mtodos j estudados:

::

  pointToPoint.EnablePcapAll ("second");
  pointToPoint.EnablePcap ("second", p2pNodes.Get (0)->GetId (), 0);
  csma.EnablePcap ("third", csmaDevices.Get (0), true);
  pointToPoint.EnableAsciiAll (ascii.CreateFileStream ("myfirst.tr"));

..
	What may not be obvious, though, is that there is a consistent model for all of 
	the trace-related methods found in the system.  We will now take a little time
	and take a look at the "big picture".


O que no parece claro  que h um modelo consistente para todos os mtodos relacionados  rastreamento encontrados no sistema. Apresentaremos uma viso geral desse modelo.

..
	There are currently two primary use cases of the tracing helpers in |ns3|:
	Device helpers and protocol helpers.  Device helpers look at the problem
	of specifying which traces should be enabled through a node, device pair.  For 
	example, you may want to specify that pcap tracing should be enabled on a 
	particular device on a specific node.  This follows from the |ns3| device
	conceptual model, and also the conceptual models of the various device helpers.
	Following naturally from this, the files created follow a 
	<prefix>-<node>-<device> naming convention.  

H dois casos de uso primrios de classes assistentes em |ns3|: Classes assistentes de dispositivo e classes assistentes de protocolo. Classes assistentes de dispositivo tratam o problema de especificar quais rastreamentos deveriam ser habilitados no domnio do n de rede. Por exemplo, poderamos querer especificar que o rastreamento pcap deveria ser ativado em um dispositivo particular de um n especfico. Isto  o que define o modelo conceitual de dispositivo no |ns3| e tambm os modelos conceituais de vrias classes assistentes de dispositivos. Baseado nisso, os arquivos criados seguem a conveno de nome `<prefixo>-<n>-<dispositivo>`.

..
	Protocol helpers look at the problem of specifying which traces should be
	enabled through a protocol and interface pair.  This follows from the |ns3|
	protocol stack conceptual model, and also the conceptual models of internet
	stack helpers.  Naturally, the trace files should follow a 
	<prefix>-<protocol>-<interface> naming convention.

As classes assistentes de protocolos tratam o problema de especificar quais rastreamentos deveriam ser ativados no protocolo e interface. Isto  definido pelo modelo conceitual de pilha de protocolo do |ns3| e tambm pelos modelos conceituais de classes assistentes de pilha de rede. Baseado nisso, os arquivos criados seguem a conveno de nome `<prefixo>-<protocolo>-<interface>`.

..
	The trace helpers therefore fall naturally into a two-dimensional taxonomy.
	There are subtleties that prevent all four classes from behaving identically,
	but we do strive to make them all work as similarly as possible; and whenever
	possible there are analogs for all methods in all classes.

As classes assistentes consequentemente encaixam-se em uma taxinomia bi-dimensional. H pequenos detalhes que evitam todas as classes comportarem-se da mesma forma, mas fizemos parecer que trabalham to similarmente quanto possvel e quase sempre h similares para todos mtodos em todas as classes.

::

                                                     | pcap | ascii |
  ---------------------------------------------------+------+-------|
  Classe Assistente de Dispositivo (*Device Helper*)   |      |       |
  ---------------------------------------------------+------+-------|
  Classe Assistente de Protocolo (*Protocol Helper*)   |      |       |
  ---------------------------------------------------+------+-------|

..
	We use an approach called a ``mixin`` to add tracing functionality to our 
	helper classes.  A ``mixin`` is a class that provides functionality to that
	is inherited by a subclass.  Inheriting from a mixin is not considered a form 
	of specialization but is really a way to collect functionality. 

Usamos uma abordagem chamada ``mixin`` para adicionar funcionalidade de rastreamento para nossas classes assistentes. Uma ``mixin``  uma classe que prov funcionalidade para aquela que  herdada por uma subclasse. Herdar de um ``mixin`` no  considerado uma forma de especializao mas  realmente uma maneira de colecionar funcionalidade.

..
	Let's take a quick look at all four of these cases and their respective 
	``mixins``.

Vamos verificar rapidamente os quatro casos e seus respectivos ``mixins``.

.. 
	Pcap Tracing Device Helpers

Classes Assistentes de Dispositivo para Rastreamento Pcap
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

..
	The goal of these helpers is to make it easy to add a consistent pcap trace
	facility to an |ns3| device.  We want all of the various flavors of
	pcap tracing to work the same across all devices, so the methods of these 
	helpers are inherited by device helpers.  Take a look at 
	``src/network/helper/trace-helper.h`` if you want to follow the discussion while 
	looking at real code.

O objetivo destes assistentes  simplificar a adio de um utilitrio de rastreamento pcap consistente para um dispositivo |ns3|. Queremos que opere da mesma forma entre todos os dispositivos, logo os mtodos destes assistentes so herdados por classes assistentes de dispositivo. Observe o arquivo ``src/network/helper/trace-helper.h`` para entender a discusso do cdigo a seguir.

..
	The class ``PcapHelperForDevice`` is a ``mixin`` provides the high level 
	functionality for using pcap tracing in an |ns3| device.  Every device 
	must implement a single virtual method inherited from this class.

A classe ``PcapHelperForDevice``  um ``mixin`` que prov a funcionalidade de alto nvel para usar rastreamento pcap em um dispositivo |ns3|. Todo dispositivo deve implementar um nico mtodo virtual herdado dessa classe.

::

  virtual void EnablePcapInternal (std::string prefix, Ptr<NetDevice> nd, 
  		bool promiscuous, bool explicitFilename) = 0;

..
	The signature of this method reflects the device-centric view of the situation
	at this level.  All of the public methods inherited from class 
	``PcapUserHelperForDevice`` reduce to calling this single device-dependent
	implementation method.  For example, the lowest level pcap method,

A assinatura deste mtodo reflete a viso do dispositivo da situao neste nvel. Todos os mtodos pblicos herdados da classe ``PcapUserHelperForDevice`` so reduzidos a chamada da implementao deste simples mtodo dependente de dispositivo. Por exemplo, o nvel mais baixo do mtodo pcap,

::

  void EnablePcap (std::string prefix, Ptr<NetDevice> nd, bool promiscuous = false, 
  		bool explicitFilename = false);

..
	will call the device implementation of ``EnablePcapInternal`` directly.  All
	other public pcap tracing methods build on this implementation to provide 
	additional user-level functionality.  What this means to the user is that all 
	device helpers in the system will have all of the pcap trace methods available;
	and these methods will all work in the same way across devices if the device 
	implements ``EnablePcapInternal`` correctly.

chamaremos diretamente a implementao do dispositivo de ``EnablePcapInternal``. Todos os outros mtodos de rastreamento pcap pblicos desta implementao so para prover funcionalidade adicional em nvel de usurio. Para o usurio, isto significa que todas as classes assistentes de dispositivo no sistema tero todos os mtodos de rastreamento pcap disponveis; e estes mtodos trabalharo da mesma forma entre dispositivos se o dispositivo implementar corretamente ``EnablePcapInternal``.

.. 
	Pcap Tracing Device Helper Methods

Mtodos da Classe Assistente de Dispositivo para Rastreamento Pcap
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

::

  void EnablePcap (std::string prefix, Ptr<NetDevice> nd, 
  		bool promiscuous = false, bool explicitFilename = false);
  void EnablePcap (std::string prefix, std::string ndName, 
  		bool promiscuous = false, bool explicitFilename = false);
  void EnablePcap (std::string prefix, NetDeviceContainer d, 
  		bool promiscuous = false);
  void EnablePcap (std::string prefix, NodeContainer n, 
  		bool promiscuous = false);
  void EnablePcap (std::string prefix, uint32_t nodeid, uint32_t deviceid, 
  		bool promiscuous = false);
  void EnablePcapAll (std::string prefix, bool promiscuous = false);

..
	In each of the methods shown above, there is a default parameter called 
	``promiscuous`` that defaults to false.  This parameter indicates that the
	trace should not be gathered in promiscuous mode.  If you do want your traces
	to include all traffic seen by the device (and if the device supports a 
	promiscuous mode) simply add a true parameter to any of the calls above.  For example,

Em cada mtodo apresentado existe um parmetro padro chamado ``promiscuous`` que  definido para o valor "false". Este parmetro indica que o rastreamento no deveria coletar dados em modo promscuo. Se quisermos incluir todo trfego visto pelo dispositivo devemos modificar o valor para "true". Por exemplo,

::

  Ptr<NetDevice> nd;
  ...
  helper.EnablePcap ("prefix", nd, true);

..
	will enable promiscuous mode captures on the ``NetDevice`` specified by ``nd``.

ativar o modo de captura promscuo no ``NetDevice`` especificado por ``nd``.

..
	The first two methods also include a default parameter called ``explicitFilename``
	that will be discussed below.

Os  dois primeiros mtodos tambm incluem um parmetro padro chamado ``explicitFilename`` que ser abordado a seguir.

..
	You are encouraged to peruse the Doxygen for class ``PcapHelperForDevice``
	to find the details of these methods; but to summarize ...

 interessante procurar maiores detalhes dos mtodos da classe ``PcapHelperForDevice`` no Doxygen; mas para resumir ...

..
	You can enable pcap tracing on a particular node/net-device pair by providing a
	``Ptr<NetDevice>`` to an ``EnablePcap`` method.  The ``Ptr<Node>`` is 
	implicit since the net device must belong to exactly one ``Node``.
	For example, 

Podemos ativar o rastreamento pcap em um par n/dispositivo-rede especfico provendo um ``Ptr<NetDevice>`` para um mtodo ``EnablePcap``. O ``Ptr<Node>``  implcito, pois o dispositivo de rede deve estar em um ``Node``. Por exemplo,

::

  Ptr<NetDevice> nd;
  ...
  helper.EnablePcap ("prefix", nd);

..
	You can enable pcap tracing on a particular node/net-device pair by providing a
	``std::string`` representing an object name service string to an 
	``EnablePcap`` method.  The ``Ptr<NetDevice>`` is looked up from the name
	string.  Again, the ``<Node>`` is implicit since the named net device must 
	belong to exactly one ``Node``.  For example, 

Podemos ativar o rastreamento pcap em um par n/dispositivo-rede passando uma ``std::string`` que representa um nome de servio para um mtodo ``EnablePcap``. O ``Ptr<NetDevice>``  buscado a partir do nome da `string`.
Novamente, o ``Ptr<Node>``  implcito pois o dispositivo de rede deve estar em um ``Node``. 

::

  Names::Add ("server" ...);
  Names::Add ("server/eth0" ...);
  ...
  helper.EnablePcap ("prefix", "server/eth0");

..
	You can enable pcap tracing on a collection of node/net-device pairs by 
	providing a ``NetDeviceContainer``.  For each ``NetDevice`` in the container
	the type is checked.  For each device of the proper type (the same type as is 
	managed by the device helper), tracing is enabled.    Again, the ``<Node>`` is 
	implicit since the found net device must belong to exactly one ``Node``.
	For example, 

Podemos ativar o rastreamento pcap em uma coleo de pares ns/dispositivos usando um ``NetDeviceContainer``. Para cada ``NetDevice`` no continer o tipo  verificado. Para cada dispositivo com o tipo adequado, o rastreamento ser ativado. Por exemplo,

::

  NetDeviceContainer d = ...;
  ...
  helper.EnablePcap ("prefix", d);

..
	You can enable pcap tracing on a collection of node/net-device pairs by 
	providing a ``NodeContainer``.  For each ``Node`` in the ``NodeContainer``
	its attached ``NetDevices`` are iterated.  For each ``NetDevice`` attached
	to each node in the container, the type of that device is checked.  For each 
	device of the proper type (the same type as is managed by the device helper), 
	tracing is enabled.

Podemos ativar o rastreamento em uma coleo de pares n/dispositivo-rede usando um ``NodeContainer``. Para cada ``Node`` no ``NodeContainer`` seus ``NetDevices`` so percorridos e verificados segundo o tipo. Para cada dispositivo com o tipo adequado, o rastreamento  ativado.

::

  NodeContainer n;
  ...
  helper.EnablePcap ("prefix", n);

..
	You can enable pcap tracing on the basis of node ID and device ID as well as
	with explicit ``Ptr``.  Each ``Node`` in the system has an integer node ID
	and each device connected to a node has an integer device ID.

Podemos ativar o rastreamento pcap usando o nmero identificador (`ID`) do n e do dispositivo. Todo ``Node`` no sistema tem um valor inteiro indicando o `ID` do n e todo dispositivo conectado ao n tem um valor inteiro indicando o `ID` do dispositivo.

::

  helper.EnablePcap ("prefix", 21, 1);

..
	Finally, you can enable pcap tracing for all devices in the system, with the
	same type as that managed by the device helper.

Por fim, podemos ativar rastreamento pcap para todos os dispositivos no sistema, desde que o tipo seja o mesmo gerenciado pela classe assistentes de dispositivo.

::

  helper.EnablePcapAll ("prefix");

.. 
	Pcap Tracing Device Helper Filename Selection

Seleo de um Nome de Arquivo para o Rastreamento Pcap da Classe Assistente de Dispositivo
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

..
	Implicit in the method descriptions above is the construction of a complete 
	filename by the implementation method.  By convention, pcap traces in the 
	|ns3| system are of the form "<prefix>-<node id>-<device id>.pcap"

Implcito nas descries de mtodos anteriores  a construo do nome de arquivo por meio do mtodo da implementao. Por conveno, rastreamento pcap no |ns3| usa a forma "<prefixo>-<id do n>-<id do dispositivo>.pcap"

..
	As previously mentioned, every node in the system will have a system-assigned
	node id; and every device will have an interface index (also called a device id)
	relative to its node.  By default, then, a pcap trace file created as a result
	of enabling tracing on the first device of node 21 using the prefix "prefix"
	would be "prefix-21-1.pcap".
	
Como mencionado, todo n no sistema ter um `id` de n associado; e todo dispositivo ter um ndice de interface (tambm chamado de id do dispositivo) relativo ao seu n. Por padro, ento, um arquivo pcap criado como um resultado de ativar rastreamento no primeiro dispositivo do n 21 usando o prefixo "prefix" seria "prefix-21-1.pcap".

..
	You can always use the |ns3| object name service to make this more clear.
	For example, if you use the object name service to assign the name "server"
	to node 21, the resulting pcap trace file name will automatically become,
	"prefix-server-1.pcap" and if you also assign the name "eth0" to the 
	device, your pcap file name will automatically pick this up and be called
	"prefix-server-eth0.pcap".

Sempre podemos usar o servio de nome de objeto do |ns3| para tornar isso mais claro. Por exemplo, se voc usa o servio para associar o nome "server" ao n 21, o arquivo pcap resultante automaticamente ser, "prefix-server-1.pcap" e se voc tambm associar o nome "eth0" ao dispositivo, seu nome do arquivo pcap automaticamente ser denominado "prefix-server-eth0.pcap".

.. 
	Finally, two of the methods shown above,

Finalmente, dois dos mtodos mostrados, 

::

  void EnablePcap (std::string prefix, Ptr<NetDevice> nd, 
  		bool promiscuous = false, bool explicitFilename = false);
  void EnablePcap (std::string prefix, std::string ndName, 
  		bool promiscuous = false, bool explicitFilename = false);

..
	have a default parameter called ``explicitFilename``.  When set to true,
	this parameter disables the automatic filename completion mechanism and allows
	you to create an explicit filename.  This option is only available in the 
	methods which enable pcap tracing on a single device.  

tem um parmetro padro ``explicitFilename``. Quando modificado para verdadeiro, este parmetro desabilita o mecanismo automtico de completar o nome do arquivo e permite criarmos um nome de arquivo abertamente. Esta opo est disponvel nos mtodos que ativam o rastreamento pcap em um nico dispositivo.

..
	For example, in order to arrange for a device helper to create a single 
	promiscuous pcap capture file of a specific name ("my-pcap-file.pcap") on a
	given device, one could:

Por exemplo, com a finalidade providenciar uma classe assistente de dispositivo para criar um nico arquivo de captura pcap no modo promscuo com um nome especfico ("my-pcap-file.pcap") em um determinado dispositivo:
	
::

  Ptr<NetDevice> nd;
  ...
  helper.EnablePcap ("my-pcap-file.pcap", nd, true, true);

..
	The first ``true`` parameter enables promiscuous mode traces and the second
	tells the helper to interpret the ``prefix`` parameter as a complete filename.

O primeiro parmetro ``true`` habilita o modo de rastreamento promscuo e o segundo faz com que o parmetro ``prefix`` seja interpretado como um nome de arquivo completo.

.. 
	Ascii Tracing Device Helpers

Classes Assistentes de Dispositivo para Rastreamento ASCII
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

..
	The behavior of the ascii trace helper ``mixin`` is substantially similar to 
	the pcap version.  Take a look at ``src/network/helper/trace-helper.h`` if you want to 
	follow the discussion while looking at real code.

O comportamento do assistente  de rastreamento ASCII ``mixin``  similar a verso do pcap. Acesse o arquivo ``src/network/helper/trace-helper.h`` para compreender melhor o funcionamento dessa classe assistente.

..
	The class ``AsciiTraceHelperForDevice`` adds the high level functionality for 
	using ascii tracing to a device helper class.  As in the pcap case, every device
	must implement a single virtual method inherited from the ascii trace ``mixin``.

A classe ``AsciiTraceHelperForDevice`` adiciona funcionalidade em alto nvel para usar o rastreamento ASCII para uma classe assistente de dispositivo. Como no caso do pcap, todo dispositivo deve implementar um mtodo herdado do rastreador ASCII ``mixin``.

::

  virtual void EnableAsciiInternal (Ptr<OutputStreamWrapper> stream,
		std::string prefix, Ptr<NetDevice> nd, bool explicitFilename) = 0;

..
	The signature of this method reflects the device-centric view of the situation
	at this level; and also the fact that the helper may be writing to a shared
	output stream.  All of the public ascii-trace-related methods inherited from 
	class ``AsciiTraceHelperForDevice`` reduce to calling this single device-
	dependent implementation method.  For example, the lowest level ascii trace
	methods,

A assinatura deste mtodo reflete a viso do dispositivo da situao neste nvel; e tambm o fato que o assistente pode ser escrito para um fluxo de sada compartilhado. Todos os mtodos pblicos associados ao rastreamento ASCII herdam da classe ``AsciiTraceHelperForDevice`` resumem-se a chamada deste nico mtodo dependente de implementao. Por exemplo, os mtodos de rastreamento ASCII de mais baixo nvel,

::

  void EnableAscii (std::string prefix, Ptr<NetDevice> nd, 
  		bool explicitFilename = false);
  void EnableAscii (Ptr<OutputStreamWrapper> stream, Ptr<NetDevice> nd);

.. 
	will call the device implementation of ``EnableAsciiInternal`` directly,
	providing either a valid prefix or stream.  All other public ascii tracing 
	methods will build on these low-level functions to provide additional user-level
	functionality.  What this means to the user is that all device helpers in the 
	system will have all of the ascii trace methods available; and these methods
	will all work in the same way across devices if the devices implement 
	``EnablAsciiInternal`` correctly.

chamaro uma implementao de ``EnableAsciiInternal`` diretamente, passando um prefixo ou fluxo vlido. Todos os outros mtodos pblicos sero construdos a partir destas funes de baixo nvel para fornecer funcionalidades adicionais em nvel de usurio. Para o usurio, isso significa que todos os assistentes de
dispositivo no sistema tero todos os mtodos de rastreamento ASCII disponveis e estes mtodos trabalharo do mesmo modo em todos os dispositivos se estes implementarem ``EnableAsciiInternal``.

.. 
	Ascii Tracing Device Helper Methods

Mtodos da Classe Assistente de Dispositivo para Rastreamento  ASCII
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

::

  void EnableAscii (std::string prefix, Ptr<NetDevice> nd, 
  		bool explicitFilename = false);
  void EnableAscii (Ptr<OutputStreamWrapper> stream, Ptr<NetDevice> nd);

  void EnableAscii (std::string prefix, std::string ndName, 
  		bool explicitFilename = false);
  void EnableAscii (Ptr<OutputStreamWrapper> stream, std::string ndName);

  void EnableAscii (std::string prefix, NetDeviceContainer d);
  void EnableAscii (Ptr<OutputStreamWrapper> stream, NetDeviceContainer d);

  void EnableAscii (std::string prefix, NodeContainer n);
  void EnableAscii (Ptr<OutputStreamWrapper> stream, NodeContainer n);

  void EnableAsciiAll (std::string prefix);
  void EnableAsciiAll (Ptr<OutputStreamWrapper> stream);

  void EnableAscii (std::string prefix, uint32_t nodeid, uint32_t deviceid, 
  		bool explicitFilename);
  void EnableAscii (Ptr<OutputStreamWrapper> stream, uint32_t nodeid, 
  		uint32_t deviceid);

..
	You are encouraged to peruse the Doxygen for class ``AsciiTraceHelperForDevice``
	to find the details of these methods; but to summarize ...

Para maiores detalhes sobre os mtodos  interessante consultar a documentao para a classe ``AsciiTraceHelperForDevice``; mas para resumir ...

..
	There are twice as many methods available for ascii tracing as there were for
	pcap tracing.  This is because, in addition to the pcap-style model where traces
	from each unique node/device pair are written to a unique file, we support a model
	in which trace information for many node/device pairs is written to a common file.
	This means that the <prefix>-<node>-<device> file name generation mechanism is 
	replaced by a mechanism to refer to a common file; and the number of API methods
	is doubled to allow all combinations.

H duas vezes mais mtodos disponveis para rastreamento ASCII que para rastreamento pcap. Isto ocorre pois para o modelo pcap os rastreamentos de cada par n/dispositivo-rede so escritos para um nico arquivo, enquanto que no ASCII todo as as informaes so escritas para um arquivo comum. Isto significa que o mecanismo de gerao de nomes de arquivos `<prefixo>-<n>-<dispositivo>`  substitudo por um mecanismo para referenciar um arquivo comum; e o nmero de mtodos da API  duplicado para permitir todas as combinaes.

..
	Just as in pcap tracing, you can enable ascii tracing on a particular 
	node/net-device pair by providing a ``Ptr<NetDevice>`` to an ``EnableAscii``
	method.  The ``Ptr<Node>`` is implicit since the net device must belong to 
	exactly one ``Node``.  For example, 

Assim como no rastreamento pcap, podemos ativar o rastreamento ASCII em um par n/dispositivo-rede passando um ``Ptr<NetDevice>`` para  um mtodo ``EnableAscii``. O ``Ptr<Node>``  implcito pois o dispositivo de rede deve pertencer a exatamente um ``Node``. Por exemplo,

::

  Ptr<NetDevice> nd;
  ...
  helper.EnableAscii ("prefix", nd);

..
	The first four methods also include a default parameter called ``explicitFilename``
	that operate similar to equivalent parameters in the pcap case.

Os primeiros quatro mtodos tambm incluem um parmetro padro ``explicitFilename`` que opera similar aos parmetros no caso do pcap.

..
	In this case, no trace contexts are written to the ascii trace file since they
	would be redundant.  The system will pick the file name to be created using
	the same rules as described in the pcap section, except that the file will
	have the suffix ".tr" instead of ".pcap".

Neste caso, nenhum contexto de rastreamento  escrito para o arquivo ASCII pois seriam redundantes. O sistema pegar o nome do arquivo para ser criado usando as mesmas regras como descritas na seo pcap, exceto que o arquivo ter o extenso ".tr" ao invs de ".pcap".

..
	If you want to enable ascii tracing on more than one net device and have all 
	traces sent to a single file, you can do that as well by using an object to
	refer to a single file.  We have already seen this in the "cwnd" example
	above:

Para habilitar o rastreamento ASCII em mais de um dispositivo de rede e ter todos os dados de rastreamento enviados para um nico arquivo, pode-se usar um objeto para referenciar um nico arquivo. Ns j verificamos isso no exemplo "cwnd":

::

  Ptr<NetDevice> nd1;
  Ptr<NetDevice> nd2;
  ...
  Ptr<OutputStreamWrapper> stream = asciiTraceHelper.CreateFileStream 
  		("trace-file-name.tr");
  ...
  helper.EnableAscii (stream, nd1);
  helper.EnableAscii (stream, nd2);

..
	In this case, trace contexts are written to the ascii trace file since they
	are required to disambiguate traces from the two devices.  Note that since the
	user is completely specifying the file name, the string should include the ",tr"
	for consistency.

Neste caso, os contextos so escritos para o arquivo ASCII quando  necessrio distinguir os dados de rastreamento de dois dispositivos.  interessante usar no nome do arquivo a extenso ".tr" por motivos de consistncia.

..
	You can enable ascii tracing on a particular node/net-device pair by providing a
	``std::string`` representing an object name service string to an 
	``EnablePcap`` method.  The ``Ptr<NetDevice>`` is looked up from the name
	string.  Again, the ``<Node>`` is implicit since the named net device must 
	belong to exactly one ``Node``.  For example, 

Podemos habilitar o rastreamento ASCII em um par n/dispositivo-rede especfico passando ao mtodo ``EnableAscii`` uma ``std::string`` representando um nome no servio de nomes de objetos. O ``Ptr<NetDevice>``  obtido a partir do nome. Novamente, o ``<Node>``  implcito pois o dispositivo de rede deve pertencer a exatamente um ``Node``. Por exemplo,

::

  Names::Add ("client" ...);
  Names::Add ("client/eth0" ...);
  Names::Add ("server" ...);
  Names::Add ("server/eth0" ...);
  ...
  helper.EnableAscii ("prefix", "client/eth0");
  helper.EnableAscii ("prefix", "server/eth0");

..
	This would result in two files named "prefix-client-eth0.tr" and 
	"prefix-server-eth0.tr" with traces for each device in the respective trace
	file.  Since all of the EnableAscii functions are overloaded to take a stream wrapper,
	you can use that form as well:

Isto resultaria em dois nomes de arquivos - "prefix-client-eth0.tr" e "prefix-server-eth0.tr" - com os rastreamentos de cada dispositivo em  seu arquivo respectivo. Como todas as funes do ``EnableAscii`` so sobrecarregadas para suportar um *stream wrapper*, podemos usar da seguinte forma tambm:

::

  Names::Add ("client" ...);
  Names::Add ("client/eth0" ...);
  Names::Add ("server" ...);
  Names::Add ("server/eth0" ...);
  ...
  Ptr<OutputStreamWrapper> stream = asciiTraceHelper.CreateFileStream 
  		("trace-file-name.tr");
  ...
  helper.EnableAscii (stream, "client/eth0");
  helper.EnableAscii (stream, "server/eth0");

..
	This would result in a single trace file called "trace-file-name.tr" that 
	contains all of the trace events for both devices.  The events would be 
	disambiguated by trace context strings.

Isto resultaria em um nico arquivo chamado "trace-file-name.tr" que contm todosos eventos rastreados para ambos os dispositivos. Os eventos seriam diferenciados por `strings` de contexto.

..
	You can enable ascii tracing on a collection of node/net-device pairs by 
	providing a ``NetDeviceContainer``.  For each ``NetDevice`` in the container
	the type is checked.  For each device of the proper type (the same type as is 
	managed by the device helper), tracing is enabled.    Again, the ``<Node>`` is 
	implicit since the found net device must belong to exactly one ``Node``.
	For example, 

Podemos habilitar o rastreamento ASCII em um coleo de pares n/dispositivo-rede fornecendo um ``NetDeviceContainer``. Para cada ``NetDevice`` no continer o tipo  verificado. Para cada dispositivo de um tipo adequado (o mesmo tipo que  gerenciado por uma classe assistente de dispositivo), o rastreamento  habilitado. Novamente, o ``<Node>``  implcito pois o dispositivo de rede encontrado deve pertencer a exatamente um ``Node``. 

::

  NetDeviceContainer d = ...;
  ...
  helper.EnableAscii ("prefix", d);

..
	This would result in a number of ascii trace files being created, each of which
	follows the <prefix>-<node id>-<device id>.tr convention.  Combining all of the
	traces into a single file is accomplished similarly to the examples above:

Isto resultaria em vrios arquivos de rastreamento ASCII sendo criados, cada um seguindo a conveno ``<prefixo>-<id do n>-<id do dispositivo>.tr``.

Para obtermos um nico arquivo teramos:

::

  NetDeviceContainer d = ...;
  ...
  Ptr<OutputStreamWrapper> stream = asciiTraceHelper.CreateFileStream 
  		("trace-file-name.tr");
  ...
  helper.EnableAscii (stream, d);

..
	You can enable ascii tracing on a collection of node/net-device pairs by 
	providing a ``NodeContainer``.  For each ``Node`` in the ``NodeContainer``
	its attached ``NetDevices`` are iterated.  For each ``NetDevice`` attached
	to each node in the container, the type of that device is checked.  For each 
	device of the proper type (the same type as is managed by the device helper), 
	tracing is enabled.

Podemos habilitar o rastreamento ASCII em um coleo de pares n/dispositivo-rede fornecendo um ``NodeContainer``. Para cada ``Node`` no ``NodeContainer``, os seus ``NetDevices`` so percorridos. Para cada ``NetDevice`` associado a cada n no continer, o tipo do dispositivo  verificado. Para cada dispositivo do tipo adequado (o mesmo tipo que  gerenciado pelo assistente de dispositivo), o rastreamento  habilitado.

::

  NodeContainer n;
  ...
  helper.EnableAscii ("prefix", n);

..
	This would result in a number of ascii trace files being created, each of which
	follows the <prefix>-<node id>-<device id>.tr convention.  Combining all of the
	traces into a single file is accomplished similarly to the examples above:
		
Isto resultaria em vrios arquivos ASCII sendo criados, cada um seguindo a conveno ``<prefixo>-<id do n>-<id do dispositivo>.tr``.

..
	You can enable pcap tracing on the basis of node ID and device ID as well as
	with explicit ``Ptr``.  Each ``Node`` in the system has an integer node ID
	and each device connected to a node has an integer device ID.
	
Podemos habilitar o rastreamento pcap na base da `ID` do n e `ID` do dispositivo to bem como com um ``Ptr``. Cada ``Node`` no sistema possui um nmero identificador inteiro associado ao n e cada dispositivo conectado possui um nmero identificador inteiro associado ao dispositivo.

::

  helper.EnableAscii ("prefix", 21, 1);

..
	Of course, the traces can be combined into a single file as shown above.

Os rastreamentos podem ser combinados em um nico arquivo como mostrado acima.

..
	Finally, you can enable pcap tracing for all devices in the system, with the
	same type as that managed by the device helper.

Finalmente, podemos habilitar o rastreamento ASCII para todos os dispositivos no sistema.

::

  helper.EnableAsciiAll ("prefix");

..
	This would result in a number of ascii trace files being created, one for
	every device in the system of the type managed by the helper.  All of these
	files will follow the <prefix>-<node id>-<device id>.tr convention.  Combining
	all of the traces into a single file is accomplished similarly to the examples
	above.

Isto resultaria em vrios arquivos ASCII sendo criados, um para cada dispositivo no sistema do tipo gerenciado pelo assistente. Todos estes arquivos seguiriam a conveno ``<prefixo>-<id do n>-<id do dispositivo>.tr``.

.. 
	Ascii Tracing Device Helper Filename Selection

Selecionando Nome de Arquivo para as Sadas ASCII
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

..
	Implicit in the prefix-style method descriptions above is the construction of the
	complete filenames by the implementation method.  By convention, ascii traces
	in the |ns3| system are of the form "<prefix>-<node id>-<device id>.tr"

Implcito nas descries de mtodos anteriores  a construo do nome de arquivo por meio do mtodo da implementao. Por conveno, rastreamento ASCII no |ns3| usa a forma "``<prefixo>-<id do n>-<id do dispositivo>.tr``".

..
	As previously mentioned, every node in the system will have a system-assigned
	node id; and every device will have an interface index (also called a device id)
	relative to its node.  By default, then, an ascii trace file created as a result
	of enabling tracing on the first device of node 21, using the prefix "prefix",
	would be "prefix-21-1.tr".

Como mencionado, todo n no sistema ter um `id` de n associado; e todo dispositivo ter um ndice de interface (tambm chamado de id do dispositivo) relativo ao seu n. Por padro, ento, um arquivo ASCII criado como um resultado de ativar rastreamento no primeiro dispositivo do n 21 usando o prefixo "prefix" seria "prefix-21-1.tr".

..
	You can always use the |ns3| object name service to make this more clear.
	For example, if you use the object name service to assign the name "server"
	to node 21, the resulting ascii trace file name will automatically become,
	"prefix-server-1.tr" and if you also assign the name "eth0" to the 
	device, your ascii trace file name will automatically pick this up and be called
	"prefix-server-eth0.tr".

Sempre podemos usar o servio de nome de objeto do |ns3| para tornar isso mais claro. Por exemplo, se usarmos o servio para associar o nome ``server`` ao n 21, o arquivo ASCII resultante automaticamente ser, ``prefix-server-1.tr`` e se tambm associarmos o nome ``eth0`` ao dispositivo, o nome do arquivo ASCII automaticamente ser denominado ``prefix-server-eth0.tr``.

..
	Several of the methods have a default parameter called ``explicitFilename``.
	When set to true, this parameter disables the automatic filename completion 
	mechanism and allows you to create an explicit filename.  This option is only
	available in the methods which take a prefix and enable tracing on a single device.  
	
Diversos mtodos tem um parmetro padro ``explicitFilename``. Quando modificado para verdadeiro, este parmetro desabilita o mecanismo automtico de completar o nome do arquivo e permite criarmos um nome de arquivo abertamente. Esta opo est disponvel nos mtodos que possuam um prefixo e ativem o rastreamento em um nico dispositivo.

.. 
	Pcap Tracing Protocol Helpers

Classes Assistentes de Protocolo para Rastreamento Pcap
++++++++++++++++++++++++++++++++++++++++++++++++++++++++

..
	The goal of these ``mixins`` is to make it easy to add a consistent pcap trace
	facility to protocols.  We want all of the various flavors of pcap tracing to 
	work the same across all protocols, so the methods of these helpers are 
	inherited by stack helpers.  Take a look at ``src/network/helper/trace-helper.h``
	if you want to follow the discussion while looking at real code.

O objetivo destes ``mixins``  facilitar a adio de um mecanismo consistente para da facilidade de rastreamento para protocolos. Queremos que todos os mecanismos de rastreamento para todos os protocolos operem de mesma forma, logo os mtodos dessas classe assistentes so herdados por assistentes de pilha. Acesse ``src/network/helper/trace-helper.h`` para acompanhar o contedo discutido nesta seo.

..
	In this section we will be illustrating the methods as applied to the protocol
	``Ipv4``.  To specify traces in similar protocols, just substitute the
	appropriate type.  For example, use a ``Ptr<Ipv6>`` instead of a
	``Ptr<Ipv4>`` and call ``EnablePcapIpv6`` instead of ``EnablePcapIpv4``.

Nesta seo ilustraremos os mtodos aplicados ao protocolo ``Ipv4``. Para especificar rastreamentos em protocolos similares, basta substituir pelo tipo apropriado. Por exemplo, use um ``Ptr<Ipv6>`` ao invs de um ``Ptr<Ipv4>`` e chame um ``EnablePcapIpv6`` ao invs de ``EnablePcapIpv4``.

..
	The class ``PcapHelperForIpv4`` provides the high level functionality for
	using pcap tracing in the ``Ipv4`` protocol.  Each protocol helper enabling these
	methods must implement a single virtual method inherited from this class.  There
	will be a separate implementation for ``Ipv6``, for example, but the only
	difference will be in the method names and signatures.  Different method names
	are required to disambiguate class ``Ipv4`` from ``Ipv6`` which are both 
	derived from class ``Object``, and methods that share the same signature.

A classe ``PcapHelperForIpv4`` prov funcionalidade de alto nvel para usar rastreamento no protocolo ``Ipv4``. Cada classe assistente de protocolo devem implementar um mtodo herdado desta. Haver uma implementao separada para ``Ipv6``, por exemplo, mas a diferena ser apenas nos nomes dos mtodos e assinaturas. Nomes de mtodos diferentes so necessrio para distinguir a classe ``Ipv4`` da ``Ipv6``, pois ambas so derivadas da classe ``Object``, logo os mtodos compartilham a mesma assinatura.

::

  virtual void EnablePcapIpv4Internal (std::string prefix, Ptr<Ipv4> ipv4, 
  		uint32_t interface, bool explicitFilename) = 0;

..
	The signature of this method reflects the protocol and interface-centric view 
	of the situation at this level.  All of the public methods inherited from class 
	``PcapHelperForIpv4`` reduce to calling this single device-dependent
	implementation method.  For example, the lowest level pcap method,

A assinatura desse mtodo reflete a viso do protocolo e interface da situao neste nvel. Todos os mtodos herdados da classe ``PcapHelperForIpv4`` resumem-se a chamada deste nico mtodo dependente de dispositivo. Por exemplo, o mtodo do pcap de mais baixo nvel, 

::

  void EnablePcapIpv4 (std::string prefix, Ptr<Ipv4> ipv4, uint32_t interface, 
  		bool explicitFilename = false);

..
	will call the device implementation of ``EnablePcapIpv4Internal`` directly.
	All other public pcap tracing methods build on this implementation to provide 
	additional user-level functionality.  What this means to the user is that all 
	protocol helpers in the system will have all of the pcap trace methods 
	available; and these methods will all work in the same way across 
	protocols if the helper implements ``EnablePcapIpv4Internal`` correctly.

chamar a implementao de dispositivo de ``EnablePcapIpv4Internal`` diretamente. Todos os outros mtodos pblicos de rastreamento pcap  so construdos a partir desta implementao para prover funcionalidades adicionais em nvel do usurio. Para o usurio, isto significa que todas as classes assistentes de dispositivo no sistema tero todos os mtodos de rastreamento pcap disponveis; e estes mtodos trabalharo da mesma forma entre dispositivos se o dispositivo implementar corretamente ``EnablePcapIpv4Internal``.


.. 
	Pcap Tracing Protocol Helper Methods

Mtodos da Classe Assistente de Protocolo para Rastreamento Pcap
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

..
	These methods are designed to be in one-to-one correspondence with the ``Node``-
	and ``NetDevice``- centric versions of the device versions.  Instead of
	``Node`` and ``NetDevice`` pair constraints, we use protocol and interface
	constraints.

Estes mtodos so projetados para terem correspondncia de um-para-um com o ``Node`` e ``NetDevice``. Ao invs de restries de pares ``Node`` e ``NetDevice``, usamos restries de protocolo e interface.

.. 
	Note that just like in the device version, there are six methods:

Note que como na verso de dispositivo, h seis mtodos:

::

  void EnablePcapIpv4 (std::string prefix, Ptr<Ipv4> ipv4, uint32_t interface, 
  		bool explicitFilename = false);
  void EnablePcapIpv4 (std::string prefix, std::string ipv4Name, 
  		uint32_t interface, bool explicitFilename = false);
  void EnablePcapIpv4 (std::string prefix, Ipv4InterfaceContainer c);
  void EnablePcapIpv4 (std::string prefix, NodeContainer n);
  void EnablePcapIpv4 (std::string prefix, uint32_t nodeid, uint32_t interface, 
  		bool explicitFilename);
  void EnablePcapIpv4All (std::string prefix);

..
	You are encouraged to peruse the Doxygen for class ``PcapHelperForIpv4``
	to find the details of these methods; but to summarize ...

Para maiores detalhes sobre estes mtodos  interessante consultar na documentao da classe ``PcapHelperForIpv4``, mas para resumir ...

..
	You can enable pcap tracing on a particular protocol/interface pair by providing a
	``Ptr<Ipv4>`` and ``interface`` to an ``EnablePcap`` method.  For example, 

Podemos habilitar o rastreamento pcap em um par protocolo/interface  passando um ``Ptr<Ipv4>`` e ``interface`` para um mtodo ``EnablePcap``. Por exemplo,

::

  Ptr<Ipv4> ipv4 = node->GetObject<Ipv4> ();
  ...
  helper.EnablePcapIpv4 ("prefix", ipv4, 0);

..
	You can enable pcap tracing on a particular node/net-device pair by providing a
	``std::string`` representing an object name service string to an 
	``EnablePcap`` method.  The ``Ptr<Ipv4>`` is looked up from the name
	string.  For example, 

Podemos ativar o rastreamento pcap em um par protocolo/interface passando uma ``std::string`` que representa um nome de servio para um mtodo ``EnablePcapIpv4``. O ``Ptr<Ipv4>``  buscado a partir do nome da `string`.
Por exemplo,

::

  Names::Add ("serverIPv4" ...);
  ...
  helper.EnablePcapIpv4 ("prefix", "serverIpv4", 1);

..
	You can enable pcap tracing on a collection of protocol/interface pairs by 
	providing an ``Ipv4InterfaceContainer``.  For each ``Ipv4`` / interface
	pair in the container the protocol type is checked.  For each protocol of the 
	proper type (the same type as is managed by the device helper), tracing is 
	enabled for the corresponding interface.  For example, 

Podemos ativar o rastreamento pcap em uma coleo de pares protocolo/interface usando um ``Ipv4InterfaceContainer``. Para cada par``Ipv4``/interface no continer o tipo do protocolo  verificado. Para cada protocolo do tipo adequado, o rastreamento  ativado para a interface correspondente. Por exemplo,


::

  NodeContainer nodes;
  ...
  NetDeviceContainer devices = deviceHelper.Install (nodes);
  ... 
  Ipv4AddressHelper ipv4;
  ipv4.SetBase ("10.1.1.0", "255.255.255.0");
  Ipv4InterfaceContainer interfaces = ipv4.Assign (devices);
  ...
  helper.EnablePcapIpv4 ("prefix", interfaces);

..
	You can enable pcap tracing on a collection of protocol/interface pairs by 
	providing a ``NodeContainer``.  For each ``Node`` in the ``NodeContainer``
	the appropriate protocol is found.  For each protocol, its interfaces are 
	enumerated and tracing is enabled on the resulting pairs.  For example,

Podemos ativar o rastreamento em uma coleo de pares protocolo/interface usando um ``NodeContainer``. Para cada ``Node`` no ``NodeContainer`` o protocolo apropriado  encontrado. Para cada protocolo, suas interfaces so enumeradas e o rastreamento  ativado nos pares resultantes. Por exemplo,

::

  NodeContainer n;
  ...
  helper.EnablePcapIpv4 ("prefix", n);

..
	You can enable pcap tracing on the basis of node ID and interface as well.  In
	this case, the node-id is translated to a ``Ptr<Node>`` and the appropriate
	protocol is looked up in the node.  The resulting protocol and interface are
	used to specify the resulting trace source.

Pode ativar o rastreamento pcap usando o nmero identificador do n e da interface. Neste caso, o `ID` do n  traduzido para um ``Ptr<Node>`` e o protocolo apropriado  buscado no n. O protocolo e interface resultante so usados para especificar a origem do rastreamento resultante.


::

  helper.EnablePcapIpv4 ("prefix", 21, 1);

..
	Finally, you can enable pcap tracing for all interfaces in the system, with
	associated protocol being the same type as that managed by the device helper.

Por fim, podemos ativar rastreamento pcap para todas as interfaces no sistema, desde que o protocolo seja do mesmo tipo gerenciado pela classe assistente.


::

  helper.EnablePcapIpv4All ("prefix");

.. 
	Pcap Tracing Protocol Helper Filename Selection

Seleo de um Nome de Arquivo para o Rastreamento Pcap da Classe Assistente de Protocolo
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

..
	Implicit in all of the method descriptions above is the construction of the
	complete filenames by the implementation method.  By convention, pcap traces
	taken for devices in the |ns3| system are of the form 
	"<prefix>-<node id>-<device id>.pcap".  In the case of protocol traces,
	there is a one-to-one correspondence between protocols and ``Nodes``.
	This is because protocol ``Objects`` are aggregated to ``Node Objects``.
	Since there is no global protocol id in the system, we use the corresponding
	node id in file naming.  Therefore there is a possibility for file name 
	collisions in automatically chosen trace file names.  For this reason, the
	file name convention is changed for protocol traces.

Implcito nas descries de mtodos anterior  a construo do nome de arquivo por meio do mtodo da implementao. Por conveno, rastreamento pcap no |ns3| usa a forma ``<prefixo>-<id do n>-<id do dispositivo>.pcap``. No caso de rastreamento de protocolos, h uma correspondncia de um-para-um entre protocolos e ``Nodes``. Isto porque ``Objects`` de protocolo so agregados a `Node Objects``. Como no h um `id` global de protocolo no sistema, usamos o `ID` do n na nomeao do arquivo. Consequentemente h possibilidade de coliso de nomes quando usamos o sistema automtico de nomes. Por esta razo, a conveno de nome de arquivo  modificada para rastreamentos de protocolos.

..
	As previously mentioned, every node in the system will have a system-assigned
	node id.  Since there is a one-to-one correspondence between protocol instances
	and node instances we use the node id.  Each interface has an interface id 
	relative to its protocol.  We use the convention 
	"<prefix>-n<node id>-i<interface id>.pcap" for trace file naming in protocol
	helpers.

Como mencionado, todo n no sistema ter um `id` de n associado. Como h uma correspondncia de um-para-um entre instncias de protocolo e instncias de n, usamos o `id` de n. Cada interface tem um `id` de interface relativo ao seu protocolo. Usamos a conveno "<prefixo>-n<id do n>-i<id da interface>.pcap" para especificar o nome do arquivo de rastreamento para as classes assistentes de protocolo.

..
	Therefore, by default, a pcap trace file created as a result of enabling tracing
	on interface 1 of the Ipv4 protocol of node 21 using the prefix "prefix"
	would be "prefix-n21-i1.pcap".

Consequentemente, por padro, uma arquivo pcap criado como um resultado da ativao de rastreamento na interface 1 do protocolo ipv4 do n 21 usando o prefixo ``prefix`` seria ``prefix-n21-i1.pcap``.

..
	You can always use the |ns3| object name service to make this more clear.
	For example, if you use the object name service to assign the name "serverIpv4"
	to the Ptr<Ipv4> on node 21, the resulting pcap trace file name will 
	automatically become, "prefix-nserverIpv4-i1.pcap".

Sempre podemos usar o servio de nomes de objetos do |ns3| para tornar isso mais claro. Por exemplo, se usamos o servio de nomes  para associar o nome "serverIpv4" ao Ptr<Ipv4> no n 21, o nome de arquivo resultante seria ``prefix-nserverIpv4-i1.pcap``.

..
	Several of the methods have a default parameter called ``explicitFilename``.
	When set to true, this parameter disables the automatic filename completion 
	mechanism and allows you to create an explicit filename.  This option is only
	available in the methods which take a prefix and enable tracing on a single device.  

Diversos mtodos tem um parmetro padro ``explicitFilename``. Quando modificado para verdadeiro, este parmetro desabilita o mecanismo automtico de completar o nome do arquivo e permite criarmos um nome de arquivo abertamente. Esta opo est disponvel nos mtodos que  ativam o rastreamento pcap em um nico dispositivo.

.. 
	Ascii Tracing Protocol Helpers

Classes Assistentes de Protocolo para Rastreamento ASCII
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++

..
	The behavior of the ascii trace helpers is substantially similar to the pcap
	case.  Take a look at ``src/network/helper/trace-helper.h`` if you want to 
	follow the discussion while looking at real code.

O comportamento dos assistentes de rastreamento ASCII  similar ao do pcap. Acesse o arquivo ``src/network/helper/trace-helper.h`` para compreender melhor o funcionamento dessa classe assistente.

..
	In this section we will be illustrating the methods as applied to the protocol
	``Ipv4``.  To specify traces in similar protocols, just substitute the
	appropriate type.  For example, use a ``Ptr<Ipv6>`` instead of a
	``Ptr<Ipv4>`` and call ``EnableAsciiIpv6`` instead of ``EnableAsciiIpv4``.

Nesta seo apresentamos os mtodos aplicados ao protocolo ``Ipv4``. Para protocolos similares apenas substitua para o tipo apropriado. Por exemplo, use um ``Ptr<Ipv6>`` ao invs de um  ``Ptr<Ipv4>`` e chame ``EnableAsciiIpv6`` ao invs de ``EnableAsciiIpv4``.

..
	The class ``AsciiTraceHelperForIpv4`` adds the high level functionality
	for using ascii tracing to a protocol helper.  Each protocol that enables these
	methods must implement a single virtual method inherited from this class.

A classe ``AsciiTraceHelperForIpv4`` adiciona funcionalidade de alto nvel para usar rastreamento ASCII para um assistente de protocolo. Todo protocolo que usa estes mtodos deve implementar um mtodo herdado desta classe. 

::

  virtual void EnableAsciiIpv4Internal (Ptr<OutputStreamWrapper> stream, 
                                        std::string prefix, 
                                        Ptr<Ipv4> ipv4, 
                                        uint32_t interface,
                                        bool explicitFilename) = 0;

..
	The signature of this method reflects the protocol- and interface-centric view 
	of the situation at this level; and also the fact that the helper may be writing
	to a shared output stream.  All of the public methods inherited from class 
	``PcapAndAsciiTraceHelperForIpv4`` reduce to calling this single device-
	dependent implementation method.  For example, the lowest level ascii trace
	methods,

A assinatura deste mtodo reflete a viso central do protocolo e interface da situao neste nvel; e tambm o fato que o assistente pode ser escrito para um fluxo de sada compartilhado. Todos os mtodos pblicos herdados desta classe ``PcapAndAsciiTraceHelperForIpv4`` resumem-se a chamada deste nico mtodo dependente de implementao. Por exemplo, os mtodos de rastreamento ASCII de mais baixo nvel,

::

  void EnableAsciiIpv4 (std::string prefix, Ptr<Ipv4> ipv4, uint32_t interface, 
  		bool explicitFilename = false);
  void EnableAsciiIpv4 (Ptr<OutputStreamWrapper> stream, Ptr<Ipv4> ipv4, 
  		uint32_t interface);

..
	will call the device implementation of ``EnableAsciiIpv4Internal`` directly,
	providing either the prefix or the stream.  All other public ascii tracing 
	methods will build on these low-level functions to provide additional user-level
	functionality.  What this means to the user is that all device helpers in the 
	system will have all of the ascii trace methods available; and these methods
	will all work in the same way across protocols if the protocols implement 
	``EnablAsciiIpv4Internal`` correctly.

chamaro uma implementao de ``EnableAsciiIpv4Internal`` diretamente, passando um prefixo ou fluxo vlido. Todos os outros mtodos pblicos sero construdos a partir destas funes de baixo nvel para fornecer funcionalidades adicionais em nvel de usurio. Para o usurio, isso significa que todos os assistentes de protocolos no sistema tero todos os mtodos de rastreamento ASCII disponveis e estes mtodos trabalharo do mesmo modo em todos os protocolos se estes implementarem ``EnableAsciiIpv4Internal``.


.. 
	Ascii Tracing Protocol Helper Methods

Mtodos da Classe Assistente de Protocolo para Rastreamento ASCII
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

::

  void EnableAsciiIpv4 (std::string prefix, Ptr<Ipv4> ipv4, uint32_t interface, 
                        bool explicitFilename = false);
  void EnableAsciiIpv4 (Ptr<OutputStreamWrapper> stream, Ptr<Ipv4> ipv4,
                        uint32_t interface);

  void EnableAsciiIpv4 (std::string prefix, std::string ipv4Name, uint32_t interface,
                        bool explicitFilename = false);
  void EnableAsciiIpv4 (Ptr<OutputStreamWrapper> stream, std::string ipv4Name,
                        uint32_t interface);

  void EnableAsciiIpv4 (std::string prefix, Ipv4InterfaceContainer c);
  void EnableAsciiIpv4 (Ptr<OutputStreamWrapper> stream, Ipv4InterfaceContainer c);

  void EnableAsciiIpv4 (std::string prefix, NodeContainer n);
  void EnableAsciiIpv4 (Ptr<OutputStreamWrapper> stream, NodeContainer n);

  void EnableAsciiIpv4All (std::string prefix);
  void EnableAsciiIpv4All (Ptr<OutputStreamWrapper> stream);

  void EnableAsciiIpv4 (std::string prefix, uint32_t nodeid, uint32_t deviceid,
                        bool explicitFilename);
  void EnableAsciiIpv4 (Ptr<OutputStreamWrapper> stream, uint32_t nodeid, 
                        uint32_t interface);

..
	You are encouraged to peruse the Doxygen for class ``PcapAndAsciiHelperForIpv4``
	to find the details of these methods; but to summarize ...

Para maiores detalhes sobre os mtodos consulte na documentao a classe ``PcapAndAsciiHelperForIpv4``; mas para resumir ...

..
	There are twice as many methods available for ascii tracing as there were for
	pcap tracing.  This is because, in addition to the pcap-style model where traces
	from each unique protocol/interface pair are written to a unique file, we 
	support a model in which trace information for many protocol/interface pairs is 
	written to a common file.  This means that the <prefix>-n<node id>-<interface>
	file name generation mechanism is replaced by a mechanism to refer to a common 
	file; and the number of API methods is doubled to allow all combinations.

H duas vezes mais mtodos disponveis para rastreamento ASCII que para rastreamento pcap. Isto ocorre pois para o modelo pcap os rastreamentos de cada par protocolo/interface so escritos para um nico arquivo, enquanto que no ASCII todo as as informaes so escritas para um arquivo comum. Isto significa que o mecanismo de gerao de nomes de arquivos "<prefixo>-n<id do n>-i<interface>"  substitudo por um mecanismo para referenciar um arquivo comum; e o nmero de mtodos da API  duplicado para permitir todas as combinaes.

..
	Just as in pcap tracing, you can enable ascii tracing on a particular 
	protocol/interface pair by providing a ``Ptr<Ipv4>`` and an ``interface``
	to an ``EnableAscii`` method.
	For example, 

Assim, como no rastreamento pcap, podemos ativar o rastreamento ASCII em um par protocolo/interface passando um ``Ptr<Ipv4>`` e uma ``interface`` para  um mtodo ``EnableAsciiIpv4``. Por exemplo,


::

  Ptr<Ipv4> ipv4;
  ...
  helper.EnableAsciiIpv4 ("prefix", ipv4, 1);

..
	In this case, no trace contexts are written to the ascii trace file since they
	would be redundant.  The system will pick the file name to be created using
	the same rules as described in the pcap section, except that the file will
	have the suffix ".tr" instead of ".pcap".

Neste caso, nenhum contexto de rastreamento  escrito para o arquivo ASCII pois seriam redundantes. O sistema pegar o nome do arquivo para ser criado usando as mesmas regras como descritas na seo pcap, exceto que o arquivo ter o extenso ``.tr`` ao invs de ``.pcap``.

..
	If you want to enable ascii tracing on more than one interface and have all 
	traces sent to a single file, you can do that as well by using an object to
	refer to a single file.  We have already something similar to this in the
	"cwnd" example above:

Para habilitar o rastreamento ASCII em mais de uma interface e ter todos os dados de rastreamento enviados para um nico arquivo, pode-se usar um objeto para referenciar um nico arquivo. Ns j verificamos isso no exemplo "cwnd":

::

  Ptr<Ipv4> protocol1 = node1->GetObject<Ipv4> ();
  Ptr<Ipv4> protocol2 = node2->GetObject<Ipv4> ();
  ...
  Ptr<OutputStreamWrapper> stream = asciiTraceHelper.CreateFileStream 
  		("trace-file-name.tr");
  ...
  helper.EnableAsciiIpv4 (stream, protocol1, 1);
  helper.EnableAsciiIpv4 (stream, protocol2, 1);

..
	In this case, trace contexts are written to the ascii trace file since they
	are required to disambiguate traces from the two interfaces.  Note that since 
	the user is completely specifying the file name, the string should include the
	",tr" for consistency.

Neste caso, os contextos so escritos para o arquivo ASCII quando  necessrio distinguir os dados de rastreamento de duas interfaces.  interessante usar no nome do arquivo a extenso ``.tr`` por motivos de consistncia.

..
	You can enable ascii tracing on a particular protocol by providing a 
	``std::string`` representing an object name service string to an 
	``EnablePcap`` method.  The ``Ptr<Ipv4>`` is looked up from the name
	string.  The ``<Node>`` in the resulting filenames is implicit since there
	is a one-to-one correspondence between protocol instances and nodes,
	For example, 

Pode habilitar o rastreamento ASCII em protocolo especfico passando ao mtodo ``EnableAsciiIpv4`` uma ``std::string`` representando um nome no servio de nomes de objetos. O ``Ptr<Ipv4>``  obtido a partir do nome. O ``<Node>``  implcito, pois h uma correspondncia de um-para-um entre instancias de protocolos e ns. Por exemplo,

::

  Names::Add ("node1Ipv4" ...);
  Names::Add ("node2Ipv4" ...);
  ...
  helper.EnableAsciiIpv4 ("prefix", "node1Ipv4", 1);
  helper.EnableAsciiIpv4 ("prefix", "node2Ipv4", 1);

..
	This would result in two files named "prefix-nnode1Ipv4-i1.tr" and 
	"prefix-nnode2Ipv4-i1.tr" with traces for each interface in the respective 
	trace file.  Since all of the EnableAscii functions are overloaded to take a 
	stream wrapper, you can use that form as well:

Isto resultaria em dois nomes de arquivos ``prefix-nnode1Ipv4-i1.tr`` e ``prefix-nnode2Ipv4-i1.tr``, com os rastreamentos de cada interface em  seu arquivo respectivo. Como todas as funes do ``EnableAsciiIpv4`` so sobrecarregadas para suportar um *stream wrapper*, podemos usar da seguinte forma tambm:


::

  Names::Add ("node1Ipv4" ...);
  Names::Add ("node2Ipv4" ...);
  ...
  Ptr<OutputStreamWrapper> stream = asciiTraceHelper.CreateFileStream 
  		("trace-file-name.tr");
  ...
  helper.EnableAsciiIpv4 (stream, "node1Ipv4", 1);
  helper.EnableAsciiIpv4 (stream, "node2Ipv4", 1);

..
	This would result in a single trace file called "trace-file-name.tr" that 
	contains all of the trace events for both interfaces.  The events would be 
	disambiguated by trace context strings.

Isto resultaria em um nico arquivo chamado ``trace-file-name.tr`` que contm todos os eventos rastreados para ambas as interfaces. Os eventos seriam diferenciados por `strings` de contexto.

.. 
	You can enable ascii tracing on a collection of protocol/interface pairs by 
	providing an ``Ipv4InterfaceContainer``.  For each protocol of the proper 
	type (the same type as is managed by the device helper), tracing is enabled
	for the corresponding interface.  Again, the ``<Node>`` is implicit since 
	there is a one-to-one correspondence between each protocol and its node.
	For example, 

Podemos habilitar o rastreamento ASCII em um coleo de pares protocolo/interface provendo um ``Ipv4InterfaceContainer``. Para cada protocolo no continer o tipo  verificado. Para cada protocolo do tipo adequado (o mesmo tipo que  gerenciado por uma classe assistente de protocolo), o rastreamento  habilitado para a interface correspondente. Novamente, o ``<Node>``  implcito, pois h uma correspondncia de um-para-um entre protocolo e seu n. Por exemplo,


::

  NodeContainer nodes;
  ...
  NetDeviceContainer devices = deviceHelper.Install (nodes);
  ... 
  Ipv4AddressHelper ipv4;
  ipv4.SetBase ("10.1.1.0", "255.255.255.0");
  Ipv4InterfaceContainer interfaces = ipv4.Assign (devices);
  ...
  ...
  helper.EnableAsciiIpv4 ("prefix", interfaces);

..
	This would result in a number of ascii trace files being created, each of which
	follows the <prefix>-n<node id>-i<interface>.tr convention.  Combining all of the
	traces into a single file is accomplished similarly to the examples above:

Isto resultaria em vrios arquivos de rastreamento ASCII sendo criados, cada um seguindo a conveno ``<prefixo>-n<id do n>-i<interface>.tr``. 

Para obtermos um nico arquivo teramos:

::

  NodeContainer nodes;
  ...
  NetDeviceContainer devices = deviceHelper.Install (nodes);
  ... 
  Ipv4AddressHelper ipv4;
  ipv4.SetBase ("10.1.1.0", "255.255.255.0");
  Ipv4InterfaceContainer interfaces = ipv4.Assign (devices);
  ...
  Ptr<OutputStreamWrapper> stream = asciiTraceHelper.CreateFileStream 
  		("trace-file-name.tr");
  ...
  helper.EnableAsciiIpv4 (stream, interfaces);

..
	You can enable ascii tracing on a collection of protocol/interface pairs by 
	providing a ``NodeContainer``.  For each ``Node`` in the ``NodeContainer``
	the appropriate protocol is found.  For each protocol, its interfaces are 
	enumerated and tracing is enabled on the resulting pairs.  For example,

Podemos habilitar o rastreamento ASCII em uma coleo de pares protocolo/interface provendo um `NodeContainer``. Para cada ``Node`` no ``NodeContainer`` os protocolos apropriados so encontrados. Para cada protocolo, sua interface  enumerada e o rastreamento  habilitado nos pares. Por exemplo,

::

  NodeContainer n;
  ...
  helper.EnableAsciiIpv4 ("prefix", n);

..
	You can enable pcap tracing on the basis of node ID and device ID as well.  In
	this case, the node-id is translated to a ``Ptr<Node>`` and the appropriate
	protocol is looked up in the node.  The resulting protocol and interface are
	used to specify the resulting trace source.

Podemos habilitar o rastreamento pcap usando o nmero identificador do n e nmero identificador do dispositivo. Neste caso, o `ID` do n  traduzido para um ``Ptr<Node>`` e o protocolo apropriado  procurado no n de rede. O protocolo e interface resultantes so usados para especificar a origem do rastreamento.

::

  helper.EnableAsciiIpv4 ("prefix", 21, 1);

.. 
	Of course, the traces can be combined into a single file as shown above.

Os rastreamentos podem ser combinados em um nico arquivo como mostrado anteriormente.

.. 
	Finally, you can enable ascii tracing for all interfaces in the system, with
	associated protocol being the same type as that managed by the device helper.

Finalmente, podemos habilitar o rastreamento ASCII para todas as interfaces no sistema.

::

  helper.EnableAsciiIpv4All ("prefix");

..
	This would result in a number of ascii trace files being created, one for
	every interface in the system related to a protocol of the type managed by the
	helper.  All of these files will follow the <prefix>-n<node id>-i<interface.tr
	convention.  Combining all of the traces into a single file is accomplished 
	similarly to the examples above.

Isto resultaria em vrios arquivos ASCII sendo criados, um para cada interface no sistema relacionada ao protocolo do tipo gerenciado pela classe assistente.Todos estes arquivos seguiriam a conveno
``<prefix>-n<id do node>-i<interface>.tr``.


.. 
	Ascii Tracing Protocol Helper Filename Selection

Seleo de Nome de Arquivo para Rastreamento ASCII da Classe Assistente de Protocolo 
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

..
	Implicit in the prefix-style method descriptions above is the construction of the
	complete filenames by the implementation method.  By convention, ascii traces
	in the |ns3| system are of the form "<prefix>-<node id>-<device id>.tr"

Implcito nas descries de mtodos anteriores  a construo do nome do arquivo por meio do mtodo da implementao. Por conveno, rastreamento ASCII no sistema |ns3| so da forma ``<prefix>-<id node>-<id do dispositivo>.tr``.

..
	As previously mentioned, every node in the system will have a system-assigned
	node id.  Since there is a one-to-one correspondence between protocols and nodes
	we use to node-id to identify the protocol identity.  Every interface on a 
	given protocol will have an interface index (also called simply an interface) 
	relative to its protocol.  By default, then, an ascii trace file created as a result
	of enabling tracing on the first device of node 21, using the prefix "prefix",
	would be "prefix-n21-i1.tr".  Use the prefix to disambiguate multiple protocols
	per node.

Como mencionado, todo n no sistema ter um nmero identificador de n associado. Como h uma correspondncia de um-para-um entre instncias de protocolo e instncias de n, usamos o `ID` de n. Cada interface em um protocolo ter um ndice de interface (tambm chamando apenas de interface) relativo ao seu protocolo. Por padro, ento, um arquivo de rastreamento ASCII criado a partir do rastreamento no primeiro dispositivo do n 21, usando o prefixo "prefix", seria ``prefix-n21-i1.tr``. O uso de prefixo distingue mltiplos protocolos por n.

..
	You can always use the |ns3| object name service to make this more clear.
	For example, if you use the object name service to assign the name "serverIpv4"
	to the protocol on node 21, and also specify interface one, the resulting ascii 
	trace file name will automatically become, "prefix-nserverIpv4-1.tr".

Sempre podemos usar o servio de nomes de objetos do |ns3| para tornar isso mais claro. Por exemplo, se usarmos o servio de nomes para associar o nome "serverIpv4" ao Ptr<Ipv4> no n 21, o nome de arquivo resultante seria ``prefix-nserverIpv4-i1.tr``.

..
	Several of the methods have a default parameter called ``explicitFilename``.
	When set to true, this parameter disables the automatic filename completion 
	mechanism and allows you to create an explicit filename.  This option is only
	available in the methods which take a prefix and enable tracing on a single device.  

Diversos mtodos tem um parmetro padro ``explicitFilename``. Quando modificado para verdadeiro, este parmetro desabilita o mecanismo automtico de completar o nome do arquivo e permite criarmos um nome de arquivo abertamente. Esta opo est disponvel nos mtodos que  ativam o rastreamento em um nico dispositivo.


.. 
	Summary

Consideraes Finais
********************

..
	|ns3| includes an extremely rich environment allowing users at several 
	levels to customize the kinds of information that can be extracted from 
	simulations.  

O |ns3| inclui um ambiente completo para permitir usurios de diversos nveis  personalizar os tipos de informao para serem extradas de suas simulaes.

..
	There are high-level helper functions that allow users to simply control the 
	collection of pre-defined outputs to a fine granularity.  There are mid-level
	helper functions to allow more sophisticated users to customize how information
	is extracted and saved; and there are low-level core functions to allow expert
	users to alter the system to present new and previously unexported information
	in a way that will be immediately accessible to users at higher levels.

Existem funes assistentes de alto nvel que permitem ao usurio o controle de um coleo de sadas predefinidas para uma granularidade mais fina. Existem funes assistentes de nvel intermedirio que permitem usurios mais sofisticados personalizar como as informaes so extradas e armazenadas; e existem funes de baixo nvel que permitem usurios avanados alterarem o sistema para apresentar novas ou informaes que no eram exportadas.

..
	This is a very comprehensive system, and we realize that it is a lot to 
	digest, especially for new users or those not intimately familiar with C++
	and its idioms.  We do consider the tracing system a very important part of
	|ns3| and so recommend becoming as familiar as possible with it.  It is
	probably the case that understanding the rest of the |ns3| system will
	be quite simple once you have mastered the tracing system

Este  um sistema muito abrangente e percebemos que  muita informao para digerir, especialmente para novos usurios ou aqueles que no esto intimamente familiarizados com C++ e suas expresses idiomticas. Consideramos o sistema de rastreamento uma parte muito importante do |ns3|, assim recomendamos que familiarizem-se o mximo possvel com ele. Compreender o restante do sistema |ns3|  bem simples, uma vez que dominamos o sistema de rastreamento.