[go: up one dir, main page]

Menu

[r998]: / trunk / VTS3 / VTSDoc.cpp  Maximize  Restore  History

Download this file

4673 lines (3728 with data), 126.6 kB

   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
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
// VTSDoc.cpp : implementation of the VTSDoc class
//
#include "stdafx.h"
#include <afxmt.h>
#include <direct.h>
#include "VTS.h"
#include "VTSPreferences.h"
#include "Mainfrm.h"
#include "VTSDoc.h"
#include "VTSPortDlg.h"
#include "VTSNamesDlg.h"
#include "VTSDevicesTreeDlg.h"
#include "VTSFiltersDlg.h"
#include "FrameContext.h"
#include "Send.h"
#include "SendPage.h"
#include "ScriptExecutor.h"
#include "VTSStatisticsCollector.h"
#include "VTSStatisticsDlg.h"
#include "VTSWinPTPPort.h"
#include "VTSWinMSTPPort.h"
#include "PropID.h"
#include "BakRestoreExecutor.h"
#include "InconsistentParsExecutor.h"
#include "DiscoveryExecutor.h"
#include "VTSInconsistentParsDlg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
#define NT_DebugMemState 0
/////////////////////////////////////////////////////////////////////////////
// VTSDoc
LPCSTR VTSDoc::m_pszDefaultFilename = "vts3.cfg";
IMPLEMENT_DYNCREATE(VTSDoc, CDocument)
BEGIN_MESSAGE_MAP(VTSDoc, CDocument)
//{{AFX_MSG_MAP(VTSDoc)
ON_COMMAND(ID_VIEW_STATISTICS, OnViewStatistics)
ON_COMMAND(ID_EDIT_QUICKSAVE, OnEditQuickSave)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// VTSDoc construction/destruction
#if NT_DebugMemState
_CrtMemState s1, s2, s3;
#endif
VTSDoc::VTSDoc()
: m_FrameContexts(0)
, m_pPortDlg(0), m_postMessages(false), m_pStatitiscsDlg(0)
, m_nPacketCount(0)
, m_strLogFilename("vts3.vpk")
{
#if NT_DebugMemState
_CrtMemCheckpoint( &s1 );
#endif
m_bStatisticsDlgInUse=false;
m_pStatisticsCollector=NULL;
m_apPackets.SetSize(0, 400); // reallocate in 1600 byte chunks (for DWORD size pointer)
m_fLoadPackets = true;
for (int ix = 0; ix < sizeof(m_pSegmentAccumulator)/sizeof(m_pSegmentAccumulator[0]); ix++)
{
m_pSegmentAccumulator[ix] = NULL;
}
}
//
// VTSDoc::~VTSDoc
//
// The only responsibility of the destructor is cleaning up after itself.
// When a new document is canceled, the document object is destroyed before
// the clients, so they really don't know their context has gone away.
//
VTSDoc::~VTSDoc()
{
while (m_FrameContexts)
UnbindFrameContext( m_FrameContexts );
DestroyPacketArray();
#if NT_DebugMemState
_CrtMemCheckpoint( &s2 );
_CrtMemDumpAllObjectsSince( &s1 );
_CrtMemDifference( &s3, &s1, &s2 );
_CrtMemDumpStatistics( &s3 );
#endif
for (int ix = 0; ix < sizeof(m_pSegmentAccumulator)/sizeof(m_pSegmentAccumulator[0]); ix++)
{
delete m_pSegmentAccumulator[ix];
m_pSegmentAccumulator[ix] = NULL;
}
}
// switch CWD to path supplied by relative... Even if we're not doing relative paths
// the CWD doesn't matter...
void VTSDoc::ChangeCWDToWorkspace( LPCSTR lpszWksFile /* = NULL */ )
{
CString strPath;
if (lpszWksFile)
{
strPath = lpszWksFile;
}
StripToPath(&strPath);
// now change directories if there is any left
if ( !strPath.IsEmpty() )
_chdir(strPath);
}
LPCSTR VTSDoc::StripToPath( CString * pstr )
{
if ( pstr == NULL )
return NULL;
// if no path supplied, get it from the document... might be null if in document open
// hence the supplied path
if ( pstr->IsEmpty() )
*pstr = GetPathName();
// reduce string to path only
int n = pstr->GetLength();
for ( char * p = pstr->GetBuffer(1); p != NULL && n > 0 && p[n-1] != '\\'; n-- )
p[n-1] = 0;
pstr->ReleaseBuffer();
return *pstr;
}
//
// VTSDoc::OnNewDocument
//
BOOL VTSDoc::OnNewDocument()
{
// be nice to the base class, but it is not used
if (!CDocument::OnNewDocument())
return FALSE;
// must have this here to add to recent workspace list and
// tell document what name we're using...
SetPathName(m_pszDefaultFilename);
// Initialize default data for vts3.cfg
SetTitle(m_pszDefaultFilename);
// Always make sure we're in the workspace directory before attempting to open the
// logfile... this way the logfile name, if relative, will open correctly. If not relative,
// then, CWD doesn't matter.
ChangeCWDToWorkspace();
if ( !m_PacketDB.Open(m_strLogFilename) )
return FALSE;
DestroyPacketArray();
// Create a default Device called TD, per the "Survival Guide".
bool more = true;
int sel;
while (more)
{
sel = AfxMessageBox( "VTS can respond to some BACnet services, including Who-Is and ReadProperty."
"\n\n"
"We recommend that you define the Device 'TD', to specify how "
"VTS should respond, and how it should perform segmentation."
"\n\n"
"Would you like to create 'TD' now?",
MB_YESNO | MB_ICONQUESTION );
more = (sel == IDYES);
if (more)
{
// We can pre-define this one.
VTSDevice *pDevice = new VTSDevice;
pDevice->m_strName = "TD";
m_devices.Add( pDevice );
// Show a dialog so they can see all the parameters.
// Don't care whether or not they change anything.
VTSDevicesTreeDlg dlg( &m_devices );
dlg.DoModal();
break;
}
}
// Create a default Port, per the "Survival Guide".
while (more)
{
sel = AfxMessageBox( "You will not be able to send or receive packets until you "
"create a Port to specify a communications interface."
"\n\n"
"Would you like to create a Port now?",
MB_YESNO | MB_ICONQUESTION );
more = (sel == IDYES);
if (more)
{
VTSPortDlg dlg(this);
m_pPortDlg = &dlg;
sel = dlg.DoModal();
m_pPortDlg = NULL;
if (sel == IDOK)
break;
}
}
// Create a Name for IUT, per the "Survival Guide".
while (more)
{
sel = AfxMessageBox( "We recommend that you define the Name 'IUT' for "
"the device that you want to test. Using 'IUT' makes "
"Script syntax simpler."
"\n\n"
"Names are shown instead of addresses in the packet "
"list. You may choose to define additional "
"Names for other devices on your network as well."
"\n\n"
"Would you like to create Names now?",
MB_YESNO | MB_ICONQUESTION );
more = (sel == IDYES);
if (more)
{
VTSNamesDlg dlg( GetNames(), GetPorts() );
sel = dlg.DoModal();
if (sel == IDOK)
break;
}
}
// We've got to save the file with the defaults in there...
if ( !OnSaveDocument(m_pszDefaultFilename) )
return FALSE;
// ready for messages
m_postMessages = true;
// create a new statistics collector
m_pStatisticsCollector=new VTSStatisticsCollector();
// it should be empty!
m_nPacketCount = 0;
ScheduleForProcessing();
return TRUE;
}
//
// VTSDoc::OnOpenDocument
//
BOOL VTSDoc::OnOpenDocument(LPCTSTR lpszPathName)
{
// We need to check to see if the file exists... if not, or there was an error opening the file,
// then open the default.
CFileStatus fs;
if ( CFile::GetStatus(lpszPathName, fs) == FALSE )
return FALSE;
// Calls serialization mechanisms... After complete, all data will be loaded (except packets)
if (!CDocument::OnOpenDocument(lpszPathName))
return FALSE;
// Always make sure we're in the workspace directory before attempting to open the
// logfile... this way the logfile name, if relative, will open correctly. If not relative,
// then, CWD doesn't matter.
// Try to open packet file... create if not exist and report if problem...
ChangeCWDToWorkspace(lpszPathName);
if ( !m_PacketDB.Open(m_strLogFilename) && !DoPacketFileNameDialog(false) )
return FALSE;
// create a new statistics collector
m_pStatisticsCollector=new VTSStatisticsCollector();
DestroyPacketArray();
LoadPacketArray();
// link all in memory structures together
FixupPortToDeviceLinks();
FixupNameToPortLinks();
FixupFiltersToPortLinks();
try
{
for ( int n = 0; n < m_devices.GetSize(); n++ )
m_devices[n]->Activate();
for ( int i = 0; i < m_ports.GetSize(); i++ )
m_ports[i]->Refresh();
}
catch (...)
{
AfxMessageBox("An unexpected exception ocurred initializing ports and devices.");
}
// ready for messages
m_postMessages = true;
ScheduleForProcessing();
return TRUE;
}
//
// VTSDoc::OnCloseDocument
//
void VTSDoc::OnCloseDocument()
{
// delete the statistics collector
if (m_pStatisticsCollector)
delete m_pStatisticsCollector;
// no more messages please
m_postMessages = false;
// if the executor is associated with this document, kill it
if (gExecutor.IsBound(this))
gExecutor.Kill( true );
for ( int i = 0; i < m_ports.GetSize(); i++ )
m_ports[i]->Deactivate();
for ( int n = 0; n < m_devices.GetSize(); n++ )
m_devices[n]->Deactivate();
m_PacketDB.Close();
DestroyPacketArray();
// pass along to the framework
CDocument::OnCloseDocument();
}
// This method is called by the framework during an open...
// We need to override it so we call it telling it NOT to add this document
// to the standard document MRU list...
// Add it to our own for workspaces...
void VTSDoc::SetPathName(LPCTSTR lpszPathName, BOOL bAddToMRU)
{
CDocument::SetPathName(lpszPathName, FALSE);
// Path has been made full and stored in document...
// Now add this document to recent workspaces...
((VTSApp *) AfxGetApp())->AddToRecentWorkspaceList(GetPathName());
}
//
// VTSDoc::DoPortsDialog
//
void VTSDoc::DoPortsDialog( void )
{
VTSPortDlg dlg(this);
m_pPortDlg = &dlg;
if ( dlg.DoModal() == IDOK )
SaveConfiguration();
m_pPortDlg = NULL;
}
//
// VTSDoc::DoNamesDialog
//
void VTSDoc::DoNamesDialog( void )
{
VTSNamesDlg dlg( GetNames(), GetPorts() );
if ( dlg.DoModal() == IDOK )
SaveConfiguration();
}
//
// VTSDoc::DoCaptureFiltersDialog
//
void VTSDoc::DoCaptureFiltersDialog( void )
{
VTSFiltersDlg dlg( GetCaptureFilters(), GetPorts() );
if ( dlg.DoModal() == IDOK )
SaveConfiguration();
}
//
// VTSDoc::DoDisplayFiltersDialog
//
void VTSDoc::DoDisplayFiltersDialog( void )
{
VTSFiltersDlg dlg( GetDisplayFilters(), GetPorts() );
if ( dlg.DoModal() == IDOK ) {
SaveConfiguration();
// reload all the packets, applying the (new) filter
ReloadPacketStore();
// tell the application the list has changed
ScheduleForProcessing();
}
}
void VTSDoc::ReActivateAllPorts()
{
for ( int i = 0; i < m_ports.GetSize(); i++ )
if ( m_ports[i]->IsDirty() )
m_ports[i]->Refresh();
}
void VTSDoc::SetNewCacheSize(void)
{
// make sure nobody else is using the list
m_FrameContextsCS.Lock();
for (CFrameContext* cur = m_FrameContexts; cur; cur = cur->m_NextFrame)
cur->UpdatePrefs();
// release the list back to other threads
m_FrameContextsCS.Unlock();
}
// Called by the list view in driving what ought to be cached...
// This allows us to prep our virtual list of VTSPackets with a caching scheme if we're going
// virtual...
// nFrom is the item number (lo) to start loading cache for and nTo is the high.
void VTSDoc::CacheHint(int nFrom, int nTo)
{
// for now do nothing since our m_apPacket pointer array holds pointers to all of our packets
// when we go virtual we'll do something else about this...
}
//
// VTSDoc::DoDevicesDialog
//
void VTSDoc::DoDevicesDialog( void )
{
VTSDevicesTreeDlg dlg( &m_devices );
if ( dlg.DoModal() == IDOK )
SaveConfiguration();
}
void VTSDoc::SaveConfiguration()
{
OnSaveDocument(GetPathName());
}
bool VTSDoc::DoPacketFileNameDialog( bool fReload /* = true */ )
{
CString newName = _T("NewPacketFile.vpk");
CString strPath;
CFileDialog dlgFile(TRUE);
dlgFile.m_ofn.Flags |= OFN_HIDEREADONLY | OFN_PATHMUSTEXIST;
CString strFilter(_T("VTS Packet Files (*.vpk)"));
strFilter += (TCHAR)'\0';
strFilter += _T("*.vpk");
strFilter += (TCHAR)'\0';
strFilter += _T("All Files (*.*)");
strFilter += (TCHAR)'\0';
strFilter += _T("*.*");
strFilter += (TCHAR)'\0';
dlgFile.m_ofn.nMaxCustFilter = 2;
dlgFile.m_ofn.lpstrFilter = strFilter;
dlgFile.m_ofn.lpstrTitle = "Specify Packet File";
dlgFile.m_ofn.lpstrFile = newName.GetBuffer(_MAX_PATH);
dlgFile.m_ofn.lpstrInitialDir = StripToPath(&strPath);
CString strStatusText;
strStatusText.Format("Current logfile: %s", m_strLogFilename );
((CFrameWnd *) AfxGetApp()->m_pMainWnd)->SetMessageText(strStatusText);
// Change CWD and also specify lpstrInitialDir for 2000 and XP...
// This always starts the search for a new logfile from the workspace directory
ChangeCWDToWorkspace(); // for W98 ??
int nResult = dlgFile.DoModal();
newName.ReleaseBuffer();
CString pathname = newName;
ChangeCWDToWorkspace(); // for W98 ??
// packet file open auto closes old packet file if it was opened... it leaves everything as it was
// if the open failed and it even reports an error upon fail.
if ( nResult != IDOK )
return false;
if ( gVTSPreferences.Setting_IsPacketFileRelative() )
ConvertPathToRelative(&newName);
// After path name conversion... only attempt open if the new file is diff from old
// This is a problem if they specify the same file and they've switched between relative and absolute
if ( !m_strLogFilename.CompareNoCase(newName) || !m_PacketDB.Open(newName) )
return false;
m_strLogFilename = newName;
SaveConfiguration();
//added: 2004/12/06 author:Xiao Shiyuan purpose:save log file history
CMainFrame* pMainFrame = (CMainFrame*)AfxGetApp()->GetMainWnd();
pMainFrame->SaveLogFileHistory((LPCTSTR)pathname);
// Some usage of this function is only to re-specify loading of lost packet file linkage
// during loading... Don't bother reloading list because that's our calling context
if ( !fReload )
return true;
strStatusText.Format(IDS_NEWPACKETFILENAME, m_strLogFilename);
ReloadPacketStore();
AfxMessageBox(strStatusText);
// Must call this here.. for some reason we won't see the main list view update until we let this
// message box go, at which time the message in the queue will have been lost (why?)
ScheduleForProcessing();
strStatusText.Format("Loaded logfile: %s", m_strLogFilename );
((CFrameWnd *) AfxGetApp()->m_pMainWnd)->SetMessageText(strStatusText);
return true;
}
void VTSDoc::ConvertPathToRelative( CString * pstr )
{
CString strPathRelative;
CString strOld = *pstr;
// Loads the workspace directory.. which is what we want to make the supplied filename relative to
StripToPath(&strPathRelative);
int nLen1 = strPathRelative.GetLength();
int nLen2 = strOld.GetLength();
int nStart = 0;
// scan start of both strings and compare... continue while equal
// or length runs out and increment position where directories start...
for ( int n = 0; n < nLen1 && n < nLen2 && strPathRelative[n] == strOld[n]; n++ )
if ( strPathRelative[n] == '\\' )
nStart = n+1;
// if we can't replace anything... no sense in making relative because the drive letters
// must be different...
if ( nStart == 0 )
return;
// now count how many directories in the base path we have to substitute
int nBack = 0;
for ( int nDir = nStart; nDir < nLen1; nDir++ )
if ( strPathRelative[nDir] == '\\' )
nBack++;
// now build a new path by substituting different paths and appending remaining
pstr->Empty();
for ( int i = 0; i < nBack; i++ )
*pstr += "..\\";
*pstr += strOld.Right(nLen2 - nStart);
}
//
// VTSDoc::PortStatusChange
//
void VTSDoc::PortStatusChange( void )
{
if (m_pPortDlg)
m_pPortDlg->PortStatusChange();
}
//
// VTSDoc::DoSendWindow
//
extern int gSelectedGroup, gSelectedItem;
CSend * VTSDoc::DoSendWindow( int iGroup, int iItem )
{
CSend *sendp = new CSend( "Send" );
// pass the group and item through globals
gSelectedGroup = iGroup;
gSelectedItem = iItem;
// create the window and show it
// madanner 6/03, changed back to be child of main window, not the desktop. This was originally an attempt
// to satisfy feature request 444238.
// Added minimize/maximize controls, Mike Danner 2004-Jul-23
sendp->Create( AfxGetApp()->m_pMainWnd, WS_SYSMENU | WS_POPUP | WS_CAPTION | DS_MODALFRAME | WS_VISIBLE | WS_MINIMIZEBOX );
// sendp->Create( NULL, WS_OVERLAPPEDWINDOW | WS_CAPTION | WS_VISIBLE ); // this creates a window that can go behind the main window for 444238 but decided this was not what the user actually wanted and therefore was not used.
// sendp->Create(); //Make send window a client window, Xiao Shiyuan 2002-10-24
sendp->ShowWindow( SW_SHOW );
// reset the selection
gSelectedGroup = -1;
gSelectedItem = -1;
return sendp;
}
/////////////////////////////////////////////////////////////////////////////
// VTSDoc serialization
//
// Rather oddly, VTSDoc is not declared DECLARE_SERIAL/IMPLEMENT_SERIAL
// even through its members, persisted below, are.
// That means that the doc file HAS NO VERSION INFORMATION: it starts
// with our first data item.
// It also means that CArchive::GetObjectSchema/SetObjectSchema can't be used.
//
// Since the members are DECLARE_SERIAL/IMPLEMENT_SERIAL, they could have been
// simply << or >> to the archive.
// But that isn't how the first version was done. Since it would
// presumably put extra class-data in the archive, I don't see that we can
// change course now if we want to be able to load old documents.
// In our usage, I am pretty sure that the DECLARE_SERIAL/IMPLEMENT_SERIAL
// are meaningless and unnecessary, but I have left them in place cuz I am chicken.
//
// For these sad reasons, we implement versioning "by hand", and pass the
// version to member Serialize methods.
// Note that these Serialize(CArchive,UINT) methods differ from the
// virtual Serialize(CArchive)) methods that IMPLEMENT_SERIAL would use.
//
void VTSDoc::Serialize(CArchive& ar)
{
// In the original format (now called VTS_DOC_SCHEMA_1), the first thing in
// the file is the log filename.
// In later versions, the file will begin with a string that is invalid
// as a filename and which contains the schema number.
static const char versionTemplate[] = ":::new-format:::%u:::update-VTS:::";
CString str;
UINT version = VTS_DOC_SCHEMA;
if (ar.IsStoring())
{
// Turn the version into a string and store it
str.Format( versionTemplate, version );
ar << str;
// Store our class data
ar << m_strLogFilename;
}
else
{
ar >> str;
if (sscanf( str, versionTemplate, &version ) == 1)
{
if (version > VTS_DOC_SCHEMA)
{
// The file is newer than we are.
str.Format( "The file \"%s\"\n"
"is format version %u.\n"
"This version of VTS supports only versions 1 through %u.\n"
"Either update VTS to a newer version, or use \"File\", \"Workspace\"\n"
"to select or create a different workspace.",
(LPCTSTR)ar.GetFile()->GetFilePath(),
version, VTS_DOC_SCHEMA );
AfxMessageBox( str, MB_OK );
// Not really clear how to abort loading.
// If we call CArchive::Abort, the doc crashes.
return;
}
// Get the log file as the SECOND string in the file
ar >> m_strLogFilename;
}
else
{
// Assume a legacy file: initial string is the log file.
version = VTS_DOC_SCHEMA_1;
m_strLogFilename = str;
}
}
m_ports.Serialize(ar, version);
m_names.Serialize(ar, version);
m_devices.Serialize(ar, version);
m_captureFilters.Serialize(ar, version);
m_displayFilters.Serialize(ar, version);
}
/////////////////////////////////////////////////////////////////////////////
// VTSDoc diagnostics
#ifdef _DEBUG
void VTSDoc::AssertValid() const
{
CDocument::AssertValid();
}
void VTSDoc::Dump(CDumpContext& dc) const
{
CDocument::Dump(dc);
}
#endif //_DEBUG
/////////////////////////////////////////////////////////////////////////////
// VTSDoc commands
//
// VTSDoc::BindFrameContext
//
// Binding a frame context to a document is the mechanism that changes to a
// document can be forwarded to all of the views.
//
void VTSDoc::BindFrameContext( CFrameContext *pfc )
{
// make sure nobody else is using the list
m_FrameContextsCS.Lock();
// let it know its bound to this document
pfc->m_pDoc = this;
// add it to the list of other frame contexts
pfc->m_NextFrame = m_FrameContexts;
m_FrameContexts = pfc;
// initialize the frame count, such as it is. Note that this bind function
// might be called before the document is properly initialized because the
// clients are created before OnNewDocument() or OnOpenDocument() is called.
pfc->m_PacketCount = m_nPacketCount;
// release the list back to other threads
m_FrameContextsCS.Unlock();
}
//
// VTSDoc::UnbindFrameContext
//
// Remove a frame context from the documents list of contexts. This is called
// when a view goes away.
//
void VTSDoc::UnbindFrameContext( CFrameContext *pfc )
{
// make sure nobody else is using the list
m_FrameContextsCS.Lock();
// let it know its properly unbound
pfc->m_pDoc = 0;
// add it to the list of other frame contexts
for (CFrameContext **cur = &m_FrameContexts; *cur; cur = &(*cur)->m_NextFrame)
if (*cur == pfc) {
*cur = (*cur)->m_NextFrame;
break;
}
// release the list back to other threads
m_FrameContextsCS.Unlock();
}
//
// VTSDoc::SetFrameCount
//
// Tell all of the frame contexts that the frame count of the document
// has changed. The frame context will pass the message along to
// all of its associated views.
//
void VTSDoc::SetPacketCount( int count )
{
// make sure nobody else is using the list
m_FrameContextsCS.Lock();
// make sure there is really a change
if (m_nPacketCount != count)
{
// change the local copy
m_nPacketCount = count;
// tell the frame contexts that the frame count has changed
for (CFrameContext* cur = m_FrameContexts; cur; cur = cur->m_NextFrame)
cur->SetPacketCount( count );
}
// release the list back to other threads
m_FrameContextsCS.Unlock();
}
// returns index of newly added packet
// Usually called from another thread... don't do more here than write to the database
// and wake up the main thread for this document to continue processing
int VTSDoc::WritePacket( VTSPacket & pkt )
{
//If receive packets
if( (!gVTSPreferences.Setting_IsRecvPkt())
&& pkt.packetHdr.packetType == rxData)
return -1;
//If save sent packet
if( (!gVTSPreferences.Setting_IsSaveSentPkt())
&& pkt.packetHdr.packetType == txData )
return -1;
int nIndex = -1;
bool schedule = false;
m_FrameContextsCS.Lock();
// Parse the packet, both for filtering and for segmentation
VTSFilterInfo info;
info.Parse( pkt );
if (m_captureFilters.TestPacket( pkt, info )) {
// save it in the database
m_PacketDB.WritePacket(pkt);
// see if we should display the packet
if (m_displayFilters.TestPacket( pkt )) {
// have we halted packet loads?
VTSPacketPtr ppkt = NULL;
try
{
ppkt = m_fLoadPackets ? new VTSPacket() : NULL;
if ( ppkt != NULL )
{
*ppkt = pkt;
nIndex = m_apPackets.Add(ppkt);
}
}
catch(CMemoryException *e)
{
e->Delete();
if ( ppkt != NULL )
delete ppkt;
if ( m_fLoadPackets )
::PostThreadMessage( AfxGetApp()->m_nThreadID, WM_VTS_MAXPACKETS, (WPARAM) 0, (LPARAM) this );
m_fLoadPackets = false;
}
schedule = true;
}
// Process as a possible message segment
ProcessMessageSegment( pkt, info );
}
// release the list back to other threads
m_FrameContextsCS.Unlock();
// if we saved the packet, tell the main thread to update
if (schedule)
ScheduleForProcessing();
return nIndex;
}
void VTSDoc::ScheduleForProcessing()
{
// tell the application
if ( m_postMessages )
::PostThreadMessage( AfxGetApp()->m_nThreadID, WM_VTS_RCOUNT, (WPARAM) 0, (LPARAM) this );
}
int VTSDoc::GetPacketCount()
{
return m_apPackets.GetSize();
}
VTSPacketPtr VTSDoc::GetPacket( int nIndex )
{
if ( nIndex >= m_apPackets.GetSize() || nIndex < 0 )
return NULL;
return m_apPackets[nIndex];
}
//
// VTSDoc::DeletePackets
//
void VTSDoc::DeletePackets( void )
{
m_PacketDB.DeletePackets();
// make sure nobody else is using the list
m_FrameContextsCS.Lock();
DestroyPacketArray();
// make sure there is really a change
if (m_nPacketCount != 0)
{
// change the local copy
m_nPacketCount = 0;
// tell the frame contexts that the frame count has changed
for (CFrameContext* cur = m_FrameContexts; cur; cur = cur->m_NextFrame) {
cur->SetPacketCount( 0 );
cur->SetCurrentPacket( -1 );
}
}
// release the list back to other threads
m_FrameContextsCS.Unlock();
}
void VTSDoc::ReloadPacketStore( void )
{
// make sure nobody else is using the list
m_FrameContextsCS.Lock();
DestroyPacketArray();
m_nPacketCount = 0;
for (CFrameContext* cur = m_FrameContexts; cur; cur = cur->m_NextFrame)
{
cur->SetPacketCount( 0 );
cur->SetCurrentPacket( -1 );
}
LoadPacketArray();
ScheduleForProcessing();
// release the list back to other threads
m_FrameContextsCS.Unlock();
}
int VTSDoc::LoadPacketArray( void )
{
ULONGLONG tempPosition;
try
{
VTSPacketPtr ppkt = new VTSPacket();
// put everything into the packet list that matches the display filter
for ( ULONGLONG lNextPosition = 0;
ppkt != NULL && (tempPosition = m_PacketDB.ReadNextPacket(*ppkt, lNextPosition)) > lNextPosition;
lNextPosition = tempPosition )
{
if (m_displayFilters.TestPacket(*ppkt)) {
m_apPackets.Add(ppkt);
ppkt = new VTSPacket();
}
}
// Always allocated one more than we needed... so kill it
if ( ppkt != NULL )
delete ppkt;
}
catch(CMemoryException *e)
{
e->Delete();
AfxMessageBox(IDS_ERR_MAXPACKETS, MB_ICONSTOP | MB_OK);
m_fLoadPackets = false;
}
return m_apPackets.GetSize();
}
void VTSDoc::DestroyPacketArray( void )
{
// MAD_DB
// Kill all packets stored in memory
for ( int i = 0; i < m_apPackets.GetSize(); i++ )
delete m_apPackets[i];
m_apPackets.RemoveAll();
m_fLoadPackets = true; // start again if there was an error
}
// This func is called as a result of a message on this application queue... The message
// was placed there by IO threads performing a packet write through this document.
// This function performs any processing necessary when new packets come in beyond
// writing them to the database and updating this doc's packet array.
// The idea is that the main window thread takes care of this processing because of
// PreTranslateMessage... then we'll tell all the UI type CFrameContextListeners to
// deal with the addition as well.
void VTSDoc::ProcessPacketStoreChange( void )
{
// This was called because the packets in the store have changed. See if we need to
// read the rest of these things...
VTSPacketPtr ppkt = NULL;
int nNewIndex;
if(m_nPacketCount < 0) // MAG 01FEB06 this appears to somehow occasionally get corrupted, i.e. -17891602
return;
// update stats for the unread packets
// See if this update operation (catching up the views from their current packet size to
// the new packet size) will take a long time... If so (arbitrary > 200), then
// invoke the progress bar in the status bar
int nPacketCountBehind = GetPacketCount() - m_nPacketCount;
CProgressCtrl * pprogress = nPacketCountBehind > 200 ? ((CMainFrame *) AfxGetApp()->m_pMainWnd)->InitializeProgress() : NULL;
if ( pprogress != NULL )
pprogress->SetRange(0, nPacketCountBehind);
for( nNewIndex = m_nPacketCount; nNewIndex < GetPacketCount() && (ppkt = GetPacket(nNewIndex)) != NULL; nNewIndex++ )
{
if ( pprogress != NULL )
pprogress->StepIt();
BACnetPIInfo summary( true, false );
summary.Interpret( (BACnetPIInfo::ProtocolType) ppkt->packetHdr.packetProtocolID, (char *) ppkt->packetData, ppkt->packetLen );
m_pStatisticsCollector->Update(summary.summaryLine, ppkt->packetLen, ppkt->packetHdr.packetType, ppkt->packetHdr.packetProtocolID );
if ( m_bStatisticsDlgInUse && m_pStatitiscsDlg)
m_pStatitiscsDlg->Update(summary.summaryLine);
}
//OK... this doc has finished processing... now tell listening frame contexts to process as well
SetPacketCount( nNewIndex ); // index now represents count
if ( pprogress != NULL )
((CMainFrame *) AfxGetApp()->m_pMainWnd)->ReleaseProgress();
}
//This is called after all objects have loaded... We'll fixup stored names with active pointers
void VTSDoc::FixupNameToPortLinks( bool fCheckForExistingLink /* = true */ )
{
// resolve port links in name list
int i;
for ( i = 0; i < m_names.GetSize(); i++ )
{
// May have already been munged, possibly by TD redefine
// pportLink will be NULL if fixup needed, so check name for value
if ( !fCheckForExistingLink || m_names[i]->m_pportLink == NULL )
m_names[i]->m_pportLink = m_ports.Find(m_names[i]->GetPortName());
}
}
void VTSDoc::FixupPortToDeviceLinks( bool fCheckForExistingLink /* = true */ )
{
for ( int i = 0; i < m_ports.GetSize(); i++ )
{
if ( !fCheckForExistingLink || m_ports[i]->m_pdevice == NULL )
m_ports[i]->m_pdevice = m_devices.Find(m_ports[i]->GetDeviceName());
}
}
void VTSDoc::FixupFiltersToPortLinks( bool fCheckForExistingLink /* = true */ )
{
// resolve port links in name list
int i;
for ( i = 0; i < m_captureFilters.GetSize(); i++ )
{
if ( !fCheckForExistingLink || m_captureFilters[i]->m_pportLink == NULL )
m_captureFilters[i]->m_pportLink = m_ports.Find(m_captureFilters[i]->GetPortName());
}
for ( i = 0; i < m_displayFilters.GetSize(); i++ )
{
if ( !fCheckForExistingLink || m_displayFilters[i]->m_pportLink == NULL )
m_displayFilters[i]->m_pportLink = m_ports.Find(m_displayFilters[i]->GetPortName());
}
}
void VTSDoc::UnbindPortsToDevices()
{
for ( int i = 0; i < m_ports.GetSize(); i++ )
m_ports[i]->UnbindDevice();
}
void VTSDoc::BindPortsToDevices()
{
for ( int i = 0; i < m_ports.GetSize(); i++ )
m_ports[i]->BindDevice();
}
bool VTSDoc::LoadNamedAddress( BACnetAddress * pbacnetaddr, LPCSTR lpszNameLookup )
{
int i = m_names.FindIndex(lpszNameLookup);
if ( i == -1 )
return false;
*pbacnetaddr = ((VTSName *) m_names[i])->m_bacnetaddr;
return true;
}
LPCSTR VTSDoc::AddrToName( const BACnetAddress &addr, const char * pszPortName /* = NULL */ )
{
return m_names.AddrToName(addr, m_ports.Find(pszPortName));
}
// Define names linked to this port: TD, Global Broadcast, Local Broadcast
void VTSDoc::DefineNamesForPort( VTSPort * pPort, BACnetPort * pBACnetPort )
{
VTSName *pName = new VTSName("TD");
pName->m_pportLink = pPort;
pName->m_bacnetaddr = pBACnetPort->portLocalAddr;
m_names.AddUniqueName(pName);
pName = new VTSName("Global Broadcast");
pName->m_pportLink = pPort;
pName->m_bacnetaddr.GlobalBroadcast();
m_names.AddUniqueName(pName);
pName = new VTSName("Local Broadcast");
pName->m_pportLink = pPort;
pName->m_bacnetaddr.LocalBroadcast();
m_names.AddUniqueName(pName);
}
//
// VTSDoc::OnViewStatistics
//
void VTSDoc::OnViewStatistics()
{
m_bStatisticsDlgInUse=true;
VTSStatisticsDlg dlg;
m_pStatitiscsDlg=&dlg;
m_pStatitiscsDlg->m_pDoc=this;
dlg.DoModal();
m_bStatisticsDlgInUse=false;
}
/////////////////////////////////////////////////////////////////////////////
// VTSPort
const char * VTSPort::m_pszPortTypes[] = { "Null", "IP", "Ethernet", "ARCNET", "MS/TP", "PTP" };
//
// VTSPort::VTSPort
//
VTSPort::VTSPort(void)
: portSendGroup(0)
{
portDoc = (VTSDoc *) ((VTSApp *) AfxGetApp())->GetWorkspace();
m_fDirty = true;
portStatus = 0;
portStatusDesc = "New";
portEndpoint = NULL;
portFilter = NULL;
portBTR = NULL;
portBBMD = NULL;
portBIPSimple = NULL;
portBIPForeign = NULL;
portBindPoint = NULL;
m_pdevice = NULL;
m_nPortType = nullPort;
m_fEnabled = FALSE;
m_strConfigParms = _T("");
m_strName = _T("Untitled");
m_nNet = -1;
// don't worry about device... it will reattach bound by name at load and save
// not new...
}
//
// VTSPort::~VTSPort
//
VTSPort::~VTSPort( void )
{
Deactivate();
}
void VTSPort::Deactivate(void)
{
UnbindDevice();
// if there is an endpoint, delete it
if (portEndpoint)
delete portEndpoint;
// if there is a filter, delete it
if (portFilter)
delete portFilter;
// if there is a BTR, delete it
if (portBTR)
delete portBTR;
// if there is a BBMD, delete it
if (portBBMD)
delete portBBMD;
// if there is a simple BIP object, delete it
if (portBIPSimple)
delete portBIPSimple;
// if there is a foreign BIP object, delete it
if (portBIPForeign)
delete portBIPForeign;
portEndpoint = NULL;
portFilter = NULL;
portBTR = NULL;
portBBMD = NULL;
portBIPSimple = NULL;
portBIPForeign = NULL;
}
//
// VTSPort::Refresh
//
void VTSPort::Refresh( void )
{
// unbind from the device, if bound
UnbindDevice();
// shutdown the existing endpoint, if any
if (portEndpoint) {
// unbind from the filter
Unbind( portFilter, portEndpoint );
// delete the port object
delete portEndpoint;
portStatus = 3;
portStatusDesc = "Port shut down";
portEndpoint = 0;
}
// if there is a filter, delete it
if (portFilter) {
delete portFilter;
portFilter = 0;
}
// if there is a BTR, delete it
if (portBTR) {
delete portBTR;
portBTR = 0;
}
// if there is a BBMD, delete it
if (portBBMD) {
delete portBBMD;
portBBMD = 0;
}
// if there is a simple BIP object, delete it
if (portBIPSimple) {
delete portBIPSimple;
portBIPSimple = 0;
}
// if there is a foreign BIP object, delete it
if (portBIPForeign) {
delete portBIPForeign;
portBIPForeign = 0;
}
// see if the port should be enabled
if ( !m_fEnabled ) {
portStatus = 0;
portStatusDesc = "Disabled";
return;
}
// null ports cannot be enabled
if ( m_nPortType == nullPort) {
portStatus = 3;
portStatusDesc = "Null ports cannot be enabled";
return;
}
// see if a port is already active that matches this configuration
for ( int i = 0; portDoc != NULL && i < portDoc->GetPorts()->GetSize(); i++ )
{
VTSPortPtr cur = (*portDoc->GetPorts())[i];
// skip this port if it's not loaded
if ((cur->portStatus != 1) || (!cur->portEndpoint))
continue;
// skip if port types don't match
if (cur->m_nPortType != m_nPortType )
continue;
// if config strings match, flag this one
if ( cur->m_strConfigParms.CompareNoCase(m_strConfigParms) == 0 ) {
portStatus = 2;
portStatusDesc = "Existing port with this configuration";
return;
}
}
// port should be one of those listed below
portStatus = 3;
portStatusDesc = "Unknown port type";
// enable the port
switch (m_nPortType) {
case ipPort:
portStatus = 1;
portStatusDesc = "B/IP started";
portEndpoint = new VTSWinIPPort( this );
portDoc->DefineNamesForPort( this, portEndpoint );
break;
case ethernetPort:
portStatus = 1;
portStatusDesc = "Ethernet started";
portEndpoint = new VTSWinWinPcapPort( this );
portDoc->DefineNamesForPort( this, portEndpoint );
break;
case arcnetPort:
portStatusDesc = "ARCNET unsupported";
// portDoc->DefineNamesForPort( this, portEndpoint );
break;
case mstpPort:
portStatus = 2; // need yellow status because connection must be set up
portStatusDesc = "MS/TP started";
portEndpoint = new VTSWinMSTPPort( this );
portDoc->DefineNamesForPort( this, portEndpoint );
break;
case ptpPort:
portStatus = 1;
portStatusDesc = "PTP started";
portEndpoint = new VTSWinPTPPort( this );
// PTP has no address, so we don't define a Name
break;
}
// see if a filter should be set up
if (portEndpoint)
{
// create a script filter and in the darkness bind them
portFilter = new ScriptNetFilter( GetName() );
Bind( portFilter, portEndpoint );
// default bind point is the filter
portBindPoint = portFilter;
// TODO: apparently we can't do any of the portEndpoint stuff (like SENDING)
// on any Port that isn't IP?
// if this is an IP port, we have more work to do
if ( m_nPortType == ipPort )
{
int argc = 0;
char config[kVTSPortConfigLength], *src, *argv[16];
// copy the configuration, split it up
strcpy( config, m_strConfigParms );
for (src = config; *src; )
{
argv[argc++] = src;
while (*src && (*src != ','))
src++;
if (*src == ',')
*src++ = 0;
}
for (int i = argc; i < 16; i++)
argv[i] = src;
if (argc != 1)
{
int option = atoi( argv[1] );
switch (option)
{
case 0:
break;
case 1:
portBTR = new BACnetBTR();
Bind( portBTR, portFilter );
portBindPoint = portBTR;
break;
case 2:
portBBMD = new BACnetBBMD( portEndpoint->portLocalAddr );
Bind( portBBMD, portFilter );
portBindPoint = portBBMD;
break;
case 3:
portBIPSimple = new BACnetBIPSimple();
Bind( portBIPSimple, portFilter );
portBindPoint = portBIPSimple;
break;
case 4: {
unsigned long host;
unsigned short port;
int ttl;
portBIPForeign = new BACnetBIPForeign();
Bind( portBIPForeign, portFilter );
portBindPoint = portBIPForeign;
BACnetIPAddr::StringToHostPort( argv[2], &host, 0, &port );
ttl = atoi( argv[3] );
portBIPForeign->Register( host, port, ttl );
break;
}
}
}
}
}
// see if we can bind to a device
BindDevice();
SetDirty(false);
}
void VTSPort::BindDevice()
{
if ( m_pdevice != NULL )
m_pdevice->Bind(this, m_nNet);
}
void VTSPort::UnbindDevice()
{
if ( m_pdevice != NULL ) // already fixed up but not activated yet
m_pdevice->Unbind(this);
}
//
// VTSPort::SendData
//
// This is a common passthru function that allows the application to point to
// a VTSPort and gives it access to the SendData function provided by the
// endpoint (if one has been successfully established).
//
void VTSPort::SendData( BACnetOctet *data, int len )
{
if (portEndpoint)
portEndpoint->SendData( data, len );
}
const VTSPort& VTSPort::operator=(const VTSPort& rportSrc)
{
// Set dirty to false... this will only be the case if we're copying from another port
SetDirty(false);
portDoc = rportSrc.portDoc;
portStatus = rportSrc.portStatus;
portStatusDesc = rportSrc.portStatusDesc;
// don't copy the owned devices
portEndpoint = NULL; // we'll refresh all this stuff later
portFilter = NULL;
portBTR = NULL;
portBBMD = NULL;
portBIPSimple = NULL;
portBIPForeign = NULL;
portBindPoint = NULL;
m_pdevice = rportSrc.m_pdevice;
m_nPortType = rportSrc.m_nPortType;
m_fEnabled = rportSrc.m_fEnabled;
m_strConfigParms = rportSrc.m_strConfigParms;
m_strName = rportSrc.m_strName;
m_nNet = rportSrc.m_nNet;
return *this;
}
void VTSPort::SetName( LPCSTR lpszName )
{
if ( m_strName.Compare(lpszName) != 0 )
{
SetDirty();
m_strName = lpszName;
}
}
void VTSPort::SetEnabled( BOOL fEnabled /* = true */ )
{
if ( m_fEnabled != fEnabled)
{
SetDirty();
m_fEnabled = fEnabled;
}
}
void VTSPort::SetConfig( LPCSTR lpszConfig )
{
if ( m_strConfigParms.CompareNoCase(lpszConfig) != 0 )
{
SetDirty();
m_strConfigParms = lpszConfig;
}
}
void VTSPort::SetPortType( VTSPortType nType )
{
if ( m_nPortType != nType )
{
SetDirty();
m_nPortType = nType;
}
}
void VTSPort::SetNetwork( int nNetwork )
{
if ( m_nNet != nNetwork )
{
SetDirty();
m_nNet = nNetwork;
}
}
void VTSPort::SetDevice( VTSDevice * pdevice )
{
if ( m_pdevice != pdevice )
{
SetDirty();
m_pdevice = pdevice;
}
}
void VTSPort::Serialize(CArchive& ar, UINT version)
{
if (ar.IsStoring())
{
ar << m_strName;
ar << m_nPortType;
ar << m_fEnabled;
ar << m_nNet;
if ( m_pdevice == NULL )
m_strDevice.Empty();
else
m_strDevice = m_pdevice->GetName();
ar << m_strDevice;
ar << m_strConfigParms;
}
else
{
ar >> m_strName;
ar >> (int &) m_nPortType;
ar >> m_fEnabled;
ar >> m_nNet;
// just unlink (or leave unlinked) the device here... since we're loading the fixups will be done later
m_pdevice = NULL;
ar >> m_strDevice;
ar >> m_strConfigParms;
}
SetDirty(false);
}
IMPLEMENT_SERIAL(VTSPort, CObject, 1);
IMPLEMENT_VTSPTRARRAY(VTSPorts, VTSPort);
IMPLEMENT_SERIAL(VTSName, CObject, 1);
VTSName::VTSName( void )
{
m_strName = "Untitled";
m_bacnetaddr.addrType = nullAddr;
m_bacnetaddr.addrNet = 0;
m_bacnetaddr.addrLen = 0;
memset( m_bacnetaddr.addrAddr, 0, kMaxAddressLen );
m_pportLink = NULL;
}
VTSName::VTSName( LPCSTR pszname )
:m_strName(pszname)
{
m_bacnetaddr.addrType = nullAddr;
m_bacnetaddr.addrNet = 0;
m_bacnetaddr.addrLen = 0;
memset( m_bacnetaddr.addrAddr, 0, kMaxAddressLen );
m_pportLink = NULL;
}
VTSName::~VTSName( void )
{
}
const VTSName& VTSName::operator=(const VTSName& rnameSrc)
{
m_strName = rnameSrc.m_strName;
memcpy( &m_bacnetaddr, &rnameSrc.m_bacnetaddr, sizeof(m_bacnetaddr) );
m_pportLink = rnameSrc.m_pportLink;
return *this;
}
void VTSName::Serialize(CArchive& ar, UINT version)
{
if (ar.IsStoring())
{
// Switch on schema for differnent implementations during load
ar << m_strName;
try
{
ar.Write(&m_bacnetaddr, sizeof(m_bacnetaddr));
}
catch( CFileException *e )
{
e->Delete();
}
if ( m_pportLink != NULL )
m_strPortNameTemp = m_pportLink->GetName();
ar << m_strPortNameTemp;
}
else
{
ar >> m_strName;
ar.Read(&m_bacnetaddr, sizeof(m_bacnetaddr));
ar >> m_strPortNameTemp;
// This will be fixed up later...
m_pportLink = NULL;
}
}
bool VTSName::IsAddressMatch( const BACnetAddress &addr, VTSPort * pport )
{
return (m_pportLink == NULL || m_pportLink == pport) && m_bacnetaddr == addr;
}
/////////////////////////////////////////////////////////////////////////////
// VTSNames
IMPLEMENT_VTSPTRARRAY(VTSNames, VTSName);
void VTSNames::Remove( int i )
{
ASSERT(i >= 0 && i < GetSize());
if ( i >= 0 && i < GetSize() )
{
delete (VTSName *) GetAt(i);
RemoveAt(i);
}
}
LPCSTR VTSNames::AddrToName( const BACnetAddress &addr, VTSPort * pport )
{
for (int i = 0; i < GetSize(); i++)
if ( ((VTSName *) GetAt(i))->IsAddressMatch(addr, pport) )
return ((VTSName *) GetAt(i))->m_strName;
return NULL;
}
int VTSNames::FindIndex( LPCSTR lpszName )
{
for ( int i = 0; i < GetSize(); i++ )
if ( ((VTSName *) GetAt(i))->m_strName.CompareNoCase(lpszName) == 0 )
return i;
return -1;
}
// Add pName, replacing any existing VTSName with the same strName
void VTSNames::AddUniqueName( VTSName *pName )
{
int i = FindIndex(pName->m_strName);
if (i == -1)
{
Add(pName);
}
else
{
delete (VTSName *) GetAt(i);
SetAt(i, pName);
}
}
//
// SetLookupContext
//
namespace NetworkSniffer {
const char * g_pszPortName = NULL;
void SetLookupContext( const char * pszPortName )
{
// Sadly, this is a two part call. This function is called to set the name of the port
// that received a packet that is about to be picked apart by the sniffer window... it will
// call the LookupName many time. Why not just change the sniffer window? Dunno.
g_pszPortName = pszPortName;
}
//
// LookupName
//
// This function is called by the interpreters to lookup an address and see if it
// can be translated into a name. It is assumed that the global list and port
// will be set correctly before the interpreter is called.
//
const char* LookupName( int net, const BACnetOctet *addr, int len )
{
const char * pszName = NULL;
BACnetAddress bacnetAddrSearch(net, addr, len);
if ( net == 65535 )
bacnetAddrSearch.addrType = globalBroadcastAddr;
VTSDoc * pdoc = (VTSDoc * ) ((VTSApp *) AfxGetApp())->GetWorkspace();
if ( pdoc != NULL )
pszName = pdoc->AddrToName(bacnetAddrSearch, g_pszPortName);
return pszName;
}
}
/////////////////////////////////////////////////////////////////////////////
// VTSFilter
IMPLEMENT_SERIAL(VTSFilter, CObject, 1);
VTSFilter::VTSFilter( void )
{
m_type = 0;
m_addr = 0;
m_addrType = 0;
m_filteraddr.addrType = nullAddr;
m_filteraddr.addrNet = 0;
m_filteraddr.addrLen = 0;
memset( m_filteraddr.addrAddr, 0, kMaxAddressLen );
m_fnGroup = 0;
m_pportLink = NULL;
}
VTSFilter::~VTSFilter( void )
{
}
const VTSFilter& VTSFilter::operator=(const VTSFilter& rfilterSrc)
{
m_type = rfilterSrc.m_type;
m_addr = rfilterSrc.m_addr;
m_addrType = rfilterSrc.m_addrType;
memcpy( &m_filteraddr, &rfilterSrc.m_filteraddr, sizeof(m_filteraddr) );
m_fnGroup = rfilterSrc.m_fnGroup;
m_pportLink = rfilterSrc.m_pportLink;
return *this;
}
void VTSFilter::Serialize(CArchive& ar, UINT version)
{
if (ar.IsStoring())
{
ar << m_type;
if ( m_pportLink != NULL )
m_strPortNameTemp = m_pportLink->GetName();
ar << m_strPortNameTemp;
ar << m_addr;
ar << m_addrType;
try
{
ar.Write(&m_filteraddr, sizeof(m_filteraddr));
}
catch( CFileException *e )
{
e->Delete();
}
ar << m_fnGroup;
}
else
{
ar >> m_type;
ar >> m_strPortNameTemp;
ar >> m_addr;
ar >> m_addrType;
ar.Read(&m_filteraddr, sizeof(m_filteraddr));
ar >> m_fnGroup;
// This will be fixed up later...
m_pportLink = NULL;
}
}
//
// VTSFilter::TestAddress
//
bool VTSFilter::TestAddress( const BACnetAddress &addr )
{
switch (m_addrType) {
case 0:
return true;
case 1: // local station
return ((addr == m_filteraddr) ? true : false);
case 2: // local network
return (addr.addrType == localStationAddr);
case 3: // local broadcast
return (addr.addrType == localBroadcastAddr);
case 4: // remote station
return ((addr == m_filteraddr) ? true : false);
case 5: // remote network
return ((addr.addrType == remoteStationAddr) && (addr.addrNet == m_filteraddr.addrNet));
case 6: // remote broadcast
return ((addr.addrType == remoteBroadcastAddr) && (addr.addrNet == m_filteraddr.addrNet));
case 7: // global broadcast
return (addr.addrType == globalBroadcastAddr);
}
// should never get here
return false;
}
// Class to hold information parsed from a VTSPacket
// Used by filtering, and by segmented message assembly
VTSFilterInfo::VTSFilterInfo()
: m_hasSegment(false)
, m_moreFollows(false)
, m_fnGroup(0)
, m_length(0)
, m_cursor(0)
, m_service(0)
, m_sequence(0)
, m_invokeID(0)
{
}
// Parse the packet.
// Return true to bypass filtering and accept the packet.
// Return false to use the parsed-out packet information for further filtering
bool VTSFilterInfo::Parse( const VTSPacket &packet )
{
m_hasSegment = m_moreFollows = false;
// always accept script messages
if (packet.packetHdr.packetType == msgData)
return true;
m_fnGroup = 0;
m_cursor = 0;
m_length = packet.packetLen;
m_srcAddr = packet.packetHdr.packetSource;
m_destAddr = packet.packetHdr.packetDestination;
BACnetOctet *pData = packet.packetData;
// find the first octet in the packet
switch ((BACnetPIInfo::ProtocolType)packet.packetHdr.packetProtocolID)
{
case BACnetPIInfo::ipProtocol:
// skip the fake ip header, address (4), and port (2)
m_cursor += 6;
// check for a BVLL header
if (pData[ m_cursor ] == 0x81)
{
m_cursor++;
// extract the function
int bipFn = pData[ m_cursor++ ];
// extract the length
int len = pData[ m_cursor++ ];
len = (len << 8) + pData[ m_cursor++ ];
// set the function group
switch ((BVLCFunction)bipFn) {
case bvlcResult:
case blvcWriteBroadcastDistributionTable:
case blvcReadBroadcastDistributionTable:
case blvcReadBroadcastDistributionTableAck:
case bvlcRegisterForeignDevice:
case bvlcReadForeignDeviceTable:
case bvlcReadForeignDeviceTableAck:
case bvlcDeleteForeignDeviceTableEntry:
m_fnGroup = 1;
break;
case blvcForwardedNPDU:
// extract the original source
m_srcAddr.addrType = localStationAddr;
memcpy( m_srcAddr.addrAddr, &pData[ m_cursor ], 6 );
m_srcAddr.addrLen = 6;
m_cursor += 6;
break;
// dig deeper into these
case bvlcDistributeBroadcastToNetwork:
case bvlcOriginalUnicastNPDU:
case bvlcOriginalBroadcastNPDU:
break;
}
}
break;
case BACnetPIInfo::ethernetProtocol:
// skip over source (6), destination (6), length (2), and SAP (3)
m_cursor += 17;
break;
case BACnetPIInfo::arcnetProtocol:
// skip over source (1), destination (1), SAP (3), LLC (1)
m_cursor += 6;
break;
case BACnetPIInfo::mstpProtocol:
// skip over preamble
m_cursor += 2;
// look at the frame type
switch (pData[ m_cursor++ ]) {
case 0x00: // Token Frame
case 0x01: // Poll For Master Frame
case 0x02: // Reply To Poll For Master Frame
case 0x03: // Test Request Frame
case 0x04: // Test Response Frame
case 0x07: // Reply Postponed Frame
m_fnGroup = 2;
break;
case 0x05: // Data Expecting Reply Frame
case 0x06: // Data Not Expecting Reply Frame
break;
};
// Skip over destination (1), source (1), length (2) and HCRC (1)
m_cursor += 5;
break;
case BACnetPIInfo::ptpProtocol:
// ### interpreter is painful
m_fnGroup = 3;
break;
default:
// Remove the header, leaving length remaining
m_length = packet.packetLen - m_cursor;
return true;
}
// if the function group hasn't been set, dig into the NPCI header
if (m_fnGroup == 0)
{
// Remove the header, leaving length remaining
m_length = packet.packetLen - m_cursor;
if (m_length < 2)
return true; // invalid length
// Only version 1 messages supported
if (pData[ m_cursor++ ] != 0x01)
return true; // version 1 only
// Extract the flags
int netFn = pData[ m_cursor++ ];
int netLayerMessage = (netFn & 0x80);
int dnetPresent = (netFn & 0x20);
int snetPresent = (netFn & 0x08);
// expectingReply = (netFn & 0x04); // might be nice to check these someday
// networkPriority = (netFn & 0x03); // perhaps filter all critical messages?
// Extract the destination address
if (dnetPresent)
{
int dnet = pData[ m_cursor++ ];
dnet = (dnet << 8) + pData[ m_cursor++ ];
int dlen = pData[ m_cursor++ ];
if (dlen == 0) {
if (dnet == 0xFFFF)
m_destAddr.GlobalBroadcast();
else {
m_destAddr.RemoteBroadcast( dnet );
}
}
else {
m_destAddr.RemoteStation( dnet, &pData[ m_cursor ], dlen );
m_cursor += dlen;
}
}
// Extract the source address, or copy the one from the endpoint
if (snetPresent)
{
int snet = pData[ m_cursor++ ];
snet = (snet << 8) + pData[ m_cursor++ ];
int slen = pData[ m_cursor++ ];
m_srcAddr.RemoteStation( snet, &pData[ m_cursor ], slen );
m_cursor += slen;
}
// Skip the hop count
if (dnetPresent)
m_cursor += 1;
// All done for network layer messages
if (netLayerMessage)
m_fnGroup = 4;
}
if (m_fnGroup == 0)
{
int apduFn = pData[ m_cursor ];
m_pduType = (apduFn >> 4);
switch (m_pduType)
{
case confirmedRequestPDU:
m_invokeID = pData[ m_cursor + 2];
if (apduFn & 0x08)
{
m_hasSegment = true;
m_moreFollows = (apduFn & 0x04) != 0;
m_sequence = pData[ m_cursor + 3];
m_service = pData[ m_cursor + 5];
m_cursor += 6;
}
else
{
m_sequence = -1;
m_service = pData[ m_cursor + 3];
m_cursor += 4;
}
m_fnGroup = VTSFilters::ConfirmedServiceFnGroup( m_service );
break;
case unconfirmedRequestPDU:
m_service = pData[ m_cursor + 1];
m_cursor += 2;
m_fnGroup = VTSFilters::UnconfirmedServiceFnGroup( m_service );
break;
case simpleAckPDU:
m_invokeID = pData[ m_cursor + 1];
m_service = pData[ m_cursor + 2];
m_cursor += 3;
m_fnGroup = VTSFilters::ConfirmedServiceFnGroup( m_service );
break;
case complexAckPDU:
m_invokeID = pData[ m_cursor + 1];
if (apduFn & 0x08)
{
m_hasSegment = true;
m_moreFollows = (apduFn & 0x04) != 0;
m_sequence = pData[ m_cursor + 2];
m_service = pData[ m_cursor + 4];
m_cursor += 5;
}
else
{
m_sequence = -1;
m_service = pData[ m_cursor + 2];
m_cursor += 3;
}
m_fnGroup = VTSFilters::ConfirmedServiceFnGroup( m_service );
break;
case segmentAckPDU:
// Not a part of a function group
break;
case errorPDU:
m_invokeID = pData[ m_cursor + 1];
m_service = pData[ m_cursor + 2];
m_cursor += 3;
m_fnGroup = VTSFilters::ConfirmedServiceFnGroup( m_service );
break;
case rejectPDU:
case abortPDU:
m_invokeID = pData[ m_cursor + 1];
m_service = pData[ m_cursor + 2];
m_cursor += 3;
m_fnGroup = 10;
break;
}
}
// Remove the header, leaving length remaining
m_length = packet.packetLen - m_cursor;
return false;
}
/////////////////////////////////////////////////////////////////////////////
// VTSFilters
IMPLEMENT_SERIAL(VTSFilters, CPtrArray, 1);
VTSFilters::VTSFilters( void )
{
}
//
// VTSFilters::~VTSFilters
//
VTSFilters::~VTSFilters( void )
{
KillContents();
}
//
// VTSFilters::KillContents
//
void VTSFilters::KillContents( void )
{
for ( int i = 0; i < GetSize(); i++ )
if ( GetAt(i) != NULL )
delete GetAt(i);
RemoveAll();
}
//
// VTSFilters::DeepCopy
//
void VTSFilters::DeepCopy( const VTSFilters * psrc )
{
KillContents();
for ( int i = 0; i < psrc->GetSize(); i++ ) {
VTSFilter * pelement = new VTSFilter();
*pelement = *(*psrc)[i];
Add(pelement);
}
}
//
// VTSFilters::Serialize
//
void VTSFilters::Serialize( CArchive& ar, UINT version )
{
if (ar.IsStoring()) {
ar << GetSize();
for ( int i = 0; i < GetSize(); i++ )
GetAt(i)->Serialize(ar, version);
} else {
KillContents();
if (ar.IsBufferEmpty())
return;
int iSize;
for ( ar >> iSize; iSize > 0; iSize-- ) {
VTSFilter * p = new VTSFilter();
p->Serialize(ar, version);
Add(p);
}
}
}
//
// VTSFilters::Remove
//
void VTSFilters::Remove( int i )
{
ASSERT(i >= 0 && i < GetSize());
if ( i >= 0 && i < GetSize() )
{
delete (VTSFilter *) GetAt(i);
RemoveAt(i);
}
}
//
// VTSFilters::TestPacket
//
// Return true iff packet should be accepted.
//
bool VTSFilters::TestPacket( const VTSPacket& packet )
{
// accept the packet if there are no filters
if (GetSize() == 0)
return true;
VTSFilterInfo info;
return TestPacket( packet, info );
}
// This version saves a bit of time if the packet has already
// been parsed
bool VTSFilters::TestPacket( const VTSPacket& packet, VTSFilterInfo &theInfo )
{
// Accept the packet if there are no filters
if (GetSize() == 0)
return true;
// Dig into packet. (Return here means NOT an APDU)
if (theInfo.Parse( packet ))
return true;
// look through the filters
for ( int i = 0; i < GetSize(); i++ ) {
VTSFilter *fp = (VTSFilter *)GetAt(i);
// check the port
if ((strlen(fp->m_strPortNameTemp) != 0) && (strcmp(fp->m_strPortNameTemp,packet.packetHdr.m_szPortName) != 0))
continue;
// check address
if (fp->m_addr != 0) {
if (fp->m_addr == 1) {
if (!fp->TestAddress(theInfo.m_srcAddr)) // if source doesn't match, try next filter
continue;
} else
if (fp->m_addr == 2) {
if (!fp->TestAddress(theInfo.m_destAddr)) // if destination doesn't match, try next filter
continue;
} else
if (fp->m_addr == 3) {
if (fp->TestAddress(theInfo.m_srcAddr)) // if source matches, ok
;
else
if (fp->TestAddress(theInfo.m_destAddr)) // if destination matches, ok
;
else
continue; // try next filter
} else
;
}
// check function group
if (fp->m_fnGroup && (fp->m_fnGroup != theInfo.m_fnGroup))
continue;
// everything matched, accept or reject it
return ((fp->m_type == 0) ? true : false);
}
// none of the filters matched, default is accept
return true;
}
//
// VTSFilters::ConfirmedServiceFnGroup
//
int VTSFilters::ConfirmedServiceFnGroup( int service )
{
int pktFnGroup = 0
;
switch ((BACnetConfirmedServiceChoice)service) {
// Alarm and Event Services
case acknowledgeAlarm:
case confirmedCOVNotification:
case confirmedEventNotification:
case getAlarmSummary:
case getEnrollmentSummary:
case getEventInformation: //Added by Zhu Zhenhua, 2004-5-25
case subscribeCOV:
pktFnGroup = 5;
break;
// File Access Services
case atomicReadFile:
case atomicWriteFile:
pktFnGroup = 6;
break;
// Object Access Services
case addListElement:
case removeListElement:
case createObject:
case deleteObject:
case readProperty:
case readPropertyConditional:
case readPropertyMultiple:
case writeProperty:
case writePropertyMultiple:
pktFnGroup = 7;
break;
// Remote Device Management Services
case deviceCommunicationControl:
case confirmedTextMessage:
case reinitializeDevice:
pktFnGroup = 8;
break;
// Virtual Terminal Services
case vtOpen:
case vtClose:
case vtData:
pktFnGroup = 9;
break;
case confirmedPrivateTransfer:
case authenticate:
case requestKey:
// no function group for now
break;
}
return pktFnGroup;
}
//
// VTSFilters::UnconfirmedServiceFnGroup
//
int VTSFilters::UnconfirmedServiceFnGroup( int service )
{
int pktFnGroup = 0
;
switch ((BACnetUnconfirmedServiceChoice)service) {
// Alarm and Event Services
case unconfirmedCOVNotification:
case unconfirmedEventNotification:
pktFnGroup = 5;
break;
// Remote Device Management Services
case iAm:
case iHave:
case unconfirmedTextMessage:
case timeSynchronization:
case whoHas:
case whoIs:
pktFnGroup = 8;
break;
case unconfirmedPrivateTransfer:
// no function group for now
break;
}
return pktFnGroup;
}
/////////////////////////////////////////////////////////////////////////////
// VTSClient
//
// VTSClient::VTSClient
//
VTSClient::VTSClient( VTSDevicePtr dp )
: clientDev(dp), BACnetClient( &dp->devDevice )
{
}
//
// VTSClient::Confirmation
//
void VTSClient::Confirmation( const BACnetAPDU &apdu )
{
// pass it along to the executor for a match
gExecutor.ReceiveAPDU( apdu );
}
//
// VTSDevice::IAm
//
void VTSClient::IAm( void )
{
BACnetUnconfirmedServiceAPDU hereIAm( iAm );
BACnetObjectIdentifier( 8, clientDev->m_nInstance ).Encode( hereIAm );
BACnetUnsigned( clientDev->m_nMaxAPDUSize ).Encode( hereIAm );
BACnetEnumerated( clientDev->m_segmentation ).Encode( hereIAm );
BACnetUnsigned( clientDev->m_nVendorID ).Encode( hereIAm );
hereIAm.apduAddr.GlobalBroadcast();
Request( hereIAm );
}
/////////////////////////////////////////////////////////////////////////////
// VTSServer
//
// VTSServer::VTSServer
//
VTSServer::VTSServer( VTSDevicePtr dp )
: serverDev(dp), BACnetServer( &dp->devDevice )
{
}
//
// VTSServer::Indication
//
void VTSServer::Indication( const BACnetAPDU &apdu )
{
// ### log the message
// pass it along to the executor for a match
gExecutor.ReceiveAPDU( apdu );
// process it
if (apdu.apduType == unconfirmedRequestPDU) {
switch ((BACnetUnconfirmedServiceChoice)apdu.apduService) {
case whoIs:
WhoIs( apdu );
break;
case iAm:
IAm( apdu );
break;
// NOTE: if you add a service here, be sure to update the
// associated services-supported bit in VTSDevice::VTSDevice()
default:
break;
}
} else
if (apdu.apduType == confirmedRequestPDU) {
switch ((BACnetConfirmedServiceChoice)apdu.apduService) {
case readProperty:
ReadProperty( apdu );
break;
case writeProperty:
WriteProperty( apdu );
break;
case confirmedCOVNotification:
CovNotification( apdu );
break;
case getAlarmSummary:
GetAlarmSummary(apdu);
break;
case getEventInformation:
GetEventInformation(apdu);
break;
case deviceCommunicationControl:
DeviceCommunicationControl(apdu);
break;
case reinitializeDevice:
ReinitializeDevice(apdu);
break;
case confirmedEventNotification:
EventNotification(apdu);
break;
case acknowledgeAlarm:
AcknowledgeAlarm(apdu);
break;
// NOTE: if you add a service here, be sure to update the
// associated services-supported bit in VTSDevice::VTSDevice()
default:
// madanner 5/03, needs address for return
{
BACnetRejectAPDU rejectNoService(apdu.apduInvokeID, unrecognizedService);
rejectNoService.apduAddr = apdu.apduAddr;
Response(rejectNoService);
// Response( BACnetRejectAPDU( apdu.apduInvokeID, unrecognizedService ) );
}
break;
}
} else
;
}
//
// VTSServer::Response
//
// DEVICE_LOOPBACK is used to allow the developer to send requests directly to the
// internal device object. There is currently no way to log messages that the device
// object sends and receives, so responses are tossed.
//
void VTSServer::Response( const BACnetAPDU &pdu )
{
// ### log the message
// filter out null addresses
if (pdu.apduAddr.addrType == nullAddr)
return;
BACnetAppServer::Response( pdu );
}
//
// VTSServer::WhoIs
//
void VTSServer::WhoIs( const BACnetAPDU &apdu )
{
BACnetAPDUDecoder dec( apdu );
BACnetUnsigned loLimit, hiLimit;
unsigned int myInst = serverDev->m_nInstance;
try {
if (dec.pktLength != 0) {
loLimit.Decode( dec );
hiLimit.Decode( dec );
TRACE2( "WhoIs %d..%d\n", loLimit.uintValue, hiLimit.uintValue );
if ((myInst < loLimit.uintValue) || (myInst > hiLimit.uintValue))
return;
}
BACnetUnconfirmedServiceAPDU hello( iAm );
// send it to everyone
hello.apduAddr.GlobalBroadcast();
// encode the parameters
BACnetObjectIdentifier( 8, serverDev->m_nInstance ).Encode( hello );
BACnetUnsigned( serverDev->m_nMaxAPDUSize ).Encode( hello );
BACnetEnumerated( serverDev->m_segmentation ).Encode( hello );
BACnetUnsigned( serverDev->m_nVendorID ).Encode( hello );
Response( hello );
}
catch (...) {
TRACE0( "WhoIs decoding error\n" );
}
}
//
// VTSServer::IAm
//
void VTSServer::IAm( const BACnetAPDU &apdu )
{
// reserved (add to device address binding list?)
}
//
// VTSServer::ReadProperty
//
void VTSServer::ReadProperty( const BACnetAPDU &apdu )
{
BACnetAPDUDecoder dec( apdu )
;
BACnetObjectIdentifier objId
;
BACnetEnumerated propId
;
BACnetUnsigned arryIndx
;
bool gotIndex = false
;
try {
objId.Decode( dec );
propId.Decode( dec );
if (dec.pktLength != 0) {
gotIndex = true;
arryIndx.Decode( dec );
}
TRACE( "ReadProperty %d-%d, %d, %d\n",
objId.GetObjectType(), objId.GetObjectInstance(),
propId.m_enumValue, arryIndx.uintValue );
// build an ack
BACnetComplexAckAPDU ack( readProperty, apdu.apduInvokeID );
// send the response back to where the request came from
ack.apduAddr = apdu.apduAddr;
// encode the properties from the request
objId.Encode( ack, 0 );
propId.Encode( ack, 1 );
if (gotIndex)
arryIndx.Encode( ack, 2 );
// encode the result
BACnetOpeningTag().Encode( ack, 3 );
/* MAD_DB Find proper object/property/value
serverDev->devObjPropValueList->Encode( objId.objID, propId.m_enumValue
, (gotIndex ? arryIndx.uintValue : -1)
, ack
);
*/
// I'm not sure how this hooks up to the device... Just go with it.
int nErr = serverDev->ReadProperty(&objId, &propId, gotIndex ? arryIndx.uintValue : -1, &ack );
if ( nErr != 0 )
throw(nErr);
BACnetClosingTag().Encode( ack, 3 );
// send it
Response( ack );
}
catch (int errCode) {
TRACE1( "ReadProperty execution error - %d\n", errCode );
BACnetErrorAPDU error( readProperty, apdu.apduInvokeID );
error.apduAddr = apdu.apduAddr;
// encode the Error Class
if ((errCode == 2) || (errCode == 25)) // configuration-in-progress, operational-problem
BACnetEnumerated( 0 ).Encode( error ); // DEVICE
else
if (errCode == 42 || errCode == 32) // invalid-array-index or unknown-property
BACnetEnumerated( 2 ).Encode( error ); // PROPERTY
else
BACnetEnumerated( 1 ).Encode( error ); // OBJECT
// encode the Error Code
BACnetEnumerated( errCode ).Encode( error );
Response( error );
}
catch (...) {
TRACE0( "ReadProperty execution error\n" );
BACnetRejectAPDU goAway( apdu.apduInvokeID, otherReject );
goAway.apduAddr = apdu.apduAddr;
Response( goAway );
}
}
void VTSServer::CovNotification( const BACnetAPDU &apdu )
{
BACnetAPDUTag t ;
BACnetAPDUDecoder dec( apdu ) ;
BACnetObjectIdentifier objId ;
BACnetEnumerated propId ;
BACnetUnsigned arryIndx ;
bool gotIndex = false ;
try {
// todo: need to decode the COVNotification packet to ensure it
// is encoded correctly and then perform any functions we might
// need to do. Then send the simpleAck. Currently we just send
// the simpleAck.
// objId.Decode( dec );
// propId.Decode( dec );
// look at the next tag
// dec.ExamineTag( t );
// if ((t.tagClass == contextTagClass) && (t.tagNumber == 2)) {
// gotIndex = true;
// arryIndx.Decode( dec );
// look at the next tag
// dec.ExamineTag( t );
// }
// TRACE3( "confirmedCOVNotification %d, %d, %d\n", objId.objID, propId.m_enumValue, arryIndx.uintValue );
// build an ack
BACnetSimpleAckAPDU ack( confirmedCOVNotification, apdu.apduInvokeID );
// send the response back to where the request came from
ack.apduAddr = apdu.apduAddr;
// make sure we have an opening tag
// if ((t.tagClass == openingTagClass) && (t.tagNumber == 3)) {
// remove it from the decoder
// BACnetOpeningTag().Decode( dec );
// } else
// throw (invalidTagReject);
// decode the contents
// look at the next tag
// dec.ExamineTag( t );
// make sure it's a closing tag
// if ((t.tagClass == closingTagClass) && (t.tagNumber == 3)) {
// remove it from the decoder
// BACnetClosingTag().Decode( dec );
// } else
// throw (invalidTagReject);
// send it
Response( ack );
}
catch (int errCode) {
TRACE1( "confirmedCOVNotification execution error - %d\n", errCode );
BACnetErrorAPDU error( confirmedCOVNotification, apdu.apduInvokeID );
error.apduAddr = apdu.apduAddr;
// encode the Error Class
if ((errCode == 2) || (errCode == 25)) // configuration-in-progress, operational-problem
BACnetEnumerated( 0 ).Encode( error ); // DEVICE
else
if (errCode == 42) // invalid-array-index
BACnetEnumerated( 2 ).Encode( error ); // PROPERTY
else
BACnetEnumerated( 1 ).Encode( error ); // OBJECT
// encode the Error Code
BACnetEnumerated( errCode ).Encode( error );
Response( error );
}
catch (BACnetRejectReason rr) {
TRACE0( "confirmedCOVNotification execution error\n" );
BACnetRejectAPDU goAway( apdu.apduInvokeID, rr );
goAway.apduAddr = apdu.apduAddr;
Response( goAway );
}
catch (...) {
TRACE0( "confirmedCOVNotification execution error\n" );
BACnetRejectAPDU goAway( apdu.apduInvokeID, otherReject );
goAway.apduAddr = apdu.apduAddr;
Response( goAway );
}
}
//
// VTSServer::WriteProperty
//
void VTSServer::WriteProperty( const BACnetAPDU &apdu )
{
BACnetAPDUTag t
;
BACnetAPDUDecoder dec( apdu )
;
BACnetObjectIdentifier objId
;
BACnetEnumerated propId
;
BACnetUnsigned arryIndx
;
bool gotIndex = false
;
try {
objId.Decode( dec );
propId.Decode( dec );
// look at the next tag
dec.ExamineTag( t );
if ((t.tagClass == contextTagClass) && (t.tagNumber == 2)) {
gotIndex = true;
arryIndx.Decode( dec );
// look at the next tag
dec.ExamineTag( t );
}
TRACE( "WriteProperty %d-%d, %d, %d\n",
objId.GetObjectType(), objId.GetObjectInstance(),
propId.m_enumValue, arryIndx.uintValue );
// build an ack
BACnetSimpleAckAPDU ack( writeProperty, apdu.apduInvokeID );
// send the response back to where the request came from
ack.apduAddr = apdu.apduAddr;
// make sure we have an opening tag
if ((t.tagClass == openingTagClass) && (t.tagNumber == 3)) {
// remove it from the decoder
BACnetOpeningTag().Decode( dec );
} else
throw (invalidTagReject);
// decode the contents
/* MAD_DB
serverDev->devObjPropValueList->Decode( objId.objID, propId.m_enumValue
, (gotIndex ? arryIndx.uintValue : -1)
, dec
);
*/
int nErr = serverDev->WriteProperty( &objId, &propId, gotIndex ? arryIndx.uintValue : -1, &dec );
if ( nErr != 0 )
throw(nErr);
// look at the next tag
dec.ExamineTag( t );
// make sure it's a closing tag
if ((t.tagClass == closingTagClass) && (t.tagNumber == 3)) {
// remove it from the decoder
BACnetClosingTag().Decode( dec );
} else
throw (invalidTagReject);
// send it
Response( ack );
}
catch (int errCode) {
TRACE1( "WriteProperty execution error - %d\n", errCode );
BACnetErrorAPDU error( writeProperty, apdu.apduInvokeID );
error.apduAddr = apdu.apduAddr;
// encode the Error Class
if ((errCode == 2) || (errCode == 25)) // configuration-in-progress, operational-problem
BACnetEnumerated( 0 ).Encode( error ); // DEVICE
else
if (errCode == 42) // invalid-array-index
BACnetEnumerated( 2 ).Encode( error ); // PROPERTY
else
BACnetEnumerated( 1 ).Encode( error ); // OBJECT
// encode the Error Code
BACnetEnumerated( errCode ).Encode( error );
Response( error );
}
catch (BACnetRejectReason rr) {
TRACE0( "WriteProperty execution error\n" );
BACnetRejectAPDU goAway( apdu.apduInvokeID, rr );
goAway.apduAddr = apdu.apduAddr;
Response( goAway );
}
catch (...) {
TRACE0( "WriteProperty execution error\n" );
BACnetRejectAPDU goAway( apdu.apduInvokeID, otherReject );
goAway.apduAddr = apdu.apduAddr;
Response( goAway );
}
}
void VTSServer::GetAlarmSummary( const BACnetAPDU &apdu )
{
BACnetAPDUTag t ;
BACnetAPDUDecoder dec( apdu ) ;
BACnetObjectIdentifier objId;
BACnetEnumerated alarmState;
BACnetBitString acknowledgedTransitions(3);
bool gotIndex = false ;
try {
// TRACE3( "getAlarmSummary \n");
// build an ack
BACnetComplexAckAPDU ack( getAlarmSummary, apdu.apduInvokeID );
// send the response back to where the request came from
ack.apduAddr = apdu.apduAddr;
for ( int i = 0; i < serverDev->m_nEvents; i++ )
{
// encode the properties from the request
objId.SetValue( OBJ_ANALOG_OUTPUT, i );
objId.Encode( ack );
alarmState.Encode( ack );
acknowledgedTransitions.Encode( ack );
}
// send it
Response( ack );
}
catch (BACnetRejectReason rr) {
TRACE0( "getAlarmSummary execution error\n" );
BACnetRejectAPDU goAway( apdu.apduInvokeID, rr );
goAway.apduAddr = apdu.apduAddr;
Response( goAway );
}
catch (...) {
TRACE0( "getAlarmSummary execution error\n" );
BACnetRejectAPDU goAway( apdu.apduInvokeID, otherReject );
goAway.apduAddr = apdu.apduAddr;
Response( goAway );
}
}
void VTSServer::GetEventInformation( const BACnetAPDU &apdu )
{
BACnetAPDUTag t ;
BACnetAPDUDecoder dec( apdu ) ;
BACnetBoolean moreEvents;
BACnetOpeningTag openT;
BACnetClosingTag closeT;
BACnetObjectIdentifier objId;
BACnetEnumerated eventState;
BACnetBitString acknowledgedTransitions(3);
BACnetEnumerated notifyType;
BACnetBitString eventEnable(3);
unsigned short priorities[3] = { 0,0,0};
BACnetUnsignedArray eventPriorities( priorities, 3);
BACnetTimeStampArray eventTimeStamps;
try {
// TRACE3( "getEventInformation \n");
// Decode the requested objid if supplied
// look at the next tag
if ( dec.pktLength > 0 )
{
dec.ExamineTag( t );
if ((t.tagClass == contextTagClass) && (t.tagNumber == 0))
{
objId.Decode( dec );
}
}
// build an ack
BACnetComplexAckAPDU ack( getEventInformation, apdu.apduInvokeID );
// send the response back to where the request came from
ack.apduAddr = apdu.apduAddr;
if ( serverDev->m_nEvents > 0 )
{
openT.Encode(ack, 0);
// todo: encode 1 event
objId.Encode( ack, 0 );
eventState.Encode( ack, 1 );
acknowledgedTransitions.Encode( ack, 2 );
eventTimeStamps.Add( new ::BACnetTimeStamp(new BACnetUnsigned(serverDev->m_nEvents)));
eventTimeStamps.Add( new ::BACnetTimeStamp(new BACnetUnsigned(0)));
eventTimeStamps.Add( new ::BACnetTimeStamp(new BACnetUnsigned(0)));
eventTimeStamps.Encode( ack, 3);
notifyType.Encode( ack, 4);
eventEnable.Encode( ack, 5);
eventPriorities.Encode( ack, 6);
closeT.Encode(ack, 0);
serverDev->m_nEvents--;
moreEvents = (serverDev->m_nEvents > 0 ? true : false);
moreEvents.Encode(ack, 1);
}
else
{
openT.Encode(ack, 0); // encode empty results
closeT.Encode(ack, 0);
moreEvents = false;
moreEvents.Encode(ack, 1);
}
// send it
Response( ack );
}
catch (BACnetRejectReason rr) {
TRACE0( "getEventInformation execution error\n" );
BACnetRejectAPDU goAway( apdu.apduInvokeID, rr );
goAway.apduAddr = apdu.apduAddr;
Response( goAway );
}
catch (...) {
TRACE0( "getEventInformation execution error\n" );
BACnetRejectAPDU goAway( apdu.apduInvokeID, otherReject );
goAway.apduAddr = apdu.apduAddr;
Response( goAway );
}
}
void VTSServer::ReinitializeDevice( const BACnetAPDU &apdu)
{
BACnetAPDUTag t ;
BACnetAPDUDecoder dec( apdu ) ;
BACnetEnumerated stateOfDevice;
BACnetCharacterString password;
try {
password.SetValue("");
stateOfDevice.Decode( dec );
if ( dec.pktLength > 0 )
{
// look at the next tag
dec.ExamineTag( t );
if ((t.tagClass == contextTagClass) && (t.tagNumber == 1))
{
password.Decode( dec );
}
}
// TODO: We should actually do something with this information.
// TRACE3( "reinitializeDevice %d, %s\n", stateOfDevice.m_enumValue, password );
// build an ack
BACnetSimpleAckAPDU ack( reinitializeDevice, apdu.apduInvokeID );
// send the response back to where the request came from
ack.apduAddr = apdu.apduAddr;
// send it
Response( ack );
}
catch (BACnetRejectReason rr) {
TRACE0( "reinitializeDevice execution error\n" );
BACnetRejectAPDU goAway( apdu.apduInvokeID, rr );
goAway.apduAddr = apdu.apduAddr;
Response( goAway );
}
catch (...) {
TRACE0( "reinitializeDevice execution error\n" );
BACnetRejectAPDU goAway( apdu.apduInvokeID, otherReject );
goAway.apduAddr = apdu.apduAddr;
Response( goAway );
}
}
void VTSServer::DeviceCommunicationControl( const BACnetAPDU &apdu )
{
BACnetAPDUTag t ;
BACnetAPDUDecoder dec( apdu ) ;
BACnetUnsigned timeDur;
BACnetEnumerated enableDisable;
BACnetCharacterString password;
try {
password.SetValue("");
// look at the next tag
dec.ExamineTag( t );
if ((t.tagClass == contextTagClass) && (t.tagNumber == 0))
{
timeDur.Decode( dec );
}
enableDisable.Decode( dec );
if ( dec.pktLength > 0 )
{
// look at the next tag
dec.ExamineTag( t );
if ((t.tagClass == contextTagClass) && (t.tagNumber == 2))
{
password.Decode( dec );
}
}
// TODO: We should actually do something with this information.
// TRACE3( "deviceCommunicationControl %d, %d, %d\n", timeDur.uintValue, enableDisable.m_enumValue, password );
// build an ack
BACnetSimpleAckAPDU ack( deviceCommunicationControl, apdu.apduInvokeID );
// send the response back to where the request came from
ack.apduAddr = apdu.apduAddr;
// send it
Response( ack );
}
catch (BACnetRejectReason rr) {
TRACE0( "deviceCommunicationControl execution error\n" );
BACnetRejectAPDU goAway( apdu.apduInvokeID, rr );
goAway.apduAddr = apdu.apduAddr;
Response( goAway );
}
catch (...) {
TRACE0( "deviceCommunicationControl execution error\n" );
BACnetRejectAPDU goAway( apdu.apduInvokeID, otherReject );
goAway.apduAddr = apdu.apduAddr;
Response( goAway );
}
}
void VTSServer::AcknowledgeAlarm( const BACnetAPDU &apdu )
{
BACnetAPDUTag t ;
BACnetAPDUDecoder dec( apdu ) ;
BACnetUnsigned ack_pid;
BACnetObjectIdentifier eventObjId;
BACnetEnumerated eventState;
BACnetTimeStamp timeStamp;
BACnetCharacterString ackSource;
BACnetTimeStamp ackTime;
try {
ack_pid.Decode( dec );
eventObjId.Decode( dec );
eventState.Decode( dec );
// timeStamp.Decode( dec );
// ackSource.Decode( dec );
// ackTime.Decode( dec );
// TODO: someday do something with this information
// TRACE3( "acknowledgeAlarm %d, %d, %d\n", ack_pid.uintValue, eventObjId.objID, eventState.m_enumValue);
// build an ack
BACnetSimpleAckAPDU ack( acknowledgeAlarm, apdu.apduInvokeID );
// send the response back to where the request came from
ack.apduAddr = apdu.apduAddr;
// send it
Response( ack );
}
catch (BACnetRejectReason rr) {
TRACE0( "confirmedCOVNotification execution error\n" );
BACnetRejectAPDU goAway( apdu.apduInvokeID, rr );
goAway.apduAddr = apdu.apduAddr;
Response( goAway );
}
catch (...) {
TRACE0( "confirmedCOVNotification execution error\n" );
BACnetRejectAPDU goAway( apdu.apduInvokeID, otherReject );
goAway.apduAddr = apdu.apduAddr;
Response( goAway );
}
}
void VTSServer::EventNotification( const BACnetAPDU &apdu )
{
BACnetAPDUTag t ;
BACnetAPDUDecoder dec( apdu ) ;
BACnetObjectIdentifier objId ;
BACnetEnumerated propId ;
BACnetUnsigned arryIndx ;
bool gotIndex = false ;
try {
// todo: need to decode the EventNotification packet to ensure it
// is encoded correctly and then perform any functions we might
// need to do. Then send the simpleAck. Currently we just send
// the simpleAck.
// objId.Decode( dec );
// propId.Decode( dec );
// look at the next tag
// dec.ExamineTag( t );
// if ((t.tagClass == contextTagClass) && (t.tagNumber == 2)) {
// gotIndex = true;
// arryIndx.Decode( dec );
// look at the next tag
// dec.ExamineTag( t );
// }
// TRACE3( "EventNotification %d, %d, %d\n", objId.objID, propId.m_enumValue, arryIndx.uintValue );
// build an ack
BACnetSimpleAckAPDU ack( confirmedEventNotification, apdu.apduInvokeID );
// send the response back to where the request came from
ack.apduAddr = apdu.apduAddr;
// send it
Response( ack );
}
catch (BACnetRejectReason rr) {
TRACE0( "confirmedCOVNotification execution error\n" );
BACnetRejectAPDU goAway( apdu.apduInvokeID, rr );
goAway.apduAddr = apdu.apduAddr;
Response( goAway );
}
catch (...) {
TRACE0( "confirmedCOVNotification execution error\n" );
BACnetRejectAPDU goAway( apdu.apduInvokeID, otherReject );
goAway.apduAddr = apdu.apduAddr;
Response( goAway );
}
}
/////////////////////////////////////////////////////////////////////////////
// VTSDevice
//MAD_DB no need to create a global list because multiple documents for config are history...
//VTSDeviceList gMasterDeviceList;
//
// VTSDevice::VTSDevice
//
IMPLEMENT_SERIAL(VTSDevice, CObject, 1);
#pragma warning( disable : 4355 )
VTSDevice::VTSDevice()
: devClient(this), devServer(this)
{
// These member variables were introduced in version 1.5.
// They are almost all DUPLICATES of members of members of BACnetDevice
// and BACnetDeviceInfo, and THOSE are the values actually USED when
// sending and receiving.
// Between versions 1.5 and 3.5.3 inclusive, the m_ members are:
// - editable in the Device dialog
// - saved to disk in the Serialize methods
// - accessible via InternalReadProperty and InternalWriteProperty
// - used in WhoIs and IAm processing
// - NOT USED IN ANY COMMUNICATIONS
//
// This makes NO sense to me, as it means that there is no way to
// adjust the parameters when the device is used for communications.
//
// Rather than back out the redundant variables, I have added CopyToLive(),
// called as appropriate during creation and update.
m_strName = "Untitled";
m_nInstance = 0;
m_fRouter = FALSE;
m_segmentation = noSegmentation;
m_nSegmentSize = 1024;
m_nWindowSize = 1;
m_nMaxAPDUSize = 1024;
m_nNextInvokeID = 0;
m_nAPDUTimeout = 5000;
m_nAPDUSegmentTimeout = 1000;
m_nAPDURetries = 3;
m_nVendorID = kVendorID; // BACnet Stack at SourceForge
m_nEvents = 3;
m_services_supported = BACnetBitString(40);
// Set basic services supported
m_services_supported.SetBit(0); // acknowledgeAlarm
m_services_supported.SetBit(1); // confirmedCOVNotification
m_services_supported.SetBit(2); // confirmedEventNotification
m_services_supported.SetBit(3); // getAlarmSummary
m_services_supported.SetBit(12); // readProperty,
// m_services_supported.SetBit(14); // readPropertyMultiple -- Does not really support!!!!
m_services_supported.SetBit(15); // writeProperty,
m_services_supported.SetBit(17); // deviceCommunicationControl
m_services_supported.SetBit(20); // reinitializeDevice
m_services_supported.SetBit(26); // i-am
m_services_supported.SetBit(34); // who-is
m_services_supported.SetBit(39); // getEventInformation
m_nMaxSegs = 0;
devPort = NULL;
devPortEndpoint = NULL;
//MAD_DB devObjPropValueList = NULL;
// Copy to live objects
CopyToLive();
}
// Copy data to live device
void VTSDevice::CopyToLive()
{
// BACnetDevice members
devDevice.deviceAPDUTimeout = m_nAPDUTimeout;
devDevice.deviceAPDUSegmentTimeout = m_nAPDUSegmentTimeout;
devDevice.deviceAPDURetries = m_nAPDURetries;
devDevice.deviceInst = m_nInstance;
devDevice.deviceSegmentation = (BACnetSegmentation)m_segmentation;
devDevice.deviceSegmentSize = m_nSegmentSize;
devDevice.deviceWindowSize = m_nWindowSize;
devDevice.deviceMaxAPDUSize = m_nMaxAPDUSize;
devDevice.deviceNextInvokeID = m_nNextInvokeID;
// devDevice.deviceVendorID = m_nVendorID;
devDevice.deviceMaxSegs = m_nMaxSegs;
// BACnetRouter devRouter;
// This is never set, and seems not to be used
// ? = m_fRouter;
}
void VTSDevice::Activate()
{
// bind the device to the router (global Bind(), not our local one)
::Bind( &devDevice, &devRouter );
// create a dummy port
devPort = new VTSPort();
// the port name matches the device name
devPort->SetName(GetName());
// create a funny endpoint that redirects requests back to this device
devPortEndpoint = new VTSDevicePort( devPort, this );
}
void VTSDevice::Deactivate()
{
// Don't need to kill this object, the created port object will destroy
// the endpoint...
// if ( devPortEndpoint != NULL )
// delete devPortEndpoint;
devPortEndpoint = NULL;
if ( devPort != NULL )
delete devPort;
devPort = NULL;
}
#pragma warning( default : 4355 )
//
// VTSDevice::~VTSDevice
//
VTSDevice::~VTSDevice( void )
{
// remove this from the master list
//MAD_DB RemoveFromMasterList();
Deactivate();
// delete the dummy port which will also delete the endpoint
if ( devPort != NULL )
delete devPort;
// toss the object, properties and values manager
// Already handled by destructor for propery values arrays
// if ( devObjPropValueList != NULL )
// delete devObjPropValueList;
}
//
// VTSDevice::Bind
//
// A binding operation is pretty simple, just pass the request along
// to the built-in router.
//
void VTSDevice::Bind( VTSPortPtr pp, int net )
{
// Submitted by: Alan.Wood@nz.schneider-electric.com
if(pp->portEndpoint == NULL || pp->portBindPoint == NULL)
return; // port not set-up completely yet
devRouter.BindToEndpoint( pp->portBindPoint, net );
//madanner 5/03, uncommented SetLocaAddress to enable device RP/WP system
devRouter.SetLocalAddress( net, pp->portEndpoint->portLocalAddr );
}
//
// VTSDevice::Unbind
//
void VTSDevice::Unbind( VTSPortPtr pp )
{
devRouter.UnbindFromEndpoint( pp->portBindPoint );
}
//
// VTSDevice::IAm
//
void VTSDevice::IAm( void )
{
devClient.IAm();
}
//
// VTSDevice::SendAPDU
//
void VTSDevice::SendAPDU( const BACnetAPDU &apdu )
{
bool asClient;
switch (apdu.apduType) {
case confirmedRequestPDU:
case unconfirmedRequestPDU:
asClient = true;
break;
case simpleAckPDU:
case complexAckPDU:
asClient = false;
break;
case segmentAckPDU:
asClient = (apdu.apduSrv == 0);
break;
case errorPDU:
case rejectPDU:
asClient = false;
break;
case abortPDU:
asClient = (apdu.apduSrv == 0);
break;
}
try {
#if DEVICE_LOOPBACK
// null address is like a loopback
if (apdu.apduAddr.addrType == nullAddr) {
if (asClient)
devServer.Indication( apdu );
else
devClient.Confirmation( apdu );
} else
#endif
if (asClient)
devClient.Request( apdu );
else
devServer.Response( apdu );
}
catch (...) {
TRACE0( "---------- Something went wrong ----------\n" );
}
}
void VTSDevice::Serialize(CArchive& ar, UINT version)
{
if (ar.IsLoading())
{
// VTS_DOC_SCHEMA_1 and VTS_DOC_SCHEMA_2 data
ar >> m_strName;
ar >> m_nInstance;
ar >> m_fRouter;
int n;
ar >> n;
m_segmentation = (BACnetSegmentation) n;
ar >> m_nSegmentSize;
ar >> m_nWindowSize;
ar >> m_nMaxAPDUSize;
ar >> m_nNextInvokeID;
ar >> m_nAPDUTimeout;
ar >> m_nAPDUSegmentTimeout;
ar >> m_nAPDURetries;
ar >> m_nVendorID;
if (version >= VTS_DOC_SCHEMA_2)
{
// Can't serialize directly Read CString and get array of chars then encode into BitString
CString tmp;
ar >> tmp;
m_services_supported.Decode( tmp );
tmp = m_services_supported.ToString();
ar >> m_nEvents;
ar >> m_nMaxSegs;
}
}
else
{
// VTS_DOC_SCHEMA_1 and VTS_DOC_SCHEMA_2 data
ar << m_strName;
ar << m_nInstance;
ar << m_fRouter;
ar << m_segmentation;
ar << m_nSegmentSize;
ar << m_nWindowSize;
ar << m_nMaxAPDUSize;
ar << m_nNextInvokeID;
ar << m_nAPDUTimeout;
ar << m_nAPDUSegmentTimeout;
ar << m_nAPDURetries;
ar << m_nVendorID;
// VTS_DOC_SCHEMA_2 data
CString dec;
m_services_supported.Encode( dec, BACnetEncodeable::FMT_EPICS );
ar << dec;
ar << m_nEvents;
ar << m_nMaxSegs;
}
// Copy to live objects
CopyToLive();
m_devobjects.Serialize(ar,version);
}
CString VTSDevice::GetDescription(void)
{
CString strInstance;
strInstance.Format("%s, %d", GetName(), m_nInstance);
return strInstance;
}
// First look for supported object in our array
VTSDevObject * VTSDevice::FindObject( unsigned int nObjID )
{
for (int i = 0; i < m_devobjects.GetSize(); i++ )
if ( m_devobjects[i]->GetID() == nObjID )
return m_devobjects[i];
return NULL;
}
VTSDevProperty * VTSDevice::FindProperty( VTSDevObject * pobject, int nPropID )
{
for ( int i = 0; pobject != NULL && i < pobject->GetProperties()->GetSize(); i++ )
if ( (*pobject->GetProperties())[i]->GetID() == nPropID )
return (*pobject->GetProperties())[i];
return NULL;
}
int VTSDevice :: InternalReadProperty( BACnetObjectIdentifier * pbacnetobjectid, BACnetEnumerated * pbacnetpropid, BACnetAPDUEncoder * pAPDUEncoder, int index )
{
BACnetObjectIdentifier bacnetobjidThis(8, m_nInstance);
if ( pbacnetobjectid->objID != bacnetobjidThis.objID )
return 31; // object not found
switch( pbacnetpropid->m_enumValue )
{
case OBJECT_IDENTIFIER:
{
BACnetObjectIdentifier me;
me.SetValue( OBJ_DEVICE, m_nInstance );
me.Encode(*pAPDUEncoder);
}
break;
case OBJECT_TYPE:
{
BACnetEnumerated(8).Encode(*pAPDUEncoder);
}
break;
case OBJECT_NAME:
{
BACnetCharacterString(m_strName).Encode(*pAPDUEncoder);
}
break;
case SYSTEM_STATUS:
BACnetEnumerated(0).Encode(*pAPDUEncoder);
break;
case VENDOR_NAME:
{
CString tmp = "Vendor Name"; //BACnetVendorID[m_nVendorID];
if (tmp == "")
tmp = "Unknown Vendor";
BACnetCharacterString(tmp).Encode(*pAPDUEncoder);
}
break;
case VENDOR_IDENTIFIER:
{
BACnetUnsigned(m_nVendorID).Encode( *pAPDUEncoder );
}
break;
case MODEL_NAME:
{
BACnetCharacterString(m_strName).Encode(*pAPDUEncoder);
}
break;
case FIRMWARE_REVISION:
{
BACnetCharacterString("1.0").Encode(*pAPDUEncoder);
}
break;
case APPLICATION_SOFTWARE_VERSION:
{
BACnetCharacterString("1.0").Encode(*pAPDUEncoder);
}
break;
case PROTOCOL_VERSION:
BACnetUnsigned(1).Encode(*pAPDUEncoder);
break;
case PROTOCOL_REVISION:
BACnetUnsigned(7).Encode(*pAPDUEncoder);
break;
case PROTOCOL_SERVICES_SUPPORTED:
{
// set on device creation and can be modified through device dlg.
m_services_supported.Encode(*pAPDUEncoder);
}
break;
case PROTOCOL_OBJECT_TYPES_SUPPORTED:
{
// run through m_devobjects to see which objects are defined
BACnetBitString objects_supported = BACnetBitString(25);
for(int i = 0; i < m_devobjects.GetSize(); i++)
{
unsigned int objid = m_devobjects[i]->GetID();
int objtype=(word)(objid>>22);
objects_supported.SetBit(objtype);
}
objects_supported.SetBit(8); // always support DEVICE type object
objects_supported.Encode(*pAPDUEncoder);
}
break;
case OBJECT_LIST:
{
if (index == 0)
{
BACnetUnsigned val;
val = m_devobjects.GetSize()+1; // have to add one for the Device object
val.Encode(*pAPDUEncoder);
}
else if (index > 0)
{
BACnetArrayOf<BACnetObjectIdentifier> objList;
if ( (index-1) > (m_devobjects.GetSize()+1) )
{
return 42; // invalid-array-index
}
else if ((index-1) == m_devobjects.GetSize()) // special case: return device
{
BACnetObjectIdentifier me;
me.SetValue( OBJ_DEVICE, m_nInstance );
objList.AddElement(&me); // add device object
objList.Encode(*pAPDUEncoder);
}
else
{
BACnetObjectIdentifier objID;
unsigned int objid = m_devobjects[index-1]->GetID(); // remember index is 1 based our array is 0 based
int inst = objid & 0x003fffff ;
int objtype=(word)(objid>>22);
objID.SetValue( (BACnetObjectType)objtype, inst );
objList.AddElement(&objID);
objList.Encode(*pAPDUEncoder);
}
}
else
{
BACnetArrayOf<BACnetObjectIdentifier> objList;
for(int i = 0; i < m_devobjects.GetSize(); i++)
{
BACnetObjectIdentifier objID;
unsigned int objid = m_devobjects[i]->GetID();
int inst = objid & 0x003fffff ;
int objtype=(word)(objid>>22);
objID.SetValue( (BACnetObjectType)objtype, inst );
objList.AddElement(&objID);
}
BACnetObjectIdentifier me;
me.SetValue( OBJ_DEVICE, m_nInstance );
objList.AddElement(&me); // add device object
objList.Encode(*pAPDUEncoder);
}
}
break;
case MAX_APDU_LENGTH_ACCEPTED:
{
BACnetUnsigned(m_nMaxAPDUSize).Encode( *pAPDUEncoder );
}
break;
case SEGMENTATION_SUPPORTED:
{
BACnetUnsigned((int) m_segmentation).Encode( *pAPDUEncoder );
}
break;
case NUMBER_OF_APDU_RETRIES:
{
BACnetUnsigned(m_nAPDURetries).Encode( *pAPDUEncoder );
}
break;
case DEVICE_ADDRESS_BINDING:
{
//BACnetAddressBinding( unsigned int nobjID, unsigned short nNet, BACnetOctet * paMAC, unsigned short nMACLen );
}
break;
case DATABASE_REVISION:
{
BACnetUnsigned(20).Encode(*pAPDUEncoder);
}
break;
// optional properties supported
case LOCAL_DATE:
{
BACnetDate().Encode( *pAPDUEncoder );
}
break;
case LOCAL_TIME:
{
BACnetTime().Encode( *pAPDUEncoder );
}
break;
case APDU_TIMEOUT:
{
BACnetUnsigned(m_nAPDUTimeout).Encode( *pAPDUEncoder );
}
break;
case APDU_SEGMENT_TIMEOUT:
{
BACnetUnsigned(m_nAPDUSegmentTimeout).Encode( *pAPDUEncoder );
}
break;
case MAX_SEGMENTS_ACCEPTED:
{
BACnetUnsigned(m_nMaxSegs).Encode( *pAPDUEncoder );
}
break;
// might be nice to support others implicitly with device declaration...
default:
return 32; // property not found
}
return 0; // no errors
}
int VTSDevice :: InternalWriteProperty( BACnetObjectIdentifier * pbacnetobjectid, BACnetEnumerated * pbacnetpropid, BACnetAPDUDecoder * pdec )
{
BACnetObjectIdentifier bacnetobjidThis(8, m_nInstance);
if ( pbacnetobjectid->objID != bacnetobjidThis.objID )
return 31; // object not found
try
{
BACnetUnsigned bacnetunsigned;
switch( pbacnetpropid->m_enumValue )
{
case OBJECT_NAME:
{
BACnetCharacterString str(*pdec);
strncpy(m_strName.GetBuffer(str.strLen+1), (const char *) str.strBuff, str.strLen);
m_strName.SetAt(str.strLen, 0);
m_strName.ReleaseBuffer();
}
break;
case VENDOR_IDENTIFIER:
bacnetunsigned.Decode(*pdec);
m_nVendorID = bacnetunsigned.uintValue;
break;
case MAX_APDU_LENGTH_ACCEPTED:
bacnetunsigned.Decode(*pdec);
m_nMaxAPDUSize = bacnetunsigned.uintValue;
break;
case APDU_TIMEOUT:
bacnetunsigned.Decode(*pdec);
m_nAPDUTimeout = bacnetunsigned.uintValue;
break;
case APDU_SEGMENT_TIMEOUT:
bacnetunsigned.Decode(*pdec);
m_nAPDUSegmentTimeout = bacnetunsigned.uintValue;
break;
case NUMBER_OF_APDU_RETRIES:
bacnetunsigned.Decode(*pdec);
m_nAPDURetries = bacnetunsigned.uintValue;
break;
case SEGMENTATION_SUPPORTED:
bacnetunsigned.Decode(*pdec);
if ( bacnetunsigned.uintValue > (unsigned int) noSegmentation )
return 37; // value out of range
m_segmentation = (BACnetSegmentation) bacnetunsigned.uintValue;
break;
// might be nice to support others implicitly with device declaration...
default:
return 32; // property not found
}
}
catch(...)
{
return 9; // invalid data type
}
return 0; // no errors
}
// Possible errors:
// 2 = device configuration in progress
// 7 = value is not an array but array indexing requested
// 25 = internal problems...
// 31 = object not found
// 32 = property not found
// 42 = array index out of bounds
int VTSDevice :: ReadProperty( BACnetObjectIdentifier * pbacnetobjectid, BACnetEnumerated * pbacnetpropid, int nIndex, BACnetAPDUEncoder * pAPDUEncoder )
{
VTSDevObject * pobject = NULL;
VTSDevProperty * pprop = NULL;
// First attempt to locate property in question from list... if property is for this device this will
// allow for overrides in device object property configuration
// if we find a pobject than we need to try to find the property
// if we don't find the pobject than we assume it is our device object
if ( (pobject = FindObject(pbacnetobjectid->objID)) == NULL )
return InternalReadProperty(pbacnetobjectid, pbacnetpropid, pAPDUEncoder, nIndex);
if ( (pprop = FindProperty(pobject, pbacnetpropid->m_enumValue)) == NULL )
// LJT changed this because InternalReadProperty should only be used for Device Object and
// we already figured out this is not for the device object
// return InternalReadProperty(pbacnetobjectid, pbacnetpropid, pAPDUEncoder);
return 32;
// IF they've requested either the length of the array or a specific element and this isn't
// an array, we need to tell them
if ( !pprop->IsArray() && nIndex != -1 )
return 7; // property is not an array
if ( nIndex == 0 )
{
BACnetUnsigned( pprop->GetValues()->GetSize() ).Encode( *pAPDUEncoder );
return 0;
}
int nStart;
// get all values, array or not
if ( nIndex == -1 )
{
nStart = 0;
nIndex = pprop->GetValues()->GetSize();
}
else
{
// we might be trying to check for out of bounds array...
// Remember that the request is base 1
if ( nIndex > pprop->GetValues()->GetSize() )
return 42; // array index out of bounds
nStart = nIndex-1;
}
for ( ; nStart < nIndex; nStart++ )
{
VTSDevValue * pvalue = (*pprop->GetValues())[nStart];
// There may be some problems simply encoding value after value here..
// It seems like there needs to be a distinction between sets and arrays (I know there is,
// just can't think of it). Outer loop is for arrays, inner is for set values.
try
{
pAPDUEncoder->Append(pvalue->m_abContent, pvalue->m_nLength);
VTSDevValues * pvaluesComponents = pvalue->GetValueList();
for ( int i = 0; pvaluesComponents != NULL && i < pvaluesComponents->GetSize(); i++ )
pAPDUEncoder->Append((*pvaluesComponents)[i]->m_abContent, (*pvaluesComponents)[i]->m_nLength);
}
catch(...)
{
return 25; // database problem... Append has issues.
}
}
return 0;
}
// Possible errors:
// 2 = device configuration in progress
// 7 = value is not an array but array indexing requested
// 25 = internal problems...
// 31 = object not found
// 32 = property not found
// 42 = array index out of bounds
int VTSDevice :: WriteProperty( BACnetObjectIdentifier * pbacnetobjectid, BACnetEnumerated * pbacnetpropid, int nIndex, BACnetAPDUDecoder * pdec )
{
VTSDevObject * pobject = NULL;
VTSDevProperty * pprop = NULL;
// First attempt to locate property in question from list... if property is for this device this will
// allow for overrides in device object property configuration
if ( (pobject = FindObject(pbacnetobjectid->objID)) == NULL )
return InternalWriteProperty(pbacnetobjectid, pbacnetpropid, pdec);
if ( (pprop = FindProperty(pobject, pbacnetpropid->m_enumValue)) == NULL )
return InternalWriteProperty(pbacnetobjectid, pbacnetpropid, pdec);
// IF they've requested to change either the length of the array or a specific element and this isn't
// an array, we need to tell them. This is not physically necessary, but the property must have been
// marked as an array before we should be allowed to make it so by adding elements
if ( !pprop->IsArray() && nIndex != -1 )
return 7; // property is not an array
// They want to change the length of the array... We'll just fill it with null values or cut off
// others...
VTSDevValues * pvalues = pprop->GetValues();
if ( nIndex == 0 )
{
BACnetUnsigned bacnetunsignedLength(*pdec); // auto decodes
if ( bacnetunsignedLength.uintValue < 0 )
return 42; // invalid-array-index
// Now we'll go through all the elements and add some or remove some...
unsigned long nExistingCount = pvalues->GetSize();
if ( bacnetunsignedLength.uintValue < nExistingCount )
{
// need to kill a few existing values... start at the end and work backwards
for ( ; nExistingCount > bacnetunsignedLength.uintValue; nExistingCount-- )
{
delete (*pvalues)[nExistingCount-1];
pvalues->RemoveAt(nExistingCount-1);
}
}
else if ( bacnetunsignedLength.uintValue > nExistingCount )
{
// need to add some null elements... they'll be changed later (I guess in another bacnet message)
for ( ; nExistingCount < bacnetunsignedLength.uintValue; nExistingCount++ )
pvalues->Add(new VTSDevValue());
}
return 0;
}
// OK... they want to change either an existing element or the whole thing...
// all of the nodes have been added so it's just a matter of changing the contents of each node
int nStart;
// replace all values, array or not
if ( nIndex == -1 )
{
nStart = 0;
nIndex = pvalues->GetSize();
}
else
{
// we might be trying to check for out of bounds array...
// Remember that the request is base 1
if ( nIndex > pvalues->GetSize() )
return 42; // array index out of bounds
nStart = nIndex-1;
}
// This really doesn't work too well... Something about arrays, sets and whatnot is going
// to change this code. For now, just go through what you find in the encoded stream and stuff
// each value in the array
BACnetAPDUTag t;
int nNestCount = 0;
bool fFinish = false;
while ( nStart < nIndex && !fFinish && pdec->pktLength > 0 )
{
VTSDevValue * pvalue = (*pvalues)[nStart];
// There may be some problems simply encoding value after value here..
// It seems like there needs to be a distinction between sets and arrays (I know there is,
// just can't think of it). Outer loop is for arrays, inner is for set values.
try
{
pdec->ExamineTag(t);
switch (t.tagClass)
{
case contextTagClass:
// set this as an octet string. Because it is context tagged, the datatype connot
// be determined, the context isn't maintained. It could be, because we know the
// object type and property, and we could even validate the datatype along the
// way, but that will be saved for future work.
pvalue->m_nType = octetStringAppTag;
pvalue->m_nContext = (int) t.tagNumber;
break;
case openingTagClass:
nNestCount++;
pvalue->m_nType = 13; // opening tag
pvalue->m_nContext = (int) t.tagNumber;
break;
case closingTagClass:
if ( !nNestCount--)
{
fFinish = true;
break;
}
pvalue->m_nType = 14; // closing tag
pvalue->m_nContext = (int) t.tagNumber;
break;
case applicationTagClass:
pvalue->m_nType = t.tagNumber; // tag number matches type
pvalue->m_nContext = -1;
break;
}
}
catch (...)
{
return 25; // decoding error
}
// done yet?
if ( !fFinish )
pvalue->m_nLength = pdec->ExtractTagData(pvalue->m_abContent);
nStart++;
}
return 0;
}
const VTSDevice& VTSDevice::operator=(const VTSDevice& rdeviceSrc)
{
m_strName = rdeviceSrc.m_strName;
m_nInstance = rdeviceSrc.m_nInstance;
m_fRouter = rdeviceSrc.m_fRouter;
m_segmentation = rdeviceSrc.m_segmentation;
m_nSegmentSize = rdeviceSrc.m_nSegmentSize;
m_nWindowSize = rdeviceSrc.m_nWindowSize;
m_nMaxAPDUSize = rdeviceSrc.m_nMaxAPDUSize;
m_nNextInvokeID = rdeviceSrc.m_nNextInvokeID;
m_nAPDUTimeout = rdeviceSrc.m_nAPDUTimeout;
m_nAPDUSegmentTimeout = rdeviceSrc.m_nAPDUSegmentTimeout;
m_nAPDURetries = rdeviceSrc.m_nAPDURetries;
m_nVendorID = rdeviceSrc.m_nVendorID;
m_nEvents = rdeviceSrc.m_nEvents;
m_services_supported = rdeviceSrc.m_services_supported;
m_nMaxSegs = rdeviceSrc.m_nMaxSegs;
m_devobjects.DeepCopy(&rdeviceSrc.m_devobjects);
return *this;
}
IMPLEMENT_VTSPTRARRAY(VTSDevices, VTSDevice);
/////////////////////////////////////////////////////////////////////////////
// VTSWinWinPcapPort
//
// VTSWinWinPcapPort::VTSWinWinPcapPort
//
extern CSendGroupPtr gEthernetGroupList[];
extern CSendGroupPtr gARCNETGroupList[];
//VTSWinPacket32Port::VTSWinPacket32Port( VTSPortPtr pp )
// : WinPacket32( pp->m_strConfigParms )
VTSWinWinPcapPort::VTSWinWinPcapPort( VTSPortPtr pp )
: WinWinPcap( pp->m_strConfigParms )
// : WinWinPcap( pp->portDesc.portConfig )
, m_pPort( pp )
{
// let the port know which send group to use
m_pPort->portSendGroup = gEthernetGroupList;
}
//
// VTSWinWinPcapPort::~VTSWinWinPcapPort
//
VTSWinWinPcapPort::~VTSWinWinPcapPort( void )
{
// reset the send group
m_pPort->portSendGroup = 0;
}
//
// VTSWinWinPcapPort::FilterData
//
void VTSWinWinPcapPort::FilterData( BACnetOctet *data, int len, BACnetPortDirection dir )
{
VTSPacket pkt
;
// fill in the packet header
// pkt.packetHdr.packetPortID = m_pPort->portDescID;
strncpy(pkt.packetHdr.m_szPortName, m_pPort->GetName(), sizeof(pkt.packetHdr.m_szPortName)-1);
pkt.packetHdr.packetFlags = 0;
pkt.packetHdr.packetType = (dir == portSending) ? txData : rxData;
// parse the source and destination addresses
pkt.packetHdr.packetProtocolID = (int)BACnetPIInfo::ethernetProtocol;
// check for broadcast destination
if ((data[0] == 0xFF) && (data[1] == 0xFF) && (data[2] == 0xFF)
&& (data[3] == 0xFF) && (data[4] == 0xFF) && (data[5] == 0xFF))
pkt.packetHdr.packetDestination.LocalBroadcast();
else
pkt.packetHdr.packetDestination.LocalStation( data, 6 );
// source is always a station
pkt.packetHdr.packetSource.LocalStation( data + 6, 6 );
// skip processing packets from myself
if ((dir == portReceiving) && (pkt.packetHdr.packetSource == portLocalAddr))
return;
// let the packet refer to the pdu contents, cast away const
pkt.NewDataRef( data, len );
// save it in the database;
m_pPort->portDoc->WritePacket( pkt );
//MAD_DB This is now called from the Doc's WritePacket
/*
// tell the application
if (m_pPort->portDoc->m_postMessages)
::PostThreadMessage( AfxGetApp()->m_nThreadID
, WM_VTS_RCOUNT, (WPARAM)0, (LPARAM)m_pPort->portDoc
);
*/
}
//
// VTSWinWinPcapPort::PortStatusChange
//
void VTSWinWinPcapPort::PortStatusChange( void )
{
// set the VTSPort info to reflect this status
if (portStatus == 0) {
m_pPort->portStatus = 0;
m_pPort->portStatusDesc = 0;
} else {
m_pPort->portStatus = 2;
m_pPort->portStatusDesc = "Something is wrong";
}
// tell the application that something changed.
::PostThreadMessage( AfxGetApp()->m_nThreadID
, WM_VTS_PORTSTATUS, (WPARAM)0, (LPARAM)m_pPort->portDoc
);
}
/////////////////////////////////////////////////////////////////////////////
// VTSWinIPPort
//
// VTSWinIPPort::VTSWinIPPort
//
extern CSendGroupPtr gIPGroupList[];
VTSWinIPPort::VTSWinIPPort( VTSPortPtr pp )
: WinIP( pp->m_strConfigParms )
, m_pPort( pp )
{
// let the port know which send group to use
m_pPort->portSendGroup = gIPGroupList;
}
//
// VTSWinIPPort::~VTSWinIPPort
//
VTSWinIPPort::~VTSWinIPPort( void )
{
// reset the send group
m_pPort->portSendGroup = 0;
}
//
// VTSWinIPPort::FilterData
//
void VTSWinIPPort::FilterData( BACnetOctet *data, int len, BACnetPortDirection dir )
{
VTSPacket pkt
;
// fill in the packet header
strncpy(pkt.packetHdr.m_szPortName, m_pPort->GetName(), sizeof(pkt.packetHdr.m_szPortName)-1);
pkt.packetHdr.packetProtocolID = (int)BACnetPIInfo::ipProtocol;
pkt.packetHdr.packetFlags = 0 /* (pdu.pduExpectingReply << 8) + pdu.pduNetworkPriority */;
pkt.packetHdr.packetType = (dir == portSending) ? txData : rxData;
// parse the header and suck out the source or destination
if (dir == portSending) {
// Destination address from data
pkt.packetHdr.packetDestination.LocalStation( data, 6 );
// Source address is us
pkt.packetHdr.packetSource.LocalStation( m_pPort->portEndpoint->portLocalAddr.addrAddr, 6 );
} else if (dir == portReceiving) {
// Source address from data
pkt.packetHdr.packetSource.LocalStation( data, 6 );
// Destination is either our address or broadcast.
// The IP stack won't tell us, so use the BVLL:
// if data[6] = 0x81 (BVLL type), look at data[7]
// If Original-broadcast (0x0B), show as broadcast
// If Forwarded-npdu, MAY be a broadcast, depending on whether the BBMD used
// one-hop or two-hop. Since one-hop is rare, assume two-hop -> unicast
if ((data[6] == 0x81) && (data[7] == 0x0B))
{
// Broadcast (or a lame implementation that unicast in violation of Annex J)
pkt.packetHdr.packetDestination.LocalBroadcast();
}
else
{
// Unicast (or one-hop forwarding, or a violation of Annex J)
pkt.packetHdr.packetDestination.LocalStation( m_pPort->portEndpoint->portLocalAddr.addrAddr, 6 );
}
}
// let the packet refer to the pdu contents, cast away const
pkt.NewDataRef( data, len );
// save it in the database;
m_pPort->portDoc->WritePacket( pkt );
//MAD_DB This is now called from the Doc's WritePacket
/*
// tell the application there is a new packet count
if (m_pPort->portDoc->m_postMessages)
::PostThreadMessage( AfxGetApp()->m_nThreadID
, WM_VTS_RCOUNT, (WPARAM)0, (LPARAM)m_pPort->portDoc
);
*/
}
//
// VTSWinIPPort::PortStatusChange
//
void VTSWinIPPort::PortStatusChange( void )
{
// set the VTSPort info to reflect this status
if (portStatus == 0) {
m_pPort->portStatus = 0;
m_pPort->portStatusDesc = 0;
} else {
m_pPort->portStatus = 2;
m_pPort->portStatusDesc = "Something is wrong";
}
// tell the application that something changed.
::PostThreadMessage( AfxGetApp()->m_nThreadID
, WM_VTS_PORTSTATUS, (WPARAM)0, (LPARAM)m_pPort->portDoc
);
}
/////////////////////////////////////////////////////////////////////////////
// VTSDevicePort
//
// VTSDevicePort::VTSDevicePort
//
VTSDevicePort::VTSDevicePort( VTSPortPtr pp, VTSDevicePtr dp )
: m_pPort(pp), m_pDevice(dp)
{
// the port should think this is its endpoint
pp->portEndpoint = this;
// let the port know which send group to use
pp->portSendGroup = gDeviceGroupList;
}
//
// VTSDevicePort::~VTSDevicePort
//
VTSDevicePort::~VTSDevicePort( void )
{
// reset the send group
m_pPort->portSendGroup = 0;
}
//
// VTSDevicePort::Indication
//
// This function is required because a VTSDevicePort derives from BACnetNetServer.
// It should never be called, these objects aren't bound to anything.
//
void VTSDevicePort::Indication( const BACnetNPDU &pdu )
{
ASSERT( 0 );
}
//
// VTSDevicePort::SendData
//
void VTSDevicePort::SendData( BACnetOctet *data, int len )
{
int net, addrLen
;
BACnetAPDU apdu
;
// rip apart the address that was so carefully encoded by CSendDevice::EncodePage
apdu.apduAddr.addrType = (BACnetAddressType)(len--,*data++);
net = (len--,*data++);
net = (net << 8) + (len--,*data++);
apdu.apduAddr.addrNet = net;
addrLen = (len--,*data++);
apdu.apduAddr.addrLen = addrLen;
for (int i = 0; i < addrLen; i++)
apdu.apduAddr.addrAddr[i] = (len--,*data++);
// build a temporary decoder out of the rest
BACnetAPDUDecoder dec( data, len )
;
// turn it into an APDU
apdu.Decode( dec );
// pass it along to the device to process
m_pDevice->SendAPDU( apdu );
}
extern BakRestoreExecutor gBakRestoreExecutor;
void VTSDoc::DoBackupRestore( void )
{
gBakRestoreExecutor.ExecuteTest();
}
extern InconsistentParsExecutor gInconsistentParsExecutor;
void VTSDoc::DoInconsistentPars( void )
{
gInconsistentParsExecutor.ExecuteTest();
}
void VTSDoc::OnEditQuickSave()
{
// TODO: Add your command handler code here
CMainFrame* pMainFrame = (CMainFrame*)AfxGetApp()->GetMainWnd();
CString newName;
CString pathname;
pMainFrame->m_wndFileCombo.GetWindowText(pathname);
newName = pathname;
if ( gVTSPreferences.Setting_IsPacketFileRelative() )
ConvertPathToRelative(&newName);
// After path name conversion... only attempt open if the new file is diff from old
// This is a problem if they specify the same file and they've switched between relative and absolute
if ( !m_strLogFilename.CompareNoCase(newName) || !m_PacketDB.Open(newName) )
return;
m_strLogFilename = newName;
SaveConfiguration();
pMainFrame->SaveLogFileHistory((LPCTSTR)pathname);
// Some usage of this function is only to re-specify loading of lost packet file linkage
// during loading... Don't bother reloading list because that's our calling context
CString strStatusText;
strStatusText.Format(IDS_NEWPACKETFILENAME, m_strLogFilename);
ReloadPacketStore();
AfxMessageBox(strStatusText);
// Must call this here.. for some reason we won't see the main list view update until we let this
// message box go, at which time the message in the queue will have been lost (why?)
ScheduleForProcessing();
strStatusText.Format("Loaded logfile: %s", m_strLogFilename );
((CFrameWnd *) AfxGetApp()->m_pMainWnd)->SetMessageText(strStatusText);
}
void VTSDoc::DeleteSelPacket(int index)
{
m_FrameContextsCS.Lock();
if(index < 0 || index > m_apPackets.GetSize() - 1)
return;
delete m_apPackets[index];
m_apPackets.RemoveAt(index);
m_PacketDB.DeletePackets();
for(int i = 0; i < m_apPackets.GetSize(); i++)
{
m_PacketDB.WritePacket(*m_apPackets[i]);
}
m_FrameContextsCS.Unlock();
}
// Process the packet as a possible message segment
void VTSDoc::ProcessMessageSegment( const VTSPacket &pkt, VTSFilterInfo &theInfo )
{
if (theInfo.m_hasSegment)
{
// Message segment
DWORD now = ::GetTickCount();
int ixFree = -1;
bool processed = false;
for (int ix = 0; ix < sizeof(m_pSegmentAccumulator)/sizeof(m_pSegmentAccumulator[0]); ix++)
{
if (m_pSegmentAccumulator[ix] != NULL)
{
if (m_pSegmentAccumulator[ix]->IsMatch( pkt, theInfo ))
{
if (m_pSegmentAccumulator[ix]->AddPacket( pkt, theInfo ))
{
// Last segment: Add to the doc
WritePacket( m_pSegmentAccumulator[ix]->m_packet );
delete m_pSegmentAccumulator[ix];
m_pSegmentAccumulator[ix] = NULL;
}
processed = true;
break;
}
else if (m_pSegmentAccumulator[ix]->m_startTime - now > 60000)
{
// Context is more than 60 seconds old. Delete it
delete m_pSegmentAccumulator[ix];
m_pSegmentAccumulator[ix] = NULL;
ixFree = ix;
}
}
else if (ixFree < 0)
{
ixFree = ix;
}
}
if (!processed && (ixFree >= 0))
{
// Start a segmentation sequence
m_pSegmentAccumulator[ixFree] = new VTSSegmentAccumulator( pkt, theInfo );
}
}
}
// Class to hold information about a series of VTSPacket segments
// Used to accumulate an entire message
VTSSegmentAccumulator::VTSSegmentAccumulator( const VTSPacket &packet, VTSFilterInfo &theInfo )
: m_startTime( ::GetTickCount() )
, m_packet(packet)
, m_srcAddr(theInfo.m_srcAddr)
, m_destAddr(theInfo.m_destAddr)
, m_pduType(theInfo.m_pduType)
, m_sequence(theInfo.m_sequence + 1)
, m_service(theInfo.m_service)
, m_invokeID(theInfo.m_invokeID)
{
// m_packet contains a packet with the segmentation flags.
// We need to remove the two extra bytes (sequence number and window size)
// and recode the APDU header so that it will display correctly.
BACnetOctet *pTags = m_packet.packetData + theInfo.m_cursor;
BACnetOctet *pApduHeader = pTags;
if (m_pduType == confirmedRequestPDU)
{
pApduHeader -= 6;
pApduHeader[0] = (BACnetOctet)(pApduHeader[0] & 0xF3); // turn off SEG and MOR
pApduHeader[3] = (BACnetOctet)m_service;
pApduHeader += 4;
}
else
{
pApduHeader -= 5;
pApduHeader[0] = (BACnetOctet)(pApduHeader[0] & 0xF3); // turn off SEG and MOR
pApduHeader[2] = (BACnetOctet)m_service;
pApduHeader += 3;
}
memcpy( pApduHeader, pTags, theInfo.m_length );
m_packet.packetLen -= 2;
}
bool VTSSegmentAccumulator::IsMatch( const VTSPacket &packet, VTSFilterInfo &theInfo ) const
{
// Compare the integers first for speed of mismatch
return ((m_invokeID == theInfo.m_invokeID) &&
(m_pduType == theInfo.m_pduType) &&
(m_service == theInfo.m_service) &&
(m_srcAddr == theInfo.m_srcAddr) &&
(m_destAddr == theInfo.m_destAddr));
}
// Add the packet to the accumulator
// Return true if the final segment has been added
bool VTSSegmentAccumulator::AddPacket( const VTSPacket &packet, VTSFilterInfo &theInfo )
{
if (theInfo.m_sequence == m_sequence)
{
// Expected segment. Append its data
int newLen = m_packet.packetLen + theInfo.m_length;
BACnetOctetPtr pData = new BACnetOctet[ newLen ];
memcpy( pData, m_packet.packetData, m_packet.packetLen );
memcpy( pData + m_packet.packetLen, packet.packetData + theInfo.m_cursor, theInfo.m_length );
m_packet.NewDataRef( pData, newLen, true );
m_sequence++;
}
return !theInfo.m_moreFollows;
}