[go: up one dir, main page]

Menu

[r41]: / trunc / source / awuser.pas  Maximize  Restore  History

Download this file

4856 lines (4340 with data), 166.3 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
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
(***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is TurboPower Async Professional
*
* The Initial Developer of the Original Code is
* TurboPower Software
*
* Portions created by the Initial Developer are Copyright (C) 1991-2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Stephen W. Boyd - Rewrote the Win32 dispatcher to reduce vulnerability
* August 2005 to badly behaved event handlers. Rather than having
* the read thread block until all events have been processed
* the read thread now places input onto an 'endless'
* queue. The dispatch thread reads this queue and
* calls the event handlers. This allows input the be
* continuously read from the input device while the
* event handlers are executing. Should cut down on
* input overruns. To use the old Win32 dispatcher rather
* then mine define the conditional UseAwWin32 and rebuild
* the library.
* Kevin G. McCoy
* 1 Feb 2008 - Found and fixed the status buffer memory leak. Buffers
* were being popped off the queue but not freed; Added
* D2006 / D2007 compiler strings
*
* Sulaiman Mah
* Sean B. Durkin
* Sebastian Zierer
* ***** END LICENSE BLOCK ***** *)
{*********************************************************}
{* AWUSER.PAS 5.00 *}
{*********************************************************}
{* Low-level dispatcher *}
{*********************************************************}
{* Thanks to David Hudder for his substantial *}
{* contributions to improve efficiency and reliability *}
{*********************************************************}
{
This unit defines the dispatcher, com and output threads. When
a serial port is opened (Winsock does not use a multi-threaded
architecture), these three threads are created. The dispatcher
thread is the interface between your application and the port.
The dispatcher thread synchronizes with the thread that opened
the port via SendMessageTimeout, in case of timeout (usually 3
seconds), we will discard whatever we were trying to notify you
about and resume the thread. For this reason, the thread that
opened the port should not be blocked for more than a few ticks,
and the event handler should get the data and return as quickly
as possible. Do not do any DB or file access inside an OnTriggerXxx
event, those actions can take too long. Instead, collect the data
and process it later. A good approach is to collect the data,
post a message to yourself, and process the data from the message
handler.
The dispatcher thread is the interface between the application
layer and the port. The dispatcher thread runs in the context of
the thread that opened the port. The com thread is tied to the
serial port drivers to receive notification when things change.
The com thread wakes the dispatcher thread, the dispatcher thread
then generates the events. The output thread is there to process
the internal output buffer.
Be extrememly cautious when making changes here. The multi-threaded
nature, and very strict timing requirements, can lead to very
unpredictable results. Things as simple as doing a writeln to a
console window can dramatically change the results.
}
{Global defines potentially affecting this unit}
{$I AWDEFINE.INC}
{Options required for this unit}
{$X+,B-,I-,T-,J+}
{.$DEFINE DebugThreads} // --sm to delete
{$IFDEF CONSOLE}
{.$DEFINE DebugThreadConsole} // --sm to delete
{$ENDIF}
{!!.02} { removed Win16 references }
unit AwUser;
{-Basic API provided by APRO}
interface
uses
Windows,
Messages,
SysUtils,
Classes,
MMSystem,
OoMisc,
AdExcept,
LNSQueue; // SWB
const
FirstTriggerCounter = 1;
MaxTriggerHandle = 65536 shr 4;{Highest trigger handle number (4096)}
StatusTypeMask = $0007;
ThreadStartWait = 3000; {Milliseconds to wait for sub-threads to start}
ModemEvent = EV_CTS or EV_DSR or EV_RLSD or EV_RING or EV_RINGTE; // SWB
LineEvent = EV_ERR or EV_BREAK; // SWB
{Use these event bits for fast checking of serial events} // SWB
DefEventMask = ev_CTS + ev_DSR + ev_RLSD + ev_Ring + ev_RingTe + // SWB
ev_RxChar + ev_Err + ev_Break; // SWB
type
TApHandlerFlagUpdate = (fuKeepPort, fuEnablePort, fuDisablePort);
TApdBaseDispatcher = class;
TApdDispatcherThread = class(TThread)
private
pMsg, pTrigger : Cardinal;
plParam : LongInt;
pTriggerEvent : TApdNotifyEvent;
procedure SyncEvent;
protected
H : TApdBaseDispatcher; // SWB
public
constructor Create(Disp : TApdBaseDispatcher);
procedure SyncNotify(Msg, Trigger : Cardinal; lParam : LongInt; Event : TApdNotifyEvent);
procedure Sync(Method: TThreadMethod);
property ReturnValue; // SWB
end;
TOutThread = class(TApdDispatcherThread)
procedure Execute; override;
end;
TComThread = class(TApdDispatcherThread)
procedure Execute; override;
end;
TDispThread = class(TApdDispatcherThread)
procedure Execute; override;
end;
{Standard comm port record}
TApdDispatcherClass = class of TApdBaseDispatcher;
TApdBaseDispatcher = class
protected
fOwner : TObject;
fHandle : Integer; {Handle for this comm port}
OpenHandle : Boolean;
CidEx : Integer; {Comm or other device ID}
LastError : Integer; {Last error from COM API}
InQue : Cardinal; {Size of device input buffer}
OutQue : Cardinal; {Size of device output buffer}
ModemStatus : Cardinal; {Modem status register}
ComStatus : TComStat; {Results of last call for com status}
DCB : TDCB; {Results of last call for DCB}
LastBaud : LongInt; {Last baud set}
Flags : Cardinal; {Option flags}
DTRState : Boolean; {Last set DTR state}
DTRAuto : Boolean; {True if in handshake mode}
RTSState : Boolean; {Last set RTS state}
RTSAuto : Boolean; {True if in handshake mode}
fDispatcherWindow : Cardinal; {Handle to dispatcher window}
LastModemStatus : Cardinal; {Last modem status read}
LastLineErr : Cardinal; {Last line error read}
RS485Mode : Boolean; {True if in RS485 mode}
BaseAddress : Word; {Base address of port}
{Trigger stuff}
PortHandlerInstalled : Boolean; {True if any of the comport's trigger handlers <> nil}
HandlerServiceNeeded : Boolean; {True if handlers need to be serviced}
WndTriggerHandlers : TList;
ProcTriggerHandlers : TList;
EventTriggerHandlers : TList;
TimerTriggers : TList; {Timer triggers}
DataTriggers : TList; {Data triggers}
StatusTriggers : TList; {Status triggers}
LastTailData : Cardinal; {Tail of last data checked for data}
LastTailLen : Cardinal; {Tail of last data sent in len msg}
LenTrigger : Cardinal; {Number of bytes before length trigger}
GlobalStatHit : Boolean; {True if at least one status trigger hit}
InAvailMessage : Boolean; {True when within Avail msg}
GetCount : Cardinal; {Chars looked at in Avail msg}
MaxGetCount : Cardinal; {Max chars looked at in Avail}
DispatchFull : Boolean; {True when dispatch buffer full}
NotifyTail : Cardinal; {Position of last character notified}
{Thread stuff}
KillThreads : Boolean; {True to kill threads}
ComThread : TApdDispatcherThread; // SWB
fDispThread : TDispThread;
OutThread : TApdDispatcherThread; // SWB
StatusThread : TapdDispatcherThread; // SWB
ThreadBoost : Byte;
DataSection : TRTLCriticalSection; {For all routines}
OutputSection : TRTLCriticalSection; {For output buffer and related data}
DispSection : TRTLCriticalSection; {For dispatcher buffer and related data}
ComEvent : THandle; {Signals com thread is ready}
ReadyEvent : THandle; {Signals completion of com thread}
GeneralEvent : THandle; {For general misc signalling}
OutputEvent : THandle; {Signals output buf has data to send}
SentEvent : THandle; {Signals completion of overlapped write}
OutFlushEvent : THandle; {Signals request to flush output buffer}
OutWaitObjects1: array[0..1] of THandle; {Output thread wait objects}
OutWaitObjects2: array[0..1] of THandle; {More output thread wait objects}
CurrentEvent : DWORD; {Current communications event}
RingFlag : Boolean; {True when ringte event received}
FQueue : TIOQueue; {Input queue} // SWB
{ Output buffer -- protected by OutputSection }
OBuffer : pointer; {Output buffer}
OBufHead : Cardinal; {Head offset in OBuffer}
OBufTail : Cardinal; {Tail offset in OBuffer}
OBufFull : Boolean; {True when output buffer full}
{ Dispatcher stuff -- protected by DispSection }
DBuffer : pointer; {Dispatcher buffer}
DBufHead : Cardinal; {Head offset in DBuffer}
DBufTail : Cardinal; {Tail offset in DBuffer}
fEventBusy : Boolean; {True if we're processing a COM event}
DeletePending : Boolean; {True if an event handler was deleted during a busy state}
ClosePending : Boolean; {True if close pending}
OutSentPending: Boolean; {True if stOutSent trigger pending}
{Tracing stuff}
TracingOn : Boolean; {True if tracing is on}
TraceQueue : PTraceQueue; {Circular trace buffer}
TraceIndex : Cardinal; {Head of trace queue}
TraceMax : Cardinal; {Number of trace entries}
TraceWrapped : Boolean; {True if trace wrapped}
{DispatchLogging stuff}
DLoggingOn : Boolean; {True if dispatch logging is on}
DLoggingQueue : TIOQueue; { 'endless' dispatching buffer } // SWB
DLoggingMax : Cardinal; {Number of bytes in logging buffer}
TimeBase : DWORD; {Time dispatching was turned on}
{DispatcherMode : Cardinal;}
TimerID : Cardinal;
TriggerCounter : Cardinal; {Last allocated trigger handle}
DispActive : Boolean;
{Protected virtual dispatcher functions:}
DoDonePortPrim : Boolean;
ActiveThreads : Integer;
CloseComActive : Boolean; // SWB
function EscapeComFunction(Func : Integer) : LongInt; virtual; abstract;
function FlushCom(Queue : Integer) : Integer; virtual; abstract;
function GetComError(var Stat : TComStat) : Integer; virtual; abstract;
function GetComEventMask(EvtMask : Integer) : Cardinal; virtual; abstract;
function GetComState(var DCB: TDCB): Integer; virtual; abstract;
function ReadCom(Buf : PAnsiChar; Size: Integer) : Integer; virtual; abstract;
function SetComState(var DCB : TDCB) : Integer; virtual; abstract;
function WriteCom(Buf : PansiChar; Size: Integer) : Integer; virtual; abstract; // --sm check
function WaitComEvent(var EvtMask : DWORD;
lpOverlapped : POverlapped) : Boolean; virtual; abstract;
function SetupCom(InSize, OutSize : Integer) : Boolean; virtual; abstract;
// --sm to delete unwanted functions and procedures
function CheckReceiveTriggers : Boolean;
function CheckStatusTriggers : Boolean;
function CheckTimerTriggers : Boolean;
function CheckTriggers : Boolean;
procedure CreateDispatcherWindow;
procedure DonePortPrim; virtual;
function DumpDispatchLogPrim(
FName : string;
AppendFile, InHex, AllHex : Boolean) : Integer;
function DumpTracePrim(FName : string;
AppendFile, InHex, AllHex : Boolean) : Integer;
function ExtractData : Boolean;
function FindTriggerFromHandle(TriggerHandle : Cardinal; Delete : Boolean;
var T : TTriggerType; var Trigger : Pointer) : Integer;
function GetDispatchTime : DWORD;
function GetModemStatusPrim(ClearMask : Byte) : Byte;
function GetTriggerHandle : Cardinal;
procedure MapEventsToMS(Events : Integer);
function PeekBlockPrim(
Block : PAnsiChar;
Offset : Cardinal;
Len : Cardinal;
var NewTail : Cardinal) : Integer;
function PeekCharPrim(var C : AnsiChar; Count : Cardinal) : Integer;
procedure RefreshStatus;
procedure ResetStatusHits;
procedure ResetDataTriggers;
function SendNotify(Msg, Trigger, Data: Cardinal) : Boolean;
function SetCommStateFix(var DCB : TDCB) : Integer;
procedure StartDispatcher; virtual; abstract; // --sm need it
procedure StopDispatcher; virtual; abstract;
procedure ThreadGone(Sender: TObject); // SWB
procedure ThreadStart(Sender : TObject); // SWB
procedure WaitTxSent;
function OutBufUsed: Cardinal; virtual; abstract; // SWB
function InQueueUsed : Cardinal; virtual; // SWB
public
DataPointers : TDataPointerArray; {Array of data pointers}
DeviceName : string; {Name of device being used, for log }
LastWinError : Integer; // SWB
property Active : Boolean read DispActive;
property Logging : Boolean read DLoggingOn;
procedure AddDispatchEntry(
DT : TDispatchType;
DST : TDispatchSubType;
Data : Cardinal;
Buffer : Pointer;
BufferLen : Cardinal);
procedure AddStringToLog(S : Ansistring);
property ComHandle : Integer read CidEx;
{Public virtual dispatcher functions:}
function OpenCom(ComName: PChar; InQueue,
OutQueue : Cardinal) : Integer; virtual; abstract;
function CloseCom : Integer; virtual; abstract;
function CheckPort(ComName: PChar): Boolean; virtual; abstract; //SZ
property DispatcherWindow : Cardinal read fDispatcherWindow;
property DispThread : TDispThread read fDispThread;
property EventBusy : boolean read fEventBusy write fEventBusy;
property Handle : Integer read fHandle;
property Owner : TObject read fOwner;
constructor Create(Owner : TObject);
destructor Destroy; override;
procedure AbortDispatchLogging;
procedure AbortTracing;
function AddDataTrigger(Data : PAnsiChar; // --sm PansiChar
IgnoreCase : Boolean) : Integer;
function AddDataTriggerLen(Data : PAnsiChar; // --sm Pansichar
IgnoreCase : Boolean;
Len : Cardinal) : Integer;
function AddStatusTrigger(SType : Cardinal) : Integer;
function AddTimerTrigger : Integer;
procedure AddTraceEntry(CurEntry : AnsiChar; CurCh : AnsiChar);
function AppendDispatchLog(FName : string;
InHex, AllHex : Boolean) : Integer;
function AppendTrace(FName : string;
InHex, AllHEx : Boolean) : Integer;
procedure BufferSizes(var InSize, OutSize : Cardinal);
function ChangeBaud(NewBaud : LongInt) : Integer;
procedure ChangeLengthTrigger(Length : Cardinal);
function CheckCTS : Boolean;
function CheckDCD : Boolean;
function CheckDeltaCTS : Boolean;
function CheckDeltaDSR : Boolean;
function CheckDeltaRI : Boolean;
function CheckDeltaDCD : Boolean;
function CheckDSR : Boolean;
function CheckLineBreak : Boolean;
function CheckRI : Boolean;
function ClassifyStatusTrigger(TriggerHandle : Cardinal) : Cardinal;
procedure ClearDispatchLogging;
class procedure ClearSaveBuffers(var Save : TTriggerSave);
function ClearTracing : Integer;
procedure DeregisterWndTriggerHandler(HW : TApdHwnd);
procedure DeregisterProcTriggerHandler(NP : TApdNotifyProc);
procedure DeregisterEventTriggerHandler(NP : TApdNotifyEvent);
procedure DonePort;
function DumpDispatchLog(FName : string; InHex, AllHex : Boolean) : Integer;
function DumpTrace(FName : string; InHex, AllHex : Boolean) : Integer;
function ExtendTimer(TriggerHandle : Cardinal;
Ticks : LongInt) : Integer;
function FlushInBuffer : Integer;
function FlushOutBuffer : Integer;
function CharReady : Boolean;
function GetBaseAddress : Word;
function GetBlock(Block : PAnsiChar; Len : Cardinal) : Integer;
function GetChar(var C : AnsiChar) : Integer;
function GetDataPointer(var P : Pointer; Index : Cardinal) : Integer;
function GetFlowOptions(var HWOpts, SWOpts, BufferFull,
BufferResume : Cardinal; var OnChar, OffChar : AnsiChar): Integer;
procedure GetLine(var Baud : LongInt; var Parity : Word;
var DataBits : TDatabits; var StopBits : TStopbits);
function GetLineError : Integer;
function GetModemStatus : Byte;
function HWFlowOptions(BufferFull, BufferResume : Cardinal;
Options : Cardinal) : Integer;
function HWFlowState : Integer;
function InBuffUsed : Cardinal;
function InBuffFree : Cardinal;
procedure InitDispatchLogging(QueueSize : Cardinal);
function InitPort(AComName : PChar; Baud : LongInt;
Parity : Cardinal; DataBits : TDatabits; StopBits : TStopbits;
InSize, OutSize : Cardinal; FlowOpts : DWORD) : Integer;
function InitSocket(InSize, OutSize : Cardinal) : Integer;
function InitTracing(NumEntries : Cardinal) : Integer;
function OptionsAreOn(Options : Cardinal) : Boolean;
procedure OptionsOn(Options : Cardinal);
procedure OptionsOff(Options : Cardinal);
function OutBuffUsed : Cardinal;
function OutBuffFree : Cardinal;
function PeekBlock(Block : PAnsiChar; Len : Cardinal) : Integer;
function PeekChar(var C : AnsiChar; Count : Cardinal) : Integer;
function ProcessCommunications : Integer; virtual; abstract;
function PutBlock(const Block; Len : Cardinal) : Integer;
function PutChar(C : AnsiChar) : Integer; // --sm ansi
function PutString(S : AnsiString) : Integer;
procedure RegisterWndTriggerHandler(HW : TApdHwnd);
procedure RegisterProcTriggerHandler(NP : TApdNotifyProc);
procedure RegisterSyncEventTriggerHandler(NP : TApdNotifyEvent);
procedure RegisterEventTriggerHandler(NP : TApdNotifyEvent);
procedure RemoveAllTriggers;
function RemoveTrigger(TriggerHandle : Cardinal) : Integer;
procedure RestoreTriggers( var Save : TTriggerSave);
procedure SaveTriggers( var Save : TTriggerSave);
procedure SetBaseAddress(NewBaseAddress : Word);
procedure SendBreak(Ticks : Cardinal; Yield : Boolean);
procedure SetBreak(BreakOn : Boolean);
procedure SetThreadBoost(Boost : Byte); virtual;
function SetDataPointer( P : Pointer; Index : Cardinal) : Integer;
function SetDtr(OnOff : Boolean) : Integer;
procedure SetEventBusy(var WasOn : Boolean; SetOn : Boolean);
procedure SetRS485Mode(OnOff : Boolean);
function SetRts(OnOff : Boolean) : Integer;
function SetLine(Baud : LongInt; Parity : Cardinal;
DataBits : TDatabits; StopBits : TStopbits) : Integer;
function SetModem(DTR, RTS : Boolean) : Integer;
function SetStatusTrigger(TriggerHandle : Cardinal;
Value : Cardinal; Activate : Boolean) : Integer;
function SetTimerTrigger(TriggerHandle : Cardinal;
Ticks : LongInt; Activate : Boolean) : Integer;
function SetCommBuffers(InSize, OutSize : Integer) : Integer;
procedure StartDispatchLogging;
procedure StartTracing;
procedure StopDispatchLogging;
procedure StopTracing;
function SWFlowChars( OnChar, OffChar : AnsiChar) : Integer;
function SWFlowDisable : Integer;
function SWFlowEnable(BufferFull, BufferResume : Cardinal;
Options : Cardinal) : Integer;
function SWFlowState : Integer;
function TimerTicksRemaining(TriggerHandle : Cardinal;
var TicksRemaining : Longint) : Integer;
procedure UpdateHandlerFlags(FlagUpdate : TApHandlerFlagUpdate); virtual;
end;
function GetTComRecPtr(Cid : Integer; DeviceLayerClass : TApdDispatcherClass) : Pointer;
var
PortList : TList;
procedure LockPortList;
procedure UnlockPortList;
function PortIn(Address: Word): Byte; // SWB
implementation
var
PortListSection : TRTLCriticalSection;
const
{ This should be the same in ADSOCKET.PAS }
CM_APDSOCKETMESSAGE = WM_USER + $0711;
{For setting stop bits}
StopBitArray : array[TStopbits] of Byte = (OneStopbit, TwoStopbits, 0);
{For quick checking and disabling of all flow control options}
InHdwFlow = dcb_DTRBit2 + dcb_RTSBit2;
OutHdwFlow = dcb_OutxDSRFlow + dcb_OutxCTSFlow;
AllHdwFlow = InHdwFlow + OutHdwFlow;
AllSfwFlow = dcb_InX + dcb_OutX;
{Mask of errors we care about}
ValidErrorMask =
ce_RXOver + {receive queue overflow}
ce_Overrun + {receive overrun error}
ce_RXParity + {receive parity error}
ce_Frame + {receive framing error}
ce_Break; {break detected}
{For clearing modem status}
ClearDelta = $F0;
ClearNone = $FF;
ClearDeltaCTS = Byte(not DeltaCTSMask);
ClearDeltaDSR = Byte(not DeltaDSRMask);
ClearDeltaRI = Byte(not DeltaRIMask);
ClearDeltaDCD = Byte(not DeltaDCDMask);
{General purpose routines}
const
LastCID : Integer = -1;
LastDispatcher : TApdBaseDispatcher = nil;
//SZ: this was removed, but it is needed by AWWNSOCK.pas
function GetTComRecPtr(Cid : Integer; DeviceLayerClass : TApdDispatcherClass) : Pointer;
{-Find the entry into the port array which has the specified Cid}
var
i : Integer;
begin
LockPortList;
try
{find the correct com port record}
if (LastCID = Cid) and (LastDispatcher <> nil) then
Result := LastDispatcher
else begin
for i := 0 to pred(PortList.Count) do
if PortList[i] <> nil then
with TApdBaseDispatcher(PortList[i]) do
if (CidEx = Cid) and (TObject(PortList[i]) is DeviceLayerClass) then begin
Result := TApdBaseDispatcher(PortList[i]);
LastCID := Cid;
LastDispatcher := Result;
exit;
end;
Result := nil;
end;
finally
UnlockPortList;
end;
end;
{$IFDEF DebugThreadConsole}
type
TThreadStatus = (ComStart, ComWake, ComSleep, ComKill,
DispStart, DispWake, DispSleep, DispKill,
OutStart, OutWake, OutSleep, OutKill);
var
C, D, O : Char; {!!.02}
function ThreadStatus(Stat : TThreadStatus) : string;
begin
C := '.'; {!!.02}
D := '.'; {!!.02}
O := '.'; {!!.02}
case Stat of
ComStart,
ComWake : C := 'C';
ComSleep : C := 'c';
ComKill : C := 'x';
DispStart,
DispWake : D := 'D';
DispSleep : D := 'd';
DispKill : D := 'x';
OutStart,
OutWake : O := 'O';
OutSleep : O := 'o';
OutKill : O := 'x';
end;
Result := C + D + O + ' ' + IntToStr(AdTimeGetTime);
end;
{$ENDIF}
function BuffCount(Head, Tail: Cardinal; Full : Boolean) : Cardinal;
{-Return number of chars between Tail and Head}
begin
if Head = Tail then
if Full then
BuffCount := DispatchBufferSize
else
BuffCount := 0
else if Head > Tail then
BuffCount := Head-Tail
else
BuffCount := (Head+DispatchBufferSize)-Tail;
end;
function TApdBaseDispatcher.InQueueUsed : Cardinal; // SWB
begin // SWB
Result := 0; // SWB
end; // SWB
procedure TApdBaseDispatcher.ThreadGone(Sender: TObject);
var // SWB
retVal : Integer; // SWB
begin
retVal := TApdDispatcherThread(Sender).ReturnValue; // SWB
if ((retVal = ecDeviceRead) or (retVal = ecDeviceWrite)) then // SWB
begin // SWB
LastError := -1; // SWB
CheckStatusTriggers; // SWB
end else // SWB
begin // SWB
try // SWB
CheckException(TComponent(Owner), // SWB
TApdDispatcherThread(Sender).ReturnValue); // SWB
except // SWB
on E : Exception do // SWB
begin // SWB
ShowException(E, ExceptAddr); // SWB
end; // SWB
end; // SWB
end; // SWB
if Sender = ComThread then
ComThread := nil;
if Sender = OutThread then
OutThread := nil;
if Sender = fDispThread then begin
fDispThread := nil;
if DoDonePortPrim then begin
DonePortPrim;
DoDonePortPrim := False;
end;
end;
if Sender = StatusThread then // SWB
StatusThread := nil; // SWB
if (InterLockedDecrement(ActiveThreads) = 0) then begin
DispActive := False;
end;
end;
procedure TApdBaseDispatcher.ThreadStart(Sender : TObject); // SWB
begin // SWB
InterLockedIncrement(ActiveThreads); // SWB
SetEvent(GeneralEvent); // SWB
end; // SWB
procedure TApdBaseDispatcher.SetThreadBoost(Boost : Byte);
begin
if Boost <> ThreadBoost then begin
ThreadBoost := Boost;
if Assigned(ComThread) then
ComThread.Priority := TThreadPriority(Ord(tpNormal) + Boost);
if Assigned(fDispThread) then
fDispThread.Priority := TThreadPriority(Ord(tpNormal) + Boost);
if Assigned(fDispThread) then
if RS485Mode then
OutThread.Priority := TThreadPriority(Ord(tpHigher) + Boost)
else
OutThread.Priority := TThreadPriority(Ord(tpNormal) + Boost);
if Assigned(StatusThread) then // SWB
StatusThread.Priority := TThreadPriority(Ord(tpNormal) + Boost); // SWB
end;
end;
constructor TApdBaseDispatcher.Create(Owner : TObject);
var
i : Integer;
begin
inherited Create;
fOwner := Owner;
ComEvent := INVALID_HANDLE_VALUE;
ReadyEvent := INVALID_HANDLE_VALUE;
GeneralEvent := INVALID_HANDLE_VALUE;
OutputEvent := INVALID_HANDLE_VALUE;
SentEvent := INVALID_HANDLE_VALUE;
OutFlushEvent := INVALID_HANDLE_VALUE;
LockPortList;
try
{Find a free slot in PortListX or append if none found (see Destroy) }
fHandle := -1;
for i := 0 to pred(PortList.Count) do
if PortList[i] = nil then begin
PortList[i] := Self;
fHandle := i;
break;
end;
if fHandle = -1 then
fHandle := PortList.Add(Self);
finally
UnlockPortList;
end;
{Allocate critical section objects}
FillChar(DataSection, SizeOf(DataSection), 0);
InitializeCriticalSection(DataSection);
FillChar(OutputSection, SizeOf(OutputSection), 0);
InitializeCriticalSection(OutputSection);
FillChar(DispSection, SizeOf(DispSection), 0);
InitializeCriticalSection(DispSection);
WndTriggerHandlers := TList.Create;
ProcTriggerHandlers := TList.Create;
EventTriggerHandlers := TList.Create;
TimerTriggers := TList.Create;
DataTriggers := TList.Create;
StatusTriggers:= TList.Create;
TriggerCounter := FirstTriggerCounter;
FQueue := TIOQueue.Create; // SWB
DLoggingQueue := TIOQueue.Create; // SWB
end;
destructor TApdBaseDispatcher.Destroy;
var
i : Integer;
begin
if ClosePending then begin
DonePortPrim
end else
DonePort;
{ it's possible for the main VCL thread (or whichever thread opened }
{ the port) to destroy the dispatcher while we're still waiting for }
{ our Com, Output and Dispatcher threads to terminate, we'll spin }
{ here waiting for the threads to terminate. }
while ActiveThreads > 0 do {!!.02}
SafeYield; {!!.02}
LockPortList;
try
{ We can't just call Remove since there may be other ports open where }
{ we use the index into the PortListX array as a handle }
PortList[PortList.IndexOf(Self)] := nil;
for i := PortList.Count - 1 downto 0 do
if PortList[i] = nil then
PortList.Delete(i)
else
break;
if LastDispatcher = Self then begin
LastDispatcher := nil;
LastCID := -1;
end;
finally
UnlockPortList;
end;
while TimerTriggers.Count > 0 do begin
Dispose(PTimerTrigger(TimerTriggers[0]));
TimerTriggers.Delete(0);
end;
TimerTriggers.Free;
while DataTriggers.Count > 0 do begin
Dispose(PDataTrigger(DataTriggers[0]));
DataTriggers.Delete(0);
end;
DataTriggers.Free;
while StatusTriggers.Count > 0 do begin
Dispose(PStatusTrigger(StatusTriggers[0]));
StatusTriggers.Delete(0);
end;
StatusTriggers.Free;
while WndTriggerHandlers.Count > 0 do begin
Dispose(PWndTriggerHandler(WndTriggerHandlers[0]));
WndTriggerHandlers.Delete(0);
end;
WndTriggerHandlers.Free;
while ProcTriggerHandlers.Count > 0 do begin
Dispose(PProcTriggerHandler(ProcTriggerHandlers[0]));
ProcTriggerHandlers.Delete(0);
end;
ProcTriggerHandlers.Free;
while EventTriggerHandlers.Count > 0 do begin
Dispose(PEventTriggerHandler(EventTriggerHandlers[0]));
EventTriggerHandlers.Delete(0);
end;
EventTriggerHandlers.Free;
{Free the critical sections}
DeleteCriticalSection(DataSection);
DeleteCriticalSection(OutputSection);
DeleteCriticalSection(DispSection);
if (Assigned(FQueue)) then // SWB
FQueue.Free; // SWB
if (Assigned(DLoggingQueue)) then // SWB
DLoggingQueue.Free; // SWB
inherited Destroy;
end;
procedure TApdBaseDispatcher.RefreshStatus;
{-Get current ComStatus}
var
NewError : Integer;
begin
{Get latest ComStatus and LastError}
NewError := GetComError(ComStatus);
{Mask off those bits we don't care about}
LastError := LastError or (NewError and ValidErrorMask);
end;
procedure TApdBaseDispatcher.MapEventsToMS(Events : Integer);
{-Set bits in ModemStatus according to flags in Events}
var
OldMS : Byte;
Delta : Byte;
begin
{Note old, get new}
OldMS := ModemStatus;
GetModemStatusPrim($FF);
{Set delta bits}
Delta := (OldMS xor ModemStatus) and $F0;
ModemStatus := ModemStatus or (Delta shr 4);
end;
{Routines used by constructor}
procedure TApdBaseDispatcher.RemoveAllTriggers;
{-Remove all triggers}
begin
EnterCriticalSection(DataSection);
try
LenTrigger := 0;
while TimerTriggers.Count > 0 do begin
Dispose(PTimerTrigger(TimerTriggers[0]));
TimerTriggers.Delete(0);
end;
while DataTriggers.Count > 0 do begin
Dispose(PDataTrigger(DataTriggers[0]));
DataTriggers.Delete(0);
end;
while StatusTriggers.Count > 0 do begin
Dispose(PStatusTrigger(StatusTriggers[0]));
StatusTriggers.Delete(0);
end;
TriggerCounter := FirstTriggerCounter;
finally
LeaveCriticalSection(DataSection);
end;
end;
function TApdBaseDispatcher.SetCommStateFix(var DCB : TDCB) : Integer;
{-Preserve DTR and RTS states}
begin
if not DTRAuto then begin
DCB.Flags := DCB.Flags and not (dcb_DTRBit1 or dcb_DTRBit2);
if DTRState then begin
{ Assert DTR }
DCB.Flags := DCB.Flags or dcb_DTR_CONTROL_ENABLE;
end;
end;
if not RTSAuto then begin
DCB.Flags := DCB.Flags and not (dcb_RTSBit1 or dcb_RTSBit2);
if RTSState then begin
{ Assert RTS }
DCB.Flags := DCB.Flags or dcb_RTS_CONTROL_ENABLE;
end;
end;
Result := SetComState(DCB);
LastBaud := DCB.BaudRate;
SetDtr(DtrState);
if not RS485Mode then
SetRts(RtsState);
end;
procedure TApdBaseDispatcher.ResetStatusHits;
var
i : Integer;
begin
for i := pred(StatusTriggers.Count) downto 0 do
PStatusTrigger(StatusTriggers[i])^.StatusHit := False;
GlobalStatHit := False;
end;
procedure TApdBaseDispatcher.ResetDataTriggers;
var
i : Integer;
begin
for i := pred(DataTriggers.Count) downto 0 do
with PDataTrigger(DataTriggers[i])^ do
FillChar(tChkIndex, SizeOf(TCheckIndex), 0);
end;
function TApdBaseDispatcher.InitPort(
AComName : PChar;
Baud : LongInt;
Parity : Cardinal;
DataBits : TDatabits;
StopBits : TStopbits;
InSize, OutSize : Cardinal;
FlowOpts : DWORD) : Integer;
type
OS = record
O : Cardinal;
S : Cardinal;
end;
var
Error : Integer;
begin
RingFlag := False;
{Required inits in case DonePort is called}
DBuffer := nil;
OBuffer := nil;
fEventBusy := False;
DeletePending := False;
{Create event objects}
ComEvent := CreateEvent(nil, False, False, nil);
ReadyEvent := CreateEvent(nil, False, False, nil);
GeneralEvent := CreateEvent(nil, False, False, nil);
OutputEvent := CreateEvent(nil, False, False, nil);
SentEvent := CreateEvent(nil, True, False, nil);
OutFlushEvent := CreateEvent(nil, False, False, nil);
{wake up xmit thread when it's waiting for data}
OutWaitObjects1[0] := OutputEvent;
OutWaitObjects1[1] := OutFlushEvent;
{wake up xmit thread when it's waiting for i/o completion}
OutWaitObjects2[0] := SentEvent;
OutWaitObjects2[1] := OutFlushEvent;
{Ask Windows to open the comm port}
CidEx := OpenCom(AComName, InSize, OutSize);
if CidEx < 0 then begin
if CidEx = ecOutOfMemory then
Result := ecOutOfMemory
else
Result := -Integer(GetLastError);
DonePort;
Exit;
end;
{set the buffer sizes}
Result := SetCommBuffers(InSize, OutSize);
if Result <> 0 then begin
DonePort;
Exit;
end;
{Allocate dispatch buffer}
DBuffer := AllocMem(DispatchBufferSize);
{Allocate output buffer}
OBuffer := AllocMem(OutSize);
OBufHead := 0;
OBufTail := 0;
OBufFull := False;
{Initialize fields}
InQue := InSize;
OutQue := OutSize;
LastError := 0;
OutSentPending := False;
ClosePending := False;
fDispatcherWindow := 0;
DispatchFull := False;
GetCount := 0;
LastLineErr := 0;
LastModemStatus := 0;
RS485Mode := False;
BaseAddress := 0;
{Assure DCB is up to date in all cases}
GetComState(DCB);
{ Set initial flow control options }
if (FlowOpts and ipAutoDTR) <> 0 then begin
DTRAuto := True;
end else begin
DTRAuto := False;
SetDTR((FlowOpts and ipAssertDTR) <> 0);
end;
if (FlowOpts and ipAutoRTS) <> 0 then begin
RTSAuto := True;
end else begin
RTSAuto := False;
SetRTS((FlowOpts and ipAssertRTS) <> 0);
end;
{Trigger inits}
LastTailData := 0;
LastTailLen := 1;
RemoveAllTriggers;
DBufHead := 0;
DBufTail := 0;
NotifyTail := 0;
ResetStatusHits;
InAvailMessage := False;
ModemStatus := 0;
GetModemStatusPrim($F0);
{Set the requested line parameters}
LastBaud := 115200;
Error := SetLine(Baud, Parity, DataBits, StopBits);
if Error <> ecOk then begin
Result := Error;
DonePort;
Exit;
end;
{Get initial status}
RefreshStatus;
TracingOn := False;
TraceQueue := nil;
TraceIndex := 0;
TraceMax := 0;
TraceWrapped := False;
TimeBase := AdTimeGetTime;
DLoggingOn := False;
DLoggingMax := 0;
{Start the dispatcher}
StartDispatcher;
end;
function TApdBaseDispatcher.InitSocket(Insize, OutSize : Cardinal) : Integer;
begin
Result := ecOK;
{Create a socket}
CidEx := OpenCom(nil, InSize, OutSize);
if CidEx < 0 then begin
Result := -CidEx;
DonePort;
Exit;
end;
{Connect or bind socket}
if not SetupCom(0, 0) then begin
Result := -GetComError(ComStatus);
DonePort;
Exit;
end;
{Allocate dispatch buffer}
DBuffer := AllocMem(DispatchBufferSize);
{Initialize fields}
InQue := InSize;
OutQue := OutSize;
{Trigger inits}
LastTailLen := 1;
{Set default options}
ModemStatus := 0;
{Get initial status}
RefreshStatus;
TimeBase := AdTimeGetTime;
{Start the dispatcher}
StartDispatcher;
end;
function TApdBaseDispatcher.SetCommBuffers(InSize, OutSize : Integer) : Integer;
{-Set the new buffer sizes, win32 only}
begin
if SetupCom(InSize, OutSize) then
Result := ecOK
else
Result := -Integer(GetLastError);
end;
procedure TApdBaseDispatcher.DonePortPrim;
{-Close the port and free the handle}
begin
{Stop dispatcher}
DoDonePortPrim := False; {!!.02}
if DispActive then
StopDispatcher;
{ Free memory for the output buffer }
EnterCriticalSection(DataSection);
try
if OBuffer <> nil then begin
FreeMem(OBuffer);
OBuffer := nil;
end;
{ Free memory for the dispatcher buffer }
if DBuffer <> nil then begin
FreeMem(DBuffer, DispatchBufferSize);
DBuffer := nil;
end;
finally
LeaveCriticalSection(DataSection);
end;
end;
procedure TApdBaseDispatcher.DonePort;
{-Close the port and free the handle}
begin
{Always close the physical port...}
if CidEx >= 0 then begin
{Flush the output queue}
FlushOutBuffer;
FlushInBuffer;
CloseCom;
end;
{...but destroy our object only if not within a notify}
if fEventBusy then begin
ClosePending := True;
end else
DonePortPrim;
end;
function ActualBaud(BaudCode : LongInt) : Longint;
const
BaudTable : array[0..23] of LongInt =
(110, 300, 600, 1200, 2400, 4800, 9600, 14400,
19200, 0, 0, 38400, 0, 0, 0, 56000,
0, 0, 0, 128000, 0, 0, 0, 256000);
var
Index : Cardinal;
Baud : LongInt;
begin
if BaudCode = $FEFF then
{COMM.DRV's 115200 hack}
Result := 115200
else if BaudCode < $FF10 then
{Must be a baud rate, return it}
Result := BaudCode
else begin
{It's a code, look it up}
Index := BaudCode - $FF10;
if Index > 23 then
{Unknown code, just return it}
Result := BaudCode
else begin
Baud := BaudTable[Index];
if Baud = 0 then
{Unknown code, just return it}
Result := BaudCode
else
Result := Baud;
end;
end;
end;
{ Wait till pending Tx Data is sent for H -- used for line parameter }
{ changes -- so the data in the buffer at the time the change is made }
{ goes out under the "old" line parameters. }
procedure TApdBaseDispatcher.WaitTxSent;
var
BitsPerChar : DWORD;
BPS : Longint;
MicroSecsPerBit : DWORD;
MicroSecs : DWORD;
MilliSecs : DWORD;
TxWaitCount : Integer;
begin
{ Wait till our Output Buffer becomes free. }
{ If output hasn't drained in 10 seconds, punt. }
TxWaitCount := 0;
while((OutBuffUsed > 0) and (TxWaitCount < 5000)) do begin
Sleep(2);
Inc(TxWaitCount);
end;
{ Delay based upon a 16-character TX FIFO + 1 character for TX output }
{ register + 1 extra character for slop (= 18). Delay is based upon }
{ 1/bps * (start bit + data bits + parity bit + stop bits). }
GetComState(DCB);
BitsPerChar := DCB.ByteSize + 2; { Bits per Char + 1 start + 1 stop }
if (DCB.Parity <> 0) then
Inc(BitsPerChar);
if (DCB.StopBits <> 0) then
Inc(BitsPerChar);
BPS := ActualBaud(LastBaud);
MicroSecsPerBit := 10000000 div BPS;
MicroSecs := MicroSecsPerBit * BitsPerChar * 18;
if (MicroSecs < 10000) then
MicroSecs := MicroSecs + MicroSecs;
MilliSecs := Microsecs div 10000;
if ((Microsecs mod 10000) <> 0) then
Inc(MilliSecs);
Sleep(MilliSecs);
end;
function TApdBaseDispatcher.SetLine(
Baud : LongInt;
Parity : Cardinal;
DataBits : TDatabits;
StopBits : TStopbits) : Integer;
var
NewBaudRate : DWORD;
NewParity : Cardinal;
NewByteSize : TDatabits;
NewStopBits : Byte;
NewFlags : Longint; // SWB
{-Set or change the line parameters}
begin
Result := ecOK;
EnterCriticalSection(DataSection);
try
{Get current DCB parameters}
GetComState(DCB);
{Set critical default DCB options}
NewFlags := DCB.Flags; // SWB
NewFlags := NewFlags or dcb_Binary; // SWB
NewFlags := NewFlags and not dcb_Parity; // SWB
NewFlags := NewFlags and not dcb_DsrSensitivity; // SWB
NewFlags := NewFlags or dcb_TxContinueOnXoff; // SWB
NewFlags := NewFlags and not dcb_Null; // SWB
NewFlags := NewFlags and not dcb_Null; // SWB
{Validate stopbit range}
if StopBits <> DontChangeStopBits then
if StopBits < 1 then
StopBits := 1
else if StopBits > 2 then
StopBits := 2;
{Determine new line parameters}
if Baud <> DontChangeBaud then begin
NewBaudRate := Baud;
end else
NewBaudRate := DCB.BaudRate;
if Parity <> DontChangeParity then
NewParity := Parity
else
NewParity := DCB.Parity;
NewStopBits := DCB.StopBits;
if DataBits <> DontChangeDataBits then
begin
NewByteSize := DataBits;
if (DataBits = 5) then
NewStopBits := One5StopBits;
end else
NewByteSize := DCB.ByteSize;
if StopBits <> DontChangeStopBits then begin
NewStopBits := StopBitArray[StopBits];
if (NewByteSize = 5) then
NewStopBits := One5StopBits;
end;
finally
LeaveCriticalSection(DataSection);
end;
if ((DCB.BaudRate = NewBaudRate) and
(DCB.Parity = NewParity) and
(DCB.ByteSize = NewByteSize) and
(DCB.StopBits = NewStopBits) and // SWB
(DCB.Flags = NewFlags)) then // SWB
Exit;
{ wait for the chars to be transmitted, don't want to change line }
{ settings while chars are pending }
WaitTxSent;
EnterCriticalSection(DataSection);
try
{Get current DCB parameters}
GetComState(DCB);
{Change the parameters}
DCB.BaudRate := NewBaudRate;
DCB.Parity := NewParity;
DCB.ByteSize := NewByteSize;
DCB.StopBits := NewStopBits;
DCB.Flags := NewFlags; // SWB
{Set line parameters}
Result := SetCommStateFix(DCB);
finally
LeaveCriticalSection(DataSection);
end;
end;
procedure TApdBaseDispatcher.GetLine(
var Baud : LongInt;
var Parity : Word;
var DataBits : TDatabits;
var StopBits : TStopbits);
{-Return line parameters}
begin
EnterCriticalSection(DataSection);
try
{Get current DCB parameters}
GetComState(DCB);
{Return the line parameters}
Baud := ActualBaud(DCB.Baudrate);
Parity := DCB.Parity;
DataBits := DCB.ByteSize;
if DCB.StopBits = OneStopBit then
StopBits := 1
else
StopBits := 2;
finally
LeaveCriticalSection(DataSection);
end;
end;
function TApdBaseDispatcher.SetModem(Dtr, Rts : Boolean) : Integer;
{-Set modem control lines, Dtr and Rts}
begin
Result := SetDtr(Dtr);
if Result = ecOK then
Result := SetRts(Rts); {!!.02}
end;
function TApdBaseDispatcher.SetDtr(OnOff : Boolean) : Integer;
{-Set DTR modem control line}
begin
if DtrAuto then begin
{ We can't change DTR if we're controlling it automatically }
Result := 1;
Exit;
end;
if (OnOff = True) then
Result := EscapeComFunction(Windows.SETDTR)
else
Result := EscapeComFunction(Windows.CLRDTR);
if (Result < ecOK) then
Result := ecBadArgument;
DTRState := OnOff;
end;
function TApdBaseDispatcher.SetRts(OnOff : Boolean) : Integer;
{-Set RTS modem control line}
begin
if RtsAuto then begin
{ We can't change RTS if we're controlling it automatically }
Result := 1;
Exit;
end;
if (OnOff = True) then
Result := EscapeComFunction(Windows.SETRTS)
else
Result := EscapeComFunction(Windows.CLRRTS);
if (Result < ecOK) then
Result := ecBadArgument;
RTSState := OnOff;
end;
function TApdBaseDispatcher.GetModemStatusPrim(ClearMask : Byte) : Byte;
{-Primitive to return the modem status and clear mask}
var
Data : DWORD;
begin
{Get the new absolute values}
// There is no reason for this to be inside the critical section // SWB
// and since this can be a very slow function when using mapped // SWB
// comm ports under Citrix or W2K3 I moved it out here. // SWB
GetCommModemStatus(CidEx, Data); // SWB
EnterCriticalSection(DataSection);
try
ModemStatus := (ModemStatus and $0F) or Byte(Data);
{Special case, transfer RI bit to TERI bit}
if RingFlag then begin
RingFlag := False;
ModemStatus := ModemStatus or $04;
end;
{Return the current ModemStatus value}
Result := Lo(ModemStatus);
{Clear specified delta bits}
ModemStatus := ModemStatus and Clearmask;
finally
LeaveCriticalSection(DataSection);
end;
end;
function TApdBaseDispatcher.GetModemStatus : Byte;
{-Return the modem status byte and clear the delta bits}
begin
Result := GetModemStatusPrim(ClearDelta);
end;
function TApdBaseDispatcher.CheckCTS : Boolean;
{-Returns True if CTS is high}
begin
Result := GetModemStatusPrim(ClearDeltaCTS) and CTSMask = CTSMask;
end;
function TApdBaseDispatcher.CheckDSR : Boolean;
{-Returns True if DSR is high}
begin
Result := GetModemStatusPrim(ClearDeltaDSR) and DSRMask = DSRMask;
end;
function TApdBaseDispatcher.CheckRI : Boolean;
{-Returns True if RI is high}
begin
Result := GetModemStatusPrim(ClearDeltaRI) and RIMask = RIMask;
end;
function TApdBaseDispatcher.CheckDCD : Boolean;
{-Returns True if DCD is high}
begin
Result := GetModemStatusPrim(ClearDeltaDCD) and DCDMask = DCDMask;
end;
function TApdBaseDispatcher.CheckDeltaCTS : Boolean;
{-Returns True if DeltaCTS is high}
begin
Result := GetModemStatusPrim(ClearDeltaCTS) and DeltaCTSMask = DeltaCTSMask;
end;
function TApdBaseDispatcher.CheckDeltaDSR : Boolean;
{-Returns True if DeltaDSR is high}
begin
Result := GetModemStatusPrim(ClearDeltaDSR) and DeltaDSRMask = DeltaDSRMask;
end;
function TApdBaseDispatcher.CheckDeltaRI : Boolean;
{-Returns True if DeltaRI is high}
begin
Result := GetModemStatusPrim(ClearDeltaRI) and DeltaRIMask = DeltaRIMask;
end;
function TApdBaseDispatcher.CheckDeltaDCD : Boolean;
{-Returns True if DeltaDCD is high}
begin
Result := GetModemStatusPrim(ClearDeltaDCD) and DeltaDCDMask = DeltaDCDMask;
end;
function TApdBaseDispatcher.GetLineError : Integer;
{-Return current line errors}
const
AllErrorMask = ce_RxOver +
ce_Overrun + ce_RxParity + ce_Frame;
var
GotError : Boolean;
begin
EnterCriticalSection(DataSection);
try
GotError := True;
if (LastError = -1) then // SWB
Result := leIOError // SWB
else if FlagIsSet(LastError, ce_RxOver) then
Result := leBuffer
else if FlagIsSet(LastError, ce_Overrun) then
Result := leOverrun
else if FlagIsSet(LastError, ce_RxParity) then
Result := leParity
else if FlagIsSet(LastError, ce_Frame) then
Result := leFraming
else if FlagIsSet(LastError, ce_Break) then
Result := leBreak
else begin
GotError := False;
Result := leNoError;
end;
{Clear all error flags}
if GotError then // SWB
if (LastError = -1) then // SWB
LastError := 0 // SWB
else // SWB
LastError := LastError and not AllErrorMask; // SWB
finally
LeaveCriticalSection(DataSection);
end;
end;
function TApdBaseDispatcher.CheckLineBreak : Boolean;
begin
EnterCriticalSection(DataSection);
try
Result := FlagIsSet(LastError, ce_Break);
LastError := LastError and not ce_Break;
finally
LeaveCriticalSection(DataSection);
end;
end;
procedure TApdBaseDispatcher.SendBreak(Ticks : Cardinal; Yield : Boolean);
{Send a line break of Ticks ticks, with yields}
begin
{ raise RTS for RS485 mode }
if RS485Mode then {!!.01}
SetRTS(True); {!!.01}
SetCommBreak(CidEx);
DelayTicks(Ticks, Yield);
ClearCommBreak(CidEx);
{ lower RTS only if the output buffer is empty }
if RS485Mode and (OutBuffUsed = 0) then {!!.01}
SetRTS(False); {!!.01}
end;
procedure TApdBaseDispatcher.SetBreak(BreakOn: Boolean);
{Sets or clears line break condition}
begin
if BreakOn then begin {!!.01}
if RS485Mode then {!!.01}
SetRTS(True); {!!.01}
SetCommBreak(CidEx)
end else begin {!!.01}
ClearCommBreak(CidEx);
if RS485Mode and (OutBuffUsed = 0) then {!!.01}
SetRTS(False); {!!.01}
end; {!!.01}
end;
function TApdBaseDispatcher.CharReady : Boolean;
{-Return True if at least one character is ready at the device driver}
var
NewTail : Cardinal;
begin
EnterCriticalSection(DispSection);
try
if InAvailMessage then begin
NewTail := DBufTail + GetCount;
if NewTail >= DispatchBufferSize then
Dec(NewTail, DispatchBufferSize);
Result := (DBufHead <> NewTail)
or (DispatchFull and (GetCount < DispatchBufferSize));
end else
Result := (DBufHead <> DBufTail) or DispatchFull;
finally
LeaveCriticalSection(DispSection);
end;
end;
function TApdBaseDispatcher.PeekCharPrim(var C : AnsiChar; Count : Cardinal) : Integer;
{-Return the Count'th character but don't remove it from the buffer}
var
NewTail : Cardinal;
InCount : Cardinal;
begin
Result := ecOK;
EnterCriticalSection(DispSection);
try
if DBufHead > DBufTail then
InCount := DBufHead-DBufTail
else if DBufHead <> DBufTail then
InCount := ((DBufHead+DispatchBufferSize)-DBufTail)
else if DispatchFull then
InCount := DispatchBufferSize
else
InCount := 0;
if InCount >= Count then begin
{Calculate index of requested character}
NewTail := DBufTail + (Count - 1);
if NewTail >= DispatchBufferSize then
NewTail := (NewTail - DispatchBufferSize);
// C := DBuffer^[NewTail];
C := PAnsiChar( AddWordToPtr( DBuffer, NewTail))^;
end else
Result := ecBufferIsEmpty;
finally
LeaveCriticalSection(DispSection);
end;
end;
function TApdBaseDispatcher.PeekChar(var C : AnsiChar; Count : Cardinal) : Integer;
{-Return the Count'th character but don't remove it from the buffer}
{-Account for GetCount}
begin
EnterCriticalSection(DispSection);
try
if InAvailMessage then
Inc(Count, GetCount);
Result := PeekCharPrim(C, Count);
finally
LeaveCriticalSection(DispSection);
end;
end;
function TApdBaseDispatcher.GetChar(var C : AnsiChar) : Integer;
{-Return next char and remove it from buffer}
begin
EnterCriticalSection(DispSection);
try
{If within an apw_TriggerAvail message then do not physically }
{extract the character. It will be removed by the dispatcher after }
{all trigger handlers have seen it. If not within an }
{apw_TriggerAvail message then physically extract the character }
if InAvailMessage then begin
Inc(GetCount);
Result := PeekCharPrim(C, GetCount);
if Result < ecOK then begin
Dec(GetCount);
Exit;
end;
end else begin
Result := PeekCharPrim(C, 1);
if Result >= ecOK then begin
{Increment the tail index}
Inc(DBufTail);
if DBufTail = DispatchBufferSize then
DBufTail := 0;
DispatchFull := False;
end;
end;
if TracingOn
and (Result >= ecOK) then
AddTraceEntry('R', C);
finally
LeaveCriticalSection(DispSection);
end;
end;
function TApdBaseDispatcher.PeekBlockPrim(Block : PAnsiChar;
Offset : Cardinal; Len : Cardinal; var NewTail : Cardinal) : Integer;
{-Return Block from ComPort, return new tail value}
var
Count : Cardinal;
EndCount : Cardinal;
BeginCount : Cardinal;
begin
EnterCriticalSection(DispSection);
try
{Get count}
Count := BuffCount(DBufHead, DBufTail, DispatchFull);
{Set new tail value}
NewTail := DBufTail + Offset;
if NewTail >= DispatchBufferSize then
Dec(NewTail, DispatchBufferSize);
if Count >= Len then begin
{Set begin/end buffer counts}
if NewTail+Len < DispatchBufferSize then begin
EndCount := Len;
BeginCount := 0;
end else begin
EndCount := (DispatchBufferSize-NewTail);
BeginCount := Len-EndCount;
end;
if EndCount <> 0 then begin
{Move data from end of dispatch buffer}
Move( GetPtr(DBuffer, NewTail)^, Pointer(Block)^, SizeOf( EndCount)); // --sm check
Inc(NewTail, EndCount);
end;
if BeginCount <> 0 then begin
{Move data from beginning of dispatch buffer}
Move(DBuffer^,
GetPtr(Block, EndCount+1)^,
SizeOf( BeginCount)); // --sm check
NewTail := BeginCount;
end;
{Wrap newtail}
if NewTail = DispatchBufferSize then
NewTail := 0;
Result := Len;
end else
Result := ecBufferIsEmpty;
finally
LeaveCriticalSection(DispSection);
end;
end;
function TApdBaseDispatcher.PeekBlock(Block : PAnsiChar; Len : Cardinal) : Integer;
{-Return Block from ComPort but don't set new tail value}
var
Tail : Cardinal;
Offset : Cardinal;
begin
EnterCriticalSection(DispSection);
try
{Get block}
if InAvailMessage then
Offset := GetCount
else
Offset := 0;
Result := PeekBlockPrim(Block, Offset, Len, Tail);
finally
LeaveCriticalSection(DispSection);
end;
end;
function TApdBaseDispatcher.GetBlock(Block : PAnsiChar; Len : Cardinal) : Integer;
{-Get Block from ComPort and set new tail}
var
Tail : Cardinal;
I : Cardinal;
begin
EnterCriticalSection(DispSection);
try
{ If within an apw_TriggerAvail message then do not physically }
{ extract the data. It will be removed by the dispatcher after }
{ all trigger handlers have seen it. If not within an }
{ apw_TriggerAvail message, then physically extract the data }
if InAvailMessage then begin
Result := PeekBlockPrim(Block, GetCount, Len, Tail);
if Result > 0 then
Inc(GetCount, Result);
end else begin
Result := PeekBlockPrim(Block, 0, Len, Tail);
if Result > 0 then begin
DBufTail := Tail;
DispatchFull := False;
end;
end;
finally
LeaveCriticalSection(DispSection);
end;
EnterCriticalSection(DataSection);
try
if TracingOn and (Result > 0) then
for I := 0 to Result-1 do
AddTraceEntry('R', Block[I]);
finally
LeaveCriticalSection(DataSection);
end;
end;
function TApdBaseDispatcher.PutChar(C : AnsiChar) : Integer;
{-Route through PutBlock to transmit a single character}
begin
Result := PutBlock(C, 1);
end;
function TApdBaseDispatcher.PutString(S : AnsiString) : Integer;
{-Send as a block}
begin
Result := PutBlock(S[1], Length(S));
end;
procedure TApdBaseDispatcher.AddStringToLog(S : Ansistring);
begin
if DLoggingOn then
AddDispatchEntry(dtUser, dstNone, 0, @S[1], length(S) * SizeOf(AnsiChar))
end;
function TApdBaseDispatcher.PutBlock(const Block; Len : Cardinal) : Integer;
{-Send Block to CommPort}
var
Avail : Cardinal;
I : Cardinal;
CharsOut : Integer; {Chars transmitted from last block}
begin
{Exit immediately if nothing to do}
Result := ecOK;
if Len = 0 then
Exit;
EnterCriticalSection(OutputSection);
try
{ Is there enough free space in the outbuffer? }
{LastError := GetComError(ComStatus); // SWB
Avail := OutQue - ComStatus.cbOutQue;} // SWB
// The old method of determining available space in the output buffer // SWB
// was agonizingly slow when using mapped com ports under Citrix or // SWB
// Windows 2003. Replaced call to GetComError with a call that // SWB
// returns only the used buffer space. // SWB
Avail := OutQue - OutBufUsed; // SWB
if Avail < Len then begin
Result := ecOutputBufferTooSmall;
Exit;
end;
if Avail = Len then
OBufFull := True;
{ Raise RTS if in RS485 mode. In 32bit mode it will be lowered }
{ by the output thread. }
if Win32Platform <> VER_PLATFORM_WIN32_NT then
if RS485Mode then begin
if BaseAddress = 0 then begin
Result := ecBaseAddressNotSet;
Exit;
end;
SetRTS(True);
end;
{Send the data}
CharsOut := WriteCom(PAnsiChar(@Block), Len);
if CharsOut <= 0 then begin
CharsOut := Abs(CharsOut);
Result := ecPutBlockFail;
LastError := GetComError(ComStatus);
end;
{Flag output trigger}
OutSentPending := True;
finally
LeaveCriticalSection(OutputSection);
end;
EnterCriticalSection(DataSection);
try
if DLoggingOn then
if CharsOut = 0 then
AddDispatchEntry(dtDispatch, dstWriteCom, 0, nil, 0)
else
AddDispatchEntry(dtDispatch, dstWriteCom, CharsOut,
PAnsiChar(@Block), CharsOut);
if TracingOn and (CharsOut <> 0) then
for I := 0 to CharsOut-1 do
AddTraceEntry('T', PAnsiChar(@Block)[I]);
finally
LeaveCriticalSection(DataSection);
end;
end;
function TApdBaseDispatcher.InBuffUsed : Cardinal;
{-Return number of bytes currently in input buffer}
begin
EnterCriticalSection(DispSection);
try
if DBufHead = DBufTail then
if DispatchFull then
Result := DispatchBufferSize
else
Result := 0
else if DBufHead > DBufTail then
Result := DBufHead-DBufTail
else
Result := (DBufHead+DispatchBufferSize)-DBufTail;
if InAvailMessage then
{In apw_TriggerAvail message so reduce by retrieved chars}
Dec(Result, GetCount);
finally
LeaveCriticalSection(DispSection);
end;
end;
function TApdBaseDispatcher.InBuffFree : Cardinal;
{-Return number of bytes free in input buffer}
begin
EnterCriticalSection(DispSection);
try
if DBufHead = DBufTail then
if DispatchFull then
Result := 0
else
Result := DispatchBufferSize
else if DBufHead > DBufTail then
Result := (DBufTail+DispatchBufferSize)-DBufHead
else
Result := DBufTail-DBufHead;
if InAvailMessage then
{In apw_TriggerAvail message so reduce by retrieved chars}
Inc(Result, GetCount);
finally
LeaveCriticalSection(DispSection);
end;
end;
function TApdBaseDispatcher.OutBuffUsed : Cardinal;
{-Return number of bytes currently in output buffer}
begin
EnterCriticalSection(OutputSection);
try
RefreshStatus;
Result := ComStatus.cbOutQue;
finally
LeaveCriticalSection(OutputSection);
end;
end;
function TApdBaseDispatcher.OutBuffFree : Cardinal;
{-Return number of bytes free in output buffer}
begin
EnterCriticalSection(OutputSection);
try
RefreshStatus;
Result := OutQue - ComStatus.cbOutQue;
finally
LeaveCriticalSection(OutputSection);
end;
end;
function TApdBaseDispatcher.FlushOutBuffer : Integer;
{-Flush the output buffer}
begin
Result := FlushCom(0);
end;
function TApdBaseDispatcher.FlushInBuffer : Integer;
begin
EnterCriticalSection(DispSection);
try
{Flush COMM buffer}
Result := FlushCom(1);
{Flush the dispatcher's buffer}
if InAvailMessage then
MaxGetCount := BuffCount(DBufHead, DBufTail, DispatchFull)
else begin
DBufTail := DBufHead;
GetCount := 0;
end;
DispatchFull := False;
{Reset data triggers}
ResetDataTriggers;
finally
LeaveCriticalSection(DispSection);
end;
end;
procedure TApdBaseDispatcher.BufferSizes(var InSize, OutSize : Cardinal);
{-Return buffer sizes}
begin
InSize := InQue;
OutSize := OutQue;
end;
function TApdBaseDispatcher.HWFlowOptions(
BufferFull, BufferResume : Cardinal;
Options : Cardinal) : Integer;
{-Turn on hardware flow control}
begin
{Validate the buffer points}
if (BufferResume > BufferFull) or
(BufferFull > InQue) then begin
Result := ecBadArgument;
Exit;
end;
EnterCriticalSection(DataSection);
try
GetComState(DCB);
with DCB do begin
Flags := Flags and not (AllHdwFlow);
Flags := Flags and not (dcb_DTRBit1 or dcb_RTSBit1);
DtrAuto := False;
RtsAuto := False;
{Receive flow control, set requested signal(s)}
if FlagIsSet(Options, hfUseDtr) then begin
Flags := Flags or dcb_DTR_CONTROL_HANDSHAKE;
DtrAuto := True;
end else begin
{ If static DTR wanted }
if DTRState then
{ then assert DTR }
Flags := Flags or dcb_DTR_CONTROL_ENABLE;
end;
if FlagIsSet(Options, hfUseRts) then begin
Flags := Flags or dcb_RTS_CONTROL_HANDSHAKE;
RtsAuto := True;
end else begin
{ If static RTS wanted }
if RTSState then
{ then assert RTS }
Flags := Flags or dcb_RTS_CONTROL_ENABLE;
end;
if RS485Mode and (Win32Platform = VER_PLATFORM_WIN32_NT) then begin
Flags := Flags or dcb_RTS_CONTROL_TOGGLE;
RtsAuto := True;
end;
{Set receive flow buffer limits}
XoffLim := InQue - BufferFull;
XonLim := BufferResume;
{Transmit flow control, set requested signal(s)}
if FlagIsSet(Options, hfRequireDsr) then
Flags := Flags or dcb_OutxDsrFlow;
if FlagIsSet(Options, hfRequireCts) then
Flags := Flags or dcb_OutxCtsFlow;
{Set new DCB}
Result := SetCommStateFix(DCB);
end;
finally
LeaveCriticalSection(DataSection);
end;
end;
function TApdBaseDispatcher.HWFlowState : Integer;
{-Returns state of flow control}
begin
with DCB do begin
EnterCriticalSection(DataSection);
try
if not FlagIsSet(Flags, AllHdwFlow) then begin
Result := fsOff;
Exit;
end else
Result := fsOn;
if Flags and InHdwFlow <> 0 then begin
{Get latest flow status}
RefreshStatus;
{Set appropriate flow state}
if (Flags and dcb_OutxDsrFlow <> 0) and
(fDsrHold in ComStatus.Flags) then
Result := fsDsrHold;
if (Flags and dcb_OutxCtsFlow <> 0) and
(fCtlHold in ComStatus.Flags) then
Result := fsCtsHold;
end;
finally
LeaveCriticalSection(DataSection);
end;
end;
end;
function TApdBaseDispatcher.SWFlowEnable(
BufferFull, BufferResume : Cardinal;
Options : Cardinal) : Integer;
{-Turn on software flow control}
begin
{Validate the buffer points}
if (BufferResume > BufferFull) or
(BufferFull > InQue) then begin
Result := ecBadArgument;
Exit;
end;
EnterCriticalSection(DataSection);
try
{ Make sure we have an up-to-date DCB }
GetComState(DCB);
with DCB do begin
if FlagIsSet(Options, sfReceiveFlow) then begin
{Receive flow control}
Flags := Flags or dcb_InX;
{Set receive flow buffer limits}
XoffLim := InQue - BufferFull;
XonLim := BufferResume;
{Set flow control characters}
XOnChar := cXon;
XOffChar := cXoff;
end;
if FlagIsSet(Options, sfTransmitFlow) then begin
{Transmit flow control}
Flags := Flags or dcb_OutX;
{Set flow control characters}
XOnChar := cXon;
XOffChar := cXoff;
end;
{Set new DCB}
Result := SetCommStateFix(DCB);
end;
finally
LeaveCriticalSection(DataSection);
end;
end;
function TApdBaseDispatcher.SWFlowDisable : Integer;
{-Turn off all software flow control}
begin
with DCB do begin
EnterCriticalSection(DataSection);
try
{ Make sure we have an up-to-date DCB }
GetComState(DCB);
Flags := Flags and not AllSfwFlow;
Result := SetCommStateFix(DCB);
finally
LeaveCriticalSection(DataSection);
end;
end;
end;
function TApdBaseDispatcher.SWFlowState : Integer;
{-Returns state of flow control}
begin
with DCB do begin
EnterCriticalSection(DataSection);
try
if FlagIsSet(Flags, dcb_InX) or FlagIsSet(Flags, dcb_OutX) then
Result := fsOn
else begin
Result := fsOff;
Exit;
end;
{Get latest flow status}
RefreshStatus;
{Set appropriate flow state}
if (fXoffHold in ComStatus.Flags) then
if (fXoffSent in ComStatus.Flags) then
Result := fsXBothHold
else
Result := fsXOutHold
else if (fXoffSent in ComStatus.Flags) then
Result := fsXInHold;
finally
LeaveCriticalSection(DataSection);
end;
end;
end;
function TApdBaseDispatcher.SWFlowChars(OnChar, OffChar : AnsiChar) : Integer;
{-Set on/off chars for software flow control}
begin
with DCB do begin
EnterCriticalSection(DataSection);
try
{ Make sure we have an up-to-date DCB }
GetComState(DCB);
{Set flow control characters}
XOnChar := OnChar;
XOffChar := OffChar;
Result := SetCommStateFix(DCB);
finally
LeaveCriticalSection(DataSection);
end;
end;
end;
function TApdBaseDispatcher.SendNotify(Msg, Trigger, Data: Cardinal) : Boolean;
{-Send trigger messages, return False to stop checking triggers}
var
lParam : DWORD;
Res : DWORD;
i : Integer;
begin
Result := True;
if not HandlerServiceNeeded then Exit;
{Don't let dispatcher change anything while sending messages}
EnterCriticalSection(DataSection);
try
fEventBusy := True;
finally
LeaveCriticalSection(DataSection);
end;
try
MaxGetCount := 0;
{Flag apw_TriggerAvail messages}
InAvailMessage := (Msg = apw_TriggerAvail) or (Msg = apw_TriggerData);
{Clear trigger handle modification flags}
lParam := (DWORD(fHandle) shl 16) + Data;
for i := 0 to pred(EventTriggerHandlers.Count) do
with PEventTriggerHandler(EventTriggerHandlers[i])^ do begin
GetCount := 0;
if not thDeleted then
if thSync then
DispThread.SyncNotify(Msg,Trigger,lParam,thNotify)
else
thNotify(Msg, Trigger, lParam);
if ClosePending then begin
{Port was closed by event handler, bail out}
Result := False;
Exit;
end;
{Note deepest look at input buffer}
if GetCount > MaxGetCount then
MaxGetCount := GetCount;
end;
for i := 0 to pred(ProcTriggerHandlers.Count) do
with PProcTriggerHandler(ProcTriggerHandlers[i])^ do begin
GetCount := 0;
if not thDeleted and (@thNotify <> nil) then
thNotify(Msg, Trigger, lParam);
if ClosePending then begin
{Port was closed by event handler, bail out}
Result := False;
Exit;
end;
{Note deepest look at input buffer}
if GetCount > MaxGetCount then
MaxGetCount := GetCount;
end;
if (WndTriggerHandlers.Count > 1) or PortHandlerInstalled then
for i := 0 to pred(WndTriggerHandlers.Count) do
with PWndTriggerHandler(WndTriggerHandlers[i])^ do begin
GetCount := 0;
if not thDeleted then
SendMessageTimeout(thWnd, Msg, Trigger, lParam,
SMTO_BLOCK, 3000, Res);
if ClosePending then begin
{Port was closed by event handler, bail out}
Result := False;
Exit;
end;
{Note deepest look at input buffer}
if GetCount > MaxGetCount then
MaxGetCount := GetCount;
end;
{ If in apw_TriggerAvail message remove the data now }
if InAvailMessage then begin
EnterCriticalSection(DispSection);
try
InAvailMessage := False;
Inc(DBufTail, MaxGetCount);
if DBufTail >= DispatchBufferSize then
Dec(DBufTail, DispatchBufferSize);
if MaxGetCount <> 0 then
DispatchFull := False;
{Force CheckTriggers to exit if another avail msg is pending}
{Note: for avail msgs, trigger is really the byte count}
if (Msg = apw_TriggerAvail) and (MaxGetCount <> Trigger) then
Result := False;
finally
LeaveCriticalSection(DispSection);
end;
end;
finally
EnterCriticalSection(DataSection);
try
fEventBusy := False;
if DeletePending then begin
for i := pred(WndTriggerHandlers.Count) downto 0 do
if PWndTriggerHandler(WndTriggerHandlers[i])^.thDeleted then begin
Dispose(PWndTriggerHandler(WndTriggerHandlers[i]));
WndTriggerHandlers.Delete(i);
end;
for i := pred(ProcTriggerHandlers.Count) downto 0 do
if PProcTriggerHandler(ProcTriggerHandlers[i])^.thDeleted then begin
Dispose(PProcTriggerHandler(ProcTriggerHandlers[i]));
ProcTriggerHandlers.Delete(i);
end;
for i := pred(EventTriggerHandlers.Count) downto 0 do
if PEventTriggerHandler(EventTriggerHandlers[i])^.thDeleted then begin
Dispose(PEventTriggerHandler(EventTriggerHandlers[i]));
EventTriggerHandlers.Delete(i);
end;
DeletePending := False;
UpdateHandlerFlags(fuKeepPort);
end;
finally
LeaveCriticalSection(DataSection);
end;
end;
GetCount := 0;
end;
function MatchString(var Indexes : TCheckIndex; const C : AnsiChar; Len : Cardinal;
P : PAnsiChar; IgnoreCase : Boolean) : Boolean;
{-Checks for string P on consecutive calls, returns True when found}
var
I : Cardinal;
Check : Boolean;
GotFirst : Boolean;
begin
Result := False;
if IgnoreCase then
AnsiUpperBuff(@C, 1);
GotFirst := False;
Check := True;
for I := 0 to Len-1 do begin
{Check another index?}
if Check then begin
{Compare this index...}
if C = P[Indexes[I]] then // -- sm wants to modified this (SZ disagrees) => if C = P[Indexes[I]*PayloadLengthInBytes(P)] then
{Got match, was it complete?}
if Indexes[I] = Len-1 then begin
Indexes[I] := 0;
Result := True;
{Clear all inprogress matches}
FillChar(Indexes, SizeOf(Indexes), 0);
end else
Inc(Indexes[I])
else
{No match, reset index}
if C = P[0] then begin
GotFirst := True;
Indexes[I] := 1
end else
Indexes[I] := 0;
end;
{See if last match was on first char}
if Indexes[I] = 1 then
GotFirst := True;
{See if we should check the next index}
if I <> Len-1 then
if GotFirst then
{Got a previous restart, don't allow more restarts}
Check := Indexes[I+1] <> 0
else
{Not a restart, check next index if in progress or on first char}
Check := (Indexes[I+1] <> 0) or (C = P[0])
else
Check := False;
end;
end;
function TApdBaseDispatcher.CheckStatusTriggers : Boolean;
{-Check status triggers for H, send notification messages as required}
{-Return True if more checks remain}
var
J : Integer;
Hit : Cardinal;
StatusLen : Cardinal;
Res : Byte;
BufCnt : Cardinal;
begin
{Check status triggers}
for J := 0 to pred(StatusTriggers.Count) do begin
with PStatusTrigger(StatusTriggers[J])^ do begin
if tSActive and not StatusHit then begin
Hit := stNotActive;
StatusLen := 0;
case tSType of
stLine :
if LastError and tValue <> 0 then begin
Hit := stLine;
tValue := LastError;
end;
stModem :
begin
{Check for changed bits}
Res := Lo(tValue) xor ModemStatus;
{Skip bits not in our mask}
Res := Res and Hi(tValue);
{If anything is still set, it's a hit}
if Res <> 0 then begin
Hit := stModem;
end;
end;
stOutBuffFree :
begin
BufCnt := OutBuffFree;
if BufCnt >= tValue then begin
StatusLen := BufCnt;
Hit := stOutBuffFree;
end;
end;
stOutBuffUsed :
begin
BufCnt := OutBuffUsed;
if BufCnt <= tValue then begin
StatusLen := BufCnt;
Hit := stOutBuffUsed;
end;
end;
stOutSent :
if OutSentPending then begin
OutSentPending := False;
StatusLen := 0;
Hit := stOutSent;
end;
end;
if Hit <> stNotActive then begin
{Clear the trigger and send the notification message}
tSActive := False;
{Prevent status trigger re-entrancy issues}
GlobalStatHit := True;
StatusHit := True;
if DLoggingOn then
AddDispatchEntry(dtTrigger, dstStatus, tHandle, nil, 0);
Result :=
SendNotify(apw_TriggerStatus, tHandle, StatusLen);
Exit;
end;
end;
end;
if J >= StatusTriggers.Count then break;
end;
{No more checks required}
Result := False;
end;
function TApdBaseDispatcher.CheckReceiveTriggers : Boolean;
{-Check all receive triggers for H, send notification messages as required}
{-Return True if more checks remain}
type
LH = record L,H : Byte; end;
var
I : Cardinal;
J : Integer;
BufCnt : Cardinal;
MatchSize : Cardinal;
CC : Cardinal;
AnyMatch : Boolean;
C : AnsiChar;
function CharCount(CurTail, Adjust : Cardinal) : Cardinal;
{-Return the number of characters available between CurTail }
{ and DBufTail that haven't already been extracted. CurTail }
{ is first adjusted downward by Adjust, the size of the }
{ current match string }
begin
if Adjust <= CurTail then
Dec(CurTail, Adjust)
else
CurTail := (CurTail + DispatchBufferSize) - Adjust;
Result := BuffCount(CurTail, DBufTail, DispatchFull) + 1;
if InAvailMessage then
Dec(Result, GetCount);
end;
begin
{Assume triggers need to be re-checked}
Result := True;
I := LastTailData;
{Check data triggers}
if LastTailData <> DBufHead then begin
{Prepare}
{Loop through new data in dispatch buffer}
while I <> DBufHead do begin
// C := DBuffer^[I];
C := PAnsiChar( AddWordToPtr( DBuffer, I))^;
{Check each trigger for a match on this character}
AnyMatch := False;
MatchSize := 0;
for J := 0 to pred(DataTriggers.Count) do
with PDataTrigger(DataTriggers[J])^ do
if tLen <> 0 then begin
tMatched := tMatched or
MatchString(tChkIndex, C, tLen, tData, tIgnoreCase);
if tMatched and (tLen > MatchSize) then
MatchSize := tLen;
if not AnyMatch then
AnyMatch := tMatched;
end;
{Send len message if we have any matches}
if AnyMatch then begin
{Send len message up to first matching char}
if (LenTrigger <> 0) and
(NotifyTail <> I) and
(LongInt(CharCount(I, 0))-
LongInt(MatchSize) >= LongInt(LenTrigger))
then begin
{Generate len message for preceding data}
CC := CharCount(I, MatchSize);
if DLoggingOn then
AddDispatchEntry(dtTrigger, dstAvail, CC, nil, 0);
Result := SendNotify(apw_TriggerAvail, CC, 0);
LastTailData := I;
NotifyTail := I;
end;
{Process the matches}
for J := pred(DataTriggers.Count) downto 0 do begin
with PDataTrigger(DataTriggers[J])^ do
if tMatched then begin
{No preceding data or msg pending, send data msg}
if DLoggingOn then
AddDispatchEntry(dtTrigger, dstData, tHandle, nil, 0);
tMatched := False;
Result :=
SendNotify(apw_TriggerData, tHandle, tLen);
end;
if J >= DataTriggers.Count then break;
end;
{Exit after all data triggers that matched on this char}
if I = DispatchBufferSize-1 then
LastTailData := 0
else
LastTailData := I+1;
Exit;
end;
{Next index for buffer}
if I = DispatchBufferSize-1 then
I := 0
else
inc(I);
end;
{Update last tail for data triggers}
LastTailData := I;
end;
{Check for length trigger}
BufCnt := InBuffUsed;
if (LenTrigger <> 0) and
(NotifyTail <> I) and
(BufCnt >= LenTrigger) then begin
if DLoggingOn then
AddDispatchEntry(dtTrigger, dstAvail, BufCnt, nil, 0);
Result :=
SendNotify(apw_TriggerAvail, BufCnt, 0);
NotifyTail := I;
Exit;
end;
{No more checks required}
Result := False;
end;
function TApdBaseDispatcher.CheckTimerTriggers : Boolean;
{-Check timer triggers for H, send notification messages as required}
{-Return True if more checks remain}
var
J : Integer;
begin
{Check for timer triggers}
for J := 0 to pred(TimerTriggers.Count) do begin
with PTimerTrigger(TimerTriggers[J])^ do
if tActive and TimerExpired(tET) then begin
tActive := False;
if DLoggingOn then
AddDispatchEntry(dtTrigger, dstTimer, tHandle, nil, 0);
Result := SendNotify(apw_TriggerTimer, tHandle, 0);
Exit;
end;
if J >= TimerTriggers.Count then break;
end;
{No more checks required}
Result := False;
end;
function TApdBaseDispatcher.ExtractData : Boolean;
{-Move data from communications driver to dispatch buffer}
{-Return True if data available, false otherwise}
var
BytesToRead : Cardinal;
FreeSpace : Cardinal;
BeginFree : Cardinal;
EndFree : Cardinal;
Len : Integer;
begin
EnterCriticalSection(DispSection);
try
{Nothing to do if dispatch buffer is already full}
if DispatchFull then begin
if (DLoggingOn) then // SWB
AddDispatchEntry(dtDispatch, // SWB
dstStatus, // SWB
0, // SWB
PAnsiChar('Dispatch buffer full.'), // SWB
21); // SWB
Result := True;
Exit;
end;
{$IFDEF UseAwWin32} // SWB
RefreshStatus; // SWB
{$ELSE} // SWB
ComStatus.cbInQue := InQueueUsed; // SWB
{$ENDIF} // UseAwWin32 // SWB
if ComStatus.cbInQue > 0 then begin
Result := True;
if DBufHead = DBufTail then begin
{Buffer is completely empty}
FreeSpace := DispatchBufferSize;
EndFree := DispatchBufferSize-DBufHead;
end else if DBufHead > DBufTail then begin
{Buffer not wrapped}
FreeSpace := (DBufTail+DispatchBufferSize)-DBufHead;
EndFree := DispatchBufferSize-DBufHead;
end else begin
{Buffer is wrapped}
FreeSpace := DBufTail-DBufHead;
EndFree := DBufTail-DBufHead;
end;
{Figure out how much data to read}
if ComStatus.cbInQue > FreeSpace then begin
BytesToRead := FreeSpace;
end else begin
BytesToRead := ComStatus.cbInQue;
end;
{Figure where data fits (end and/or beginning of buffer)}
if BytesToRead > EndFree then
BeginFree := BytesToRead-EndFree
else
BeginFree := 0;
{Move data to end of dispatch buffer}
if EndFree <> 0 then begin
// Len := ReadCom(PAnsiChar(@DBuffer^[DBufHead]), EndFree);
Len := ReadCom(PAnsiChar(AddWordToPtr(@DBuffer,DBufHead)), EndFree);
{Restore data count on errors}
if Len < 0 then begin
Len := 0;
GetComEventMask(-1);
end;
if DLoggingOn then
if Len = 0 then
AddDispatchEntry(dtDispatch, dstReadCom, Len, nil, 0)
else
// AddDispatchEntry(dtDispatch, dstReadCom, Len,
// @DBuffer^[DBufHead], Len);
AddDispatchEntry(dtDispatch, dstReadCom, Len,
PAnsiChar( AddWordToPtr( DBuffer, DBufHead)), Len);
{Increment buffer head}
Inc(DBufHead, Len);
if Cardinal(Len) < EndFree then
BeginFree := 0;
end else
Len := 0;
{Handle buffer wrap}
if DBufHead = DispatchBufferSize then
DBufHead := 0;
{Check for a full dispatch buffer}
if Len <> 0 then
DispatchFull := DBufHead = DBufTail;
{Move data to beginning of dispatch buffer}
if BeginFree <> 0 then begin
// Len := ReadCom(PAnsiChar(@DBuffer^[DBufHead]), BeginFree);
Len := ReadCom(PAnsiChar(AddWordToPtr( DBuffer, DBufHead)), BeginFree);
{Restore data count on errors}
if Len < 0 then begin
Len := Abs(Len);
GetComEventMask(-1);
end;
if DLoggingOn then
if Len = 0 then
AddDispatchEntry(dtDispatch, dstReadCom, Len, nil, 0)
else
// AddDispatchEntry(dtDispatch, dstReadCom, Len,
// @DBuffer^[DBufHead], Len);
AddDispatchEntry(dtDispatch, dstReadCom, Len,
AddWordToPtr( DBuffer, DBufHead), Len);
{Increment buffer head}
Inc(DBufHead, Len);
{Check for a full dispatch buffer}
DispatchFull := DBufHead = DBufTail;
end;
end else
Result := False;
finally
LeaveCriticalSection(DispSection);
end;
end;
function TApdBaseDispatcher.CheckTriggers : Boolean;
{-Check all triggers for H, send notification messages as required}
{-Return True if more checks remain}
{-Only used by the Winsock dispatcher}
begin
Result := True;
{Check timers, exit true if any hit}
if CheckTimerTriggers then
Exit;
{Check status triggers, exit true if any hit}
if CheckStatusTriggers then
Exit;
{Check receive data triggers, exit true if any hit}
if CheckReceiveTriggers then
Exit;
{No trigger hits, exit false}
Result := False;
end;
procedure TApdBaseDispatcher.CreateDispatcherWindow;
{-Create dispatcher window element}
{-Only used by the Winsock dispatcher}
begin
fDispatcherWindow :=
CreateWindow(DispatcherClassName, {window class name}
'', {caption}
ws_Overlapped, {window style}
0, {X}
0, {Y}
10, {width}
10, {height}
0, {parent}
0, {menu}
HInstance, {instance}
nil); {parameter}
ShowWindow(fDispatcherWindow, sw_Hide);
end;
{Trigger functions}
procedure TApdBaseDispatcher.RegisterWndTriggerHandler(HW : TApdHwnd);
var
TH : PWndTriggerHandler;
begin
EnterCriticalSection(DataSection);
try
{Allocate memory for TriggerHandler node}
New(TH);
{Fill in data}
with TH^ do begin
thWnd := HW;
thDeleted := False;
end;
WndTriggerHandlers.Add(TH);
HandlerServiceNeeded := True;
if DLoggingOn then
AddDispatchEntry(dtTriggerHandlerAlloc,dstWndHandler,HW,nil,0);
finally
LeaveCriticalSection(DataSection);
end;
end;
procedure TApdBaseDispatcher.RegisterProcTriggerHandler(NP : TApdNotifyProc);
var
TH : PProcTriggerHandler;
begin
EnterCriticalSection(DataSection);
try
{Allocate memory for TriggerHandler node}
New(TH);
{Fill in data}
with TH^ do begin
thnotify := NP;
thDeleted := False;
end;
ProcTriggerHandlers.Add(TH);
HandlerServiceNeeded := True;
if DLoggingOn then
AddDispatchEntry(dtTriggerHandlerAlloc,dstProcHandler,0,nil,0);
finally
LeaveCriticalSection(DataSection);
end;
end;
procedure TApdBaseDispatcher.RegisterSyncEventTriggerHandler(NP : TApdNotifyEvent);
var
TH : PEventTriggerHandler;
begin
EnterCriticalSection(DataSection);
try
{Allocate memory for TriggerHandler node}
New(TH);
{Fill in data}
with TH^ do begin
thNotify := NP;
thSync := True;
thDeleted := False;
end;
EventTriggerHandlers.Add(TH);
HandlerServiceNeeded := True;
if DLoggingOn then
AddDispatchEntry(dtTriggerHandlerAlloc,dstEventHandler,1,nil,0);
finally
LeaveCriticalSection(DataSection);
end;
end;
procedure TApdBaseDispatcher.RegisterEventTriggerHandler(NP : TApdNotifyEvent);
var
TH : PEventTriggerHandler;
begin
EnterCriticalSection(DataSection);
try
{Allocate memory for TriggerHandler node}
New(TH);
{Fill in data}
with TH^ do begin
thNotify := NP;
thSync := False;
thDeleted := False;
end;
EventTriggerHandlers.Add(TH);
HandlerServiceNeeded := True;
if DLoggingOn then
AddDispatchEntry(dtTriggerHandlerAlloc,dstEventHandler,0,nil,0);
finally
LeaveCriticalSection(DataSection);
end;
end;
procedure TApdBaseDispatcher.DeregisterWndTriggerHandler(HW : TApdHwnd);
var
i : Integer;
begin
EnterCriticalSection(DataSection);
try
for i := 0 to pred(WndTriggerHandlers.Count) do
with PWndTriggerHandler(WndTriggerHandlers[i])^ do
if thWnd = HW then begin
if DLoggingOn then
AddDispatchEntry(dtTriggerHandlerDispose,dstWndHandler,HW,nil,0);
if fEventBusy then begin
thDeleted := True;
DeletePending := True;
end else begin
Dispose(PWndTriggerHandler(WndTriggerHandlers[i]));
WndTriggerHandlers.Delete(i);
end;
exit;
end;
UpdateHandlerFlags(fuKeepPort);
finally
LeaveCriticalSection(DataSection);
end;
end;
procedure TApdBaseDispatcher.DeregisterProcTriggerHandler(NP : TApdNotifyProc);
var
i : Integer;
begin
EnterCriticalSection(DataSection);
try
for i := 0 to pred(ProcTriggerHandlers.Count) do
with PProcTriggerHandler(ProcTriggerHandlers[i])^ do
if @thNotify = @NP then begin
if DLoggingOn then
AddDispatchEntry(dtTriggerHandlerDispose,dstProcHandler,0,nil,0);
if fEventBusy then begin
thDeleted := True;
DeletePending := True;
end else begin
Dispose(PProcTriggerHandler(ProcTriggerHandlers[i]));
ProcTriggerHandlers.Delete(i);
end;
exit;
end;
UpdateHandlerFlags(fuKeepPort);
finally
LeaveCriticalSection(DataSection);
end;
end;
procedure TApdBaseDispatcher.DeregisterEventTriggerHandler(NP : TApdNotifyEvent);
var
i : Integer;
begin
EnterCriticalSection(DataSection);
try
for i := 0 to pred(EventTriggerHandlers.Count) do
with PEventTriggerHandler(EventTriggerHandlers[i])^ do
if @thNotify = @NP then begin
if DLoggingOn then
AddDispatchEntry(dtTriggerHandlerDispose,dstEventHandler,0,nil,0);
if fEventBusy then begin
thDeleted := True;
DeletePending := True;
end else begin
Dispose(PEventTriggerHandler(EventTriggerHandlers[i]));
EventTriggerHandlers.Delete(i);
end;
exit;
end;
UpdateHandlerFlags(fuKeepPort);
finally
LeaveCriticalSection(DataSection);
end;
end;
function TApdBaseDispatcher.GetTriggerHandle : Cardinal;
{-Find, allocate and return the first free trigger handle}
var
I : Integer;
Good : Boolean;
begin
{ Allocate a trigger handle. If we can, within the size of the handle's }
{ datatype, we just increment TriggerCounter to get a new handle. If not, }
{ we need to check the existing handles to find a unique one. }
if TriggerCounter < MaxTriggerHandle then begin
Result := TriggerCounter shl 3; {low three bits reserved for trigger specific information}
inc(TriggerCounter);
end else begin
Result := FirstTriggerCounter shl 3; {lowest possible handle value}
repeat
Good := True; {Assume success}
for i := 0 to pred(TimerTriggers.Count) do
with PTimerTrigger(TimerTriggers[i])^ do
if tHandle = Result then begin
Good := False;
break;
end;
if Good then for i := 0 to pred(StatusTriggers.Count) do
with PStatusTrigger(StatusTriggers[i])^ do
if (tHandle and not 7)= Result then begin
Good := False;
break;
end;
if Good then for i := 0 to pred(DataTriggers.Count) do
with PDataTrigger(DataTriggers[i])^ do
if tHandle = Result then begin
Good := False;
break;
end;
if not Good then
inc(Result,(1 shl 3));
until Good;
if Result > MaxTriggerHandle then
Result := 0;
end;
end;
function TApdBaseDispatcher.FindTriggerFromHandle(TriggerHandle : Cardinal; Delete : Boolean;
var T : TTriggerType; var Trigger : Pointer) : Integer;
{-Find the trigger index}
var
i : Integer;
b : Byte;
begin
T := ttNone;
Result := ecOk;
if (TriggerHandle > 1) then begin
for i := 0 to pred(TimerTriggers.Count) do begin
Trigger := TimerTriggers[i];
with PTimerTrigger(Trigger)^ do
if tHandle = TriggerHandle then begin
T := ttTimer;
if Delete then begin
TimerTriggers.Delete(i);
Dispose(PTimerTrigger(Trigger));
if DLoggingOn then
AddDispatchEntry(dtTriggerDispose,dstTimer,TriggerHandle,nil,0);
Trigger := nil;
end;
exit;
end;
end;
for i := 0 to pred(StatusTriggers.Count) do begin
Trigger := StatusTriggers[i];
with PStatusTrigger(Trigger)^ do
if tHandle = TriggerHandle then begin
T := ttStatus;
if Delete then begin
StatusTriggers.Delete(i);
Dispose(PStatusTrigger(Trigger));
if DLoggingOn then begin
b := lo(TriggerHandle and (StatusTypeMask));
AddDispatchEntry(dtTriggerDispose,dstStatusTrigger,TriggerHandle,@b,1);
end;
Trigger := nil;
end;
exit;
end;
end;
for i := 0 to pred(DataTriggers.Count) do begin
Trigger := DataTriggers[i];
with PDataTrigger(Trigger)^ do
if Cardinal(tHandle and not 7) = TriggerHandle then begin {!!.01}
T := ttData;
if Delete then begin
DataTriggers.Delete(i);
Dispose(PDataTrigger(Trigger));
if DLoggingOn then
AddDispatchEntry(dtTriggerDispose,dstData,TriggerHandle,nil,0);
Trigger := nil;
end;
exit;
end;
end;
end else begin
T := ttNone;
Trigger := nil;
end;
if T = ttNone then
Result := ecBadTriggerHandle;
end;
procedure TApdBaseDispatcher.ChangeLengthTrigger(Length : Cardinal);
{-Change the length trigger to Length}
begin
EnterCriticalSection(DataSection);
try
LenTrigger := Length;
if DLoggingOn then
AddDispatchEntry(dtTriggerDataChange,dstAvailTrigger,Length,nil,0);
finally
LeaveCriticalSection(DataSection);
end;
end;
function TApdBaseDispatcher.AddTimerTrigger : Integer;
{-Add a timer trigger}
var
NewTimerTrigger : PTimerTrigger;
begin
EnterCriticalSection(DataSection);
try
NewTimerTrigger := AllocMem(sizeof(TTimerTrigger));
with NewTimerTrigger^ do begin
tHandle := GetTriggerHandle;
tTicks := 0;
tActive := False;
tValid := True;
Result := tHandle;
end;
if Result > 0 then begin
TimerTriggers.Add(NewTimerTrigger);
if DLoggingOn then
AddDispatchEntry(dtTriggerAlloc,dstTimerTrigger,Result,nil,0);
end else
Result := ecNoMoreTriggers;
finally
LeaveCriticalSection(DataSection);
end;
end;
function TApdBaseDispatcher.AddDataTriggerLen(Data : PAnsiChar;
IgnoreCase : Boolean; Len : Cardinal) : Integer;
{-Add a data trigger, data is any ASCIIZ string so no embedded zeros}
var
NewDataTrigger : PDataTrigger;
begin
EnterCriticalSection(DataSection);
try
if Len <= MaxTrigData then begin
NewDataTrigger := AllocMem(sizeof(TDataTrigger));
with NewDataTrigger^ do begin
tHandle := GetTriggerHandle;
tLen := Len;
FillChar(tChkIndex, SizeOf(TCheckIndex), 0);
tMatched := False;
tIgnoreCase := IgnoreCase;
Move(Data^, tData, Len);
if IgnoreCase and (Len <> 0) then
AnsiUpperBuff(@tData, Len);
Result := tHandle;
end;
if Result > 0 then begin
DataTriggers.Add(NewDataTrigger);
if DLoggingOn then
AddDispatchEntry(dtTriggerAlloc,dstDataTrigger,Result,Data,Len);
end else
Result := ecNoMoreTriggers;
end else
Result := ecTriggerTooLong;
finally
LeaveCriticalSection(DataSection);
end;
end;
function TApdBaseDispatcher.AddDataTrigger(Data : PAnsiChar;
IgnoreCase : Boolean) : Integer;
{-Add a data trigger, data is any ASCIIZ string so no embedded nulls}
begin
Result := AddDataTriggerLen(Data, IgnoreCase, StrLen(Data));
end;
function TApdBaseDispatcher.AddStatusTrigger(SType : Cardinal) : Integer;
{-Add a status trigger of type SType}
var
NewStatusTrigger : PStatusTrigger;
begin
if (SType > stOutSent) then begin
Result := ecBadArgument;
Exit;
end;
EnterCriticalSection(DataSection);
try
NewStatusTrigger := AllocMem(sizeof(TStatusTrigger));
with NewStatusTrigger^ do begin
tHandle := GetTriggerHandle or SType;
tSType := SType;
tSActive := False;
Result := tHandle;
end;
if (Result and not 7) > 0 then begin
StatusTriggers.Add(NewStatusTrigger);
if DLoggingOn then
AddDispatchEntry(dtTriggerAlloc, dstStatusTrigger,
Result, @SType, 1);
end else
Result := ecNoMoreTriggers;
finally
LeaveCriticalSection(DataSection);
end;
end;
function TApdBaseDispatcher.RemoveTrigger(TriggerHandle : Cardinal) : Integer;
{-Remove the trigger for Index}
var
Trigger : Pointer;
T : TTriggerType;
begin
EnterCriticalSection(DataSection);
try
if TriggerHandle = 1 then
{Length trigger}
begin
LenTrigger := 0;
Result := ecOk;
end
else
{Other trigger}
Result := FindTriggerFromHandle(TriggerHandle, True, T, Trigger);
finally
LeaveCriticalSection(DataSection);
end;
end;
function TApdBaseDispatcher.SetTimerTrigger(TriggerHandle : Cardinal;
Ticks : LongInt; Activate : Boolean) : Integer;
const
DeactivateStr : Ansistring = 'Deactivated';
var
Trigger : PTimerTrigger;
T : TTriggerType;
begin
EnterCriticalSection(DataSection);
try
FindTriggerFromHandle(TriggerHandle, False, T, Pointer(Trigger));
if (Trigger <> nil) and (T = ttTimer) then
with Trigger^ do begin
if Activate then begin
if Ticks <> 0 then
tTicks := Ticks;
NewTimer(tET, tTicks);
end;
if DLoggingOn then
if Activate then
AddDispatchEntry(dtTriggerDataChange, dstTimerTrigger,
TriggerHandle,@Ticks,sizeof(Ticks))
else
AddDispatchEntry(dtTriggerDataChange, dstTimerTrigger,
TriggerHandle,@DeactivateStr[1],Length(DeactivateStr));
tActive := Activate;
Result := ecOk;
end
else
Result := ecBadTriggerHandle;
finally
LeaveCriticalSection(DataSection);
end;
end;
function TApdBaseDispatcher.ExtendTimer(TriggerHandle : Cardinal;
Ticks : LongInt) : Integer;
var
Trigger : PTimerTrigger;
T : TTriggerType;
begin
EnterCriticalSection(DataSection);
try
FindTriggerFromHandle(TriggerHandle, False, T, Pointer(Trigger));
if (Trigger <> nil) and (T = ttTimer) then
with Trigger^ do begin
Inc(tET.ExpireTicks, Ticks);
Result := ecOk;
if DLoggingOn then
AddDispatchEntry(dtTriggerDataChange, dstTimerTrigger,
TriggerHandle, @Ticks,sizeof(Ticks));
end
else
Result := ecBadTriggerHandle;
finally
LeaveCriticalSection(DataSection);
end;
end;
function TApdBaseDispatcher.TimerTicksRemaining(TriggerHandle : Cardinal;
var TicksRemaining : Longint) : Integer;
var
Trigger : PTimerTrigger;
T : TTriggerType;
begin
TicksRemaining := 0;
EnterCriticalSection(DataSection);
try
FindTriggerFromHandle(TriggerHandle, False, T, Pointer(Trigger));
if (Trigger <> nil) and (T = ttTimer) then
with Trigger^ do begin
TicksRemaining := RemainingTime(tET);
Result := ecOk;
end
else
Result := ecBadTriggerHandle;
finally
LeaveCriticalSection(DataSection);
end;
end;
procedure TApdBaseDispatcher.UpdateHandlerFlags(FlagUpdate : TApHandlerFlagUpdate);
var
HandlersInstalled : Boolean;
begin
EnterCriticalSection(DataSection);
try
HandlersInstalled := (WndTriggerHandlers.Count > 1) or
(ProcTriggerHandlers.Count > 0) or (EventTriggerHandlers.Count > 0);
case FlagUpdate of
fuKeepPort :
HandlerServiceNeeded := (HandlersInstalled or PortHandlerInstalled);
fuEnablePort :
begin
PortHandlerInstalled := True;
HandlerServiceNeeded := True;
end;
fuDisablePort :
begin
PortHandlerInstalled := False;
HandlerServiceNeeded := HandlersInstalled;
end;
end;
finally
LeaveCriticalSection(DataSection);
end;
end;
function TApdBaseDispatcher.SetStatusTrigger(TriggerHandle : Cardinal;
Value : Cardinal; Activate : Boolean) : Integer;
type
LH = record L,H : Byte; end;
var
Trigger : PStatusTrigger;
T : TTriggerType;
function SetLineBits(Value : Cardinal) : Cardinal;
{-Return mask that can be checked against LastError later}
begin
Result := 0;
if FlagIsSet(Value, lsOverrun) then
Result := ce_Overrun;
if FlagIsSet(Value, lsParity) then
Result := Result or ce_RxParity;
if FlagIsSet(Value, lsFraming) then
Result := Result or ce_Frame;
if FlagIsSet(Value, lsBreak) then
Result := Result or ce_Break;
end;
begin
EnterCriticalSection(DataSection);
try
FindTriggerFromHandle(TriggerHandle, False, T, Pointer(Trigger));
if (Trigger <> nil) and (T = ttStatus) then
with Trigger^ do begin
if Activate then begin
case tSType of
stLine :
tValue := SetLineBits(Value);
stModem :
begin
{Hi tValue is delta mask, Lo is current modem status}
LH(tValue).H := Value;
LH(tValue).L := Value and ModemStatus;
end;
stOutBuffFree,
stOutBuffUsed :
tValue := Value;
end;
if DLoggingOn then
AddDispatchEntry(dtTriggerDataChange, dstStatusTrigger,
TriggerHandle, @tValue, sizeof(Cardinal));
end;
tSActive := Activate;
Result := ecOK;
end
else
Result := ecBadTriggerHandle;
finally
LeaveCriticalSection(DataSection);
end;
end;
class procedure TApdBaseDispatcher.ClearSaveBuffers(var Save : TTriggerSave);
begin
with Save do begin
if tsTimerTriggers <> nil then begin
while tsTimerTriggers.Count > 0 do begin
Dispose(PTimerTrigger(tsTimerTriggers[0]));
tsTimerTriggers.Delete(0);
end;
tsTimerTriggers.Free;
tsTimerTriggers := nil;
end;
if tsDataTriggers <> nil then begin
while tsDataTriggers.Count > 0 do begin
Dispose(PDataTrigger(tsDataTriggers[0]));
tsDataTriggers.Delete(0);
end;
tsDataTriggers.Free;
tsDataTriggers := nil;
end;
if tsStatusTriggers <> nil then begin
while tsStatusTriggers.Count > 0 do begin
Dispose(PStatusTrigger(tsStatusTriggers[0]));
tsStatusTriggers.Delete(0);
end;
tsStatusTriggers.Free;
tsStatusTriggers := nil;
end;
end;
end;
procedure TApdBaseDispatcher.SaveTriggers(var Save : TTriggerSave);
{-Saves all current triggers to Save}
var
i : Integer;
NewTimerTrigger : PTimerTrigger;
NewDataTrigger : PDataTrigger;
NewStatusTrigger : PStatusTrigger;
begin
with Save do begin
EnterCriticalSection(DataSection);
try
ClearSaveBuffers(Save);
tsLenTrigger := LenTrigger;
tsTimerTriggers := TList.Create;
for i := 0 to pred(TimerTriggers.Count) do begin
NewTimerTrigger := AllocMem(sizeof(TTimerTrigger));
move(PTimerTrigger(TimerTriggers[i])^, NewTimerTrigger^,
sizeof(TTimerTrigger));
tsTimerTriggers.Add(NewTimerTrigger);
end;
tsDataTriggers := TList.Create;
for i := 0 to pred(DataTriggers.Count) do begin
NewDataTrigger := AllocMem(sizeof(TDataTrigger));
move(PDataTrigger(DataTriggers[i])^, NewDataTrigger^,
sizeof(TDataTrigger));
tsDataTriggers.Add(NewDataTrigger);
end;
tsStatusTriggers := TList.Create;
for i := 0 to pred(StatusTriggers.Count) do begin
NewStatusTrigger := AllocMem(sizeof(TStatusTrigger));
move(PStatusTrigger(StatusTriggers[i])^, NewStatusTrigger^,
sizeof(TStatusTrigger));
tsStatusTriggers.Add(NewStatusTrigger);
end;
finally
LeaveCriticalSection(DataSection);
end;
end;
end;
procedure TApdBaseDispatcher.RestoreTriggers(var Save : TTriggerSave);
{-Restores previously saved triggers}
var
i : Integer;
NewTimerTrigger : PTimerTrigger;
NewDataTrigger : PDataTrigger;
NewStatusTrigger : PStatusTrigger;
begin
with Save do begin
EnterCriticalSection(DataSection);
try
LenTrigger := tsLenTrigger;
while TimerTriggers.Count > 0 do begin
Dispose(PTimerTrigger(TimerTriggers[0]));
TimerTriggers.Delete(0);
end;
while DataTriggers.Count > 0 do begin
Dispose(PDataTrigger(DataTriggers[0]));
DataTriggers.Delete(0);
end;
while StatusTriggers.Count > 0 do begin
Dispose(PStatusTrigger(StatusTriggers[0]));
StatusTriggers.Delete(0);
end;
if tsTimerTriggers <> nil then
for i := 0 to pred(tsTimerTriggers.Count) do begin
NewTimerTrigger := AllocMem(sizeof(TTimerTrigger));
move(PTimerTrigger(tsTimerTriggers[i])^, NewTimerTrigger^,
sizeof(TTimerTrigger));
TimerTriggers.Add(NewTimerTrigger);
end;
if tsDataTriggers <> nil then
for i := 0 to pred(tsDataTriggers.Count) do begin
NewDataTrigger := AllocMem(sizeof(TDataTrigger));
move(PDataTrigger(tsDataTriggers[i])^, NewDataTrigger^,
sizeof(TDataTrigger));
DataTriggers.Add(NewDataTrigger);
end;
if tsStatusTriggers <> nil then
for i := 0 to pred(tsStatusTriggers.Count) do begin
NewStatusTrigger := AllocMem(sizeof(TStatusTrigger));
move(PStatusTrigger(tsStatusTriggers[i])^, NewStatusTrigger^,
sizeof(TStatusTrigger));
StatusTriggers.Add(NewStatusTrigger);
end;
finally
LeaveCriticalSection(DataSection);
end;
end;
end;
function TApdBaseDispatcher.ChangeBaud(NewBaud : LongInt) : Integer;
{-Change the baud rate of port H to NewBaud}
begin
Result := SetLine(NewBaud, DontChangeParity, DontChangeDatabits,
DontChangeStopbits);
end;
function TApdBaseDispatcher.SetDataPointer(P : Pointer; Index : Cardinal) : Integer;
{-Set a data pointer}
begin
EnterCriticalSection(DataSection);
try
if (Index >= 1) and (Index <= MaxDataPointers) then begin
DataPointers[Index] := P;
Result := ecOK;
end else
Result := ecBadArgument;
finally
LeaveCriticalSection(DataSection);
end;
end;
function TApdBaseDispatcher.GetDataPointer(var P : Pointer;
Index : Cardinal) : Integer;
{-Return a data pointer}
begin
EnterCriticalSection(DataSection);
try
if (Index >= 1) and (Index <= MaxDataPointers) then begin
P := DataPointers[Index];
Result := ecOK;
end else
Result := ecBadArgument;
finally
LeaveCriticalSection(DataSection);
end;
end;
function TApdBaseDispatcher.GetFlowOptions(var HWOpts, SWOpts, BufferFull,
BufferResume : Cardinal; var OnChar, OffChar : AnsiChar) : Integer;
begin
HWOpts := 0;
SWOpts := 0;
EnterCriticalSection(DataSection);
try
Result := GetComState(DCB);
if (DCB.Flags and dcb_DTR_CONTROL_HANDSHAKE) <> 0 then
HWOpts := HWOpts or hfUseDtr;
if (DCB.Flags and dcb_RTS_CONTROL_HANDSHAKE) <> 0 then
HWOpts := HWOpts or hfUseRts;
if (DCB.Flags and dcb_OutxDsrFlow) <> 0 then
HWOpts := HWOpts or hfRequireDsr;
if (DCB.Flags and dcb_OutxCtsFlow) <> 0 then
HWOpts := HWOpts or hfRequireCts;
if (DCB.Flags and dcb_InX) <> 0 then
SWOpts := SWOpts or sfReceiveFlow;
if (DCB.Flags and dcb_OutX) <> 0 then
SWOpts := SWOpts or sfTransmitFlow;
OnChar := DCB.XOnChar;
OffChar := DCB.XOffChar;
finally
LeaveCriticalSection(DataSection);
end;
end;
procedure TApdBaseDispatcher.OptionsOn(Options : Cardinal);
{-Enable the port options in Options}
begin
EnterCriticalSection(DataSection);
try
Flags := Flags or Options;
finally
LeaveCriticalSection(DataSection);
end;
end;
procedure TApdBaseDispatcher.OptionsOff(Options : Cardinal);
{-Disable the port options in Options}
begin
EnterCriticalSection(DataSection);
try
Flags := Flags and not Options;
finally
LeaveCriticalSection(DataSection);
end;
end;
function TApdBaseDispatcher.OptionsAreOn(Options : Cardinal) : Boolean;
{-Return True if the specified options are on}
begin
EnterCriticalSection(DataSection);
try
Result := (Flags and Options) = Options;
finally
LeaveCriticalSection(DataSection);
end;
end;
function TApdBaseDispatcher.ClearTracing : Integer;
{-Clears the trace buffer}
begin
Result := ecOK;
EnterCriticalSection(DataSection);
try
TraceIndex := 0;
TraceWrapped := False;
finally
LeaveCriticalSection(DataSection);
end;
end;
procedure TApdBaseDispatcher.AbortTracing;
{-Stops tracing and destroys the tracebuffer}
begin
EnterCriticalSection(DataSection);
try
TracingOn := False;
if TraceQueue <> nil then begin
FreeMem(TraceQueue, TraceMax*2);
TraceQueue := nil;
end;
finally
LeaveCriticalSection(DataSection);
end;
end;
function TApdBaseDispatcher.InitTracing(NumEntries : Cardinal) : Integer;
{-Prepare a circular tracing queue}
begin
EnterCriticalSection(DataSection);
try
if TraceQueue <> nil then
{Just clear buffer if already on}
ClearTracing
else begin
{Limit check size of trace buffer}
if NumEntries > HighestTrace then begin
Result := ecBadArgument;
exit;
end;
{Allocate trace buffer and start tracing}
TraceMax := NumEntries;
TraceIndex := 0;
TraceWrapped := False;
TraceQueue := AllocMem(NumEntries*2);
end;
TracingOn := True;
Result := ecOK;
finally
LeaveCriticalSection(DataSection);
end;
end;
procedure TApdBaseDispatcher.AddTraceEntry(CurEntry : AnsiChar; CurCh : AnsiChar);
{-Add a trace event to the global TraceQueue}
begin
EnterCriticalSection(DataSection);
try
if TraceQueue <> nil then begin
TraceQueue^[TraceIndex].EventType := CurEntry;
TraceQueue^[TraceIndex].C := CurCh;
Inc(TraceIndex);
if TraceIndex = TraceMax then begin
TraceIndex := 0;
TraceWrapped := True;
end;
end;
finally
LeaveCriticalSection(DataSection);
end;
end;
function TApdBaseDispatcher.DumpTracePrim(FName : string;
AppendFile, InHex, AllHex : Boolean) : Integer;
{-Write the TraceQueue to FName}
const
Digits : array[0..$F] of AnsiChar = '0123456789ABCDEF';
LowChar : array[Boolean] of Byte = (32, 33);
var
Start, Len : Cardinal;
TraceFile : Text;
TraceFileBuffer : array[1..512] of AnsiChar;
LastEventType : AnsiChar;
First : Boolean;
Col : Cardinal;
I : Cardinal;
Res : Cardinal;
procedure CheckCol(N : Cardinal);
{-Wrap if N bytes would exceed column limit}
begin
Inc(Col, N);
if Col > MaxTraceCol then begin
WriteLn(TraceFile);
Col := N;
end;
end;
function HexB(B : Byte) : AnsiString;
{-Return hex string for byte}
begin
{$IFDEF HugeStr}
SetLength(Result, 2);
{$ELSE}
HexB[0] := #2;
{$ENDIF}
HexB[1] := Digits[B shr 4];
HexB[2] := Digits[B and $F];
end;
begin
Result := ecOK;
{Make sure we have something to do}
if TraceQueue = nil then
Exit;
{Turn tracing off now}
// TracingOn := False; // SWB
EnterCriticalSection(DataSection);
try
{Set the Start and Len markers}
Len := TraceIndex;
if TraceWrapped then
Start := TraceIndex
else if TraceIndex <> 0 then
Start := 0
else begin
{No events, just exit}
// AbortTracing; // SWB
Exit;
end;
Assign(TraceFile, FName);
SetTextBuf(TraceFile, TraceFileBuffer, SizeOf(TraceFileBuffer));
if AppendFile and ExistFileZ(FName) then begin
{Open an existing file}
Append(TraceFile);
Res := IoResult;
end else begin
{Open new file}
ReWrite(TraceFile);
Res := IoResult;
end;
if Res <> ecOK then begin
Result := -Res;
AbortTracing;
Exit;
end;
try
{Write the trace queue}
LastEventType := #0;
First := True;
Col := 0;
repeat
{Some formattting}
with TraceQueue^[Start] do begin
if EventType <> LastEventType then begin
if not First then begin
WriteLn(TraceFile,^M^J);
Col := 0;
end;
{First := False;}
case EventType of
'T' : WriteLn(TraceFile, 'Transmit: ');
'R' : WriteLn(TraceFile, 'Receive: ');
else WriteLn(TraceFile, 'Special-'+EventType+': ');
end;
LastEventType := EventType;
end;
{Write the current char}
if AllHex then begin
CheckCol(4);
Write(TraceFile, '[',HexB(Ord(C)),']');
end else
if (Ord(C) < LowChar[InHex]) or (Ord(C) > 126) then begin
if InHex then begin
CheckCol(4);
Write(TraceFile, '[',HexB(Ord(C)),']')
end else begin
if Ord(C) > 99 then
I := 5
else if Ord(C) > 9 then
I := 4
else
I := 3;
CheckCol(I);
Write(TraceFile, '[',Ord(C),']')
end;
end else begin
CheckCol(1);
Write(TraceFile, C);
end;
{Get the next char}
Inc(Start);
if Start = TraceMax then
Start := 0;
end;
First := False;
until Start = Len;
finally
Close(TraceFile);
Result := -IoResult;
// AbortTracing; // SWB
InitTracing(TraceMax); // SWB
end;
finally
LeaveCriticalSection(DataSection);
end;
end;
function TApdBaseDispatcher.DumpTrace(FName : string;
InHex, AllHex : Boolean) : Integer;
{-Write the TraceQueue to FName}
begin
Result := DumpTracePrim(FName, False, InHex, AllHex);
end;
function TApdBaseDispatcher.AppendTrace(FName : string;
InHex, AllHex : Boolean) : Integer;
{-Append the TraceQueue to FName}
begin
Result := DumpTracePrim(FName, True, InHex, AllHex);
end;
procedure TApdBaseDispatcher.StartTracing;
{-Restarts tracing after a StopTracing}
begin
EnterCriticalSection(DataSection);
try
if TraceQueue <> nil then
TracingOn := True;
finally
LeaveCriticalSection(DataSection);
end;
end;
procedure TApdBaseDispatcher.StopTracing;
{-Stops tracing temporarily}
begin
EnterCriticalSection(DataSection);
try
TracingOn := False;
finally
LeaveCriticalSection(DataSection);
end;
end;
procedure TApdBaseDispatcher.ClearDispatchLogging;
{-Clear the dispatch log}
begin
DLoggingQueue.Clear; // SWB
end;
procedure TApdBaseDispatcher.AbortDispatchLogging;
{-Abort dispatch logging}
begin
DLoggingOn := False;
DLoggingQueue.Clear; // SWB
end;
procedure TApdBaseDispatcher.StartDispatchLogging;
{-Restarts logging after a pause}
begin
DLoggingOn := True;
end;
procedure TApdBaseDispatcher.StopDispatchLogging;
{-Pause dispatch logging}
begin
DLoggingOn := False;
end;
procedure TApdBaseDispatcher.InitDispatchLogging(QueueSize : Cardinal);
{-Enable dispatch logging}
begin
ClearDispatchLogging;
DLoggingMax := QueueSize;
DLoggingOn := True;
end;
{apro.str offsets used for logging strings:}
const
drTypeBase = 15001;
drSubTypeBase = 15100;
Header1 = 15501;
Header2 = 15502;
MaxTelnetTag = 42;
TelnetBase = 15700;
MSTagBase = 15601;
function GetDTStr(drType : TDispatchType) : string;
begin
Result := AproLoadStr(drTypeBase + ord(drType));
end;
function GetDSTStr(drsType : TDispatchSubType) : ansistring; // --sm ansi
begin
if drsType = dstNone then
Result := ''
else
Result := AproLoadStr(drSubTypeBase + ord(drsType));
end;
function GetTimeStr(drTime : DWORD) : string;
begin
Result := Format('%07.7d', [drTime]);
Insert('.', Result, Length(Result) - 2); {!!.04}
end;
function TApdBaseDispatcher.DumpDispatchLogPrim(FName : string;
AppendFile, InHex, AllHex : Boolean) : Integer;
{-Dump the dispatch log}
const
StartColumn = 45;
Digits : array[0..$F] of AnsiChar = '0123456789ABCDEF';
LowChar : array[Boolean] of Byte = (32, 33);
var
I, J : Cardinal;
Col : Cardinal;
Res : Integer;
DumpFile : Text;
C : AnsiChar; // --sm ansi
LogFileBuffer : array[1..512] of AnsiChar;
S : string[80];
logBfr : TLogBuffer; // SWB
function GetOSVersion : string;
var
OSVersion : TOSVersionInfo;
SerPack : string; {!!.04}
begin
OSVersion.dwOSVersionInfoSize := SizeOf(OSVersion);
GetVersionEx(OSVersion);
SerPack := ''; {!!.04}
case OSVersion.dwPlatformID of
VER_PLATFORM_WIN32s : begin {!!.04}
SerPack := StrPas(OSVersion.szCSDVersion); {!!.04}
Result := 'Win32s on Windows ';
end; {!!.04}
VER_PLATFORM_WIN32_WINDOWS : begin {!!.04}
case OsVersion.dwMinorVersion of {!!.04}
0 : if Trim(OsVersion.szCSDVersion[1]) = 'B' then {!!.04}
Result := 'Win32 on Windows 95 OSR 2 ' {!!.04}
else {!!.04}
Result := 'Win32 on Windows 95 OSR 1 '; {!!.04}
10 : if Trim(OsVersion.szCSDVersion[1]) = 'A' then {!!.04}
Result := 'Win32 on Windows 98 OSR 2 ' {!!.04}
else {!!.04}
Result := 'Win32 on Windows 98 OSR 1 '; {!!.04}
90 : if (OsVersion.dwBuildNumber = 73010104) then {!!.04}
Result := 'Win32 on Windows ME '; {!!.04}
else Result := 'Win32 on Windows 9x'; {!!.04}
end; {!!.04}
end; {!!.04}
VER_PLATFORM_WIN32_NT : begin {!!.04}
SerPack := StrPas(OSVersion.szCSDVersion); {!!.04}
case OSVersion.dwMajorVersion of {!!.04}
2 : if OsVersion.dwMinorVersion = 6 then // --sm
Result := 'Window CE '; // --sm
3 : Result := 'Windows NT 3.5 '; {!!.04}
4 : Result := 'Windows NT 4 '; {!!.04}
5 : case OSVersion.dwMinorVersion of {!!.04}
0 : Result := 'Windows 2000 '; {!!.04}
1 : Result := 'Windows XP '; {!!.04}
2 : Result := 'Windows 2003 '; // --sm
end;
6 : case OSVersion.dwMinorVersion of // --sm
0 : Result := 'Windows Vista '; // --sm
1 : Result := 'Windows 7 '; // --sm
end; {!!.04}
else Result := 'WinNT '; {!!.04}
end; {!!.04}
end; {!!.04}
else Result := 'Unknown';
end;
Result := Result + IntToStr(OSVersion.dwMajorVersion) + '.' +
IntToStr(OSVersion.dwMinorVersion) + ' ' + SerPack; {!!.04}
end;
procedure CheckCol(N : Cardinal);
{-Wrap if N bytes would exceed column limit}
begin
Inc(Col, N);
if Col > MaxTraceCol then begin
WriteLn(DumpFile);
Write(DumpFile, '':StartColumn-1);
Col := StartColumn+N;
end;
end;
begin
Result := ecOK;
{Make sure we have something to do}
if ((DLoggingQueue = nil) or // SWB
(DLoggingQueue.Count = 0)) then begin // SWB
// AbortDispatchLogging; // SWB
Exit;
end;
EnterCriticalSection(DataSection);
try
Assign(DumpFile, FName);
SetTextBuf(DumpFile, LogFileBuffer, SizeOf(LogFileBuffer));
if AppendFile and ExistFileZ(FName) then begin
{Append to existing file}
Append(DumpFile);
Res := IoResult;
end else begin
{Create new file}
Rewrite(DumpFile);
Res := IoResult;
end;
if Res <> 0 then begin
Result := -Res;
Close(DumpFile);
if IoResult <> 0 then ;
Exit;
end;
{Write heading just once}
{$IFDEF APAX}
WriteLn(DumpFile, 'APAX', ApaxVersionStr);
{$ELSE}
WriteLn(DumpFile, 'APRO ', ApVersionStr);
{write compiler version to log}
S := 'Unknown';
{$IFDEF VER100}
S := 'Delphi 3';
{$ENDIF}
{$IFDEF VER120}
S := 'Delphi 4';
{$ENDIF}
{$IFDEF VER130}
S := 'Delphi 5';
{$ENDIF}
{$IFDEF VER140}
S := 'Delphi 6';
{$ENDIF}
{$IFDEF VER150}
S := 'Delphi 7'; {!!.06}
{$ENDIF}
{$IFDEF VER180} // KGM
S := 'Delphi 2006'; // KGM
{$ENDIF} // KGM
{$IFDEF VER190} // KGM
S := 'Delphi 2007'; // KGM
{$ENDIF} // KGM
{$IFDEF VER200} // --sm
S := 'Delphi 2009';
{$IFDEF VER210} // --sm
S := 'Delphi 2010';
{$ifdef DELPHI_Future} // --sm
{$define DELPHI_2010_UP}
S := 'Delphi 2010 UP';
{$endif}
{$ENDIF} {$ENDIF}
{$IFDEF VER93}
S := 'C++ Builder 1';
{$ENDIF}
{$IFDEF VER110}
S := 'C++ Builder 3';
{$ENDIF}
{$IFDEF VER125}
S := 'C++ Builder 4';
{$ENDIF}
{$IFDEF VER130}
{$IFDEF BCB}
S := 'C++ Builder 5';
{$ENDIF}
{$ENDIF}
{$IFDEF VER140} {!!.04}
{$IFDEF BCB} {!!.04}
S := 'C++ Builder 6'; {!!.04}
{$ENDIF} {!!.04}
{$ENDIF} {!!.04}
WriteLn(DumpFile, 'Compiler : ', S);
{$ENDIF}
{write operating system to log}
S := GetOSVersion;
WriteLn(DumpFile, 'Operating System : ', S);
WriteLn(DumpFile, 'Device: ', DeviceName);
S := FormatDateTime('dd/mm/yy, hh:mm:ss', Now); {!!.02}
WriteLn(DumpFile, 'Date/time: ', S); {!!.02}
WriteLn(DumpFile, AproLoadStr(Header1));
WriteLn(DumpFile, AproLoadStr(Header2));
{Loop through all entries}
repeat
{Get the next entry and remove from queue}
logBfr := TLogBuffer(DLoggingQueue.Pop); // SWB
{Write a report line}
if (Assigned(logBfr)) then begin // SWB
with logBfr do begin
Write(DumpFile, format('%8s %-8s %-12s %08.8x ',
[GetTimeStr(drTime),GetDTStr(drType),GetDSTStr(drSubType),drData]));
if drMoreData = 0 then begin
{Add telnet tags if necessary}
if drType = dtTelnet then begin
S := ' [';
if drData <= MaxTelnetTag then
S := S + AproLoadStr(TelnetBase + ord(drData));
Write(DumpFile, trim(S),']');
end;
WriteLn(DumpFile)
end else begin
if (drSubType = dstStatusTrigger)
and ((drType = dtTriggerAlloc)
or (drType = dtTriggerDispose))
then begin
case Byte(drBuffer^) of // SWB
0 : Write(DumpFile, '(Not active)');
1 : Write(DumpFile, '(Modem status)');
2 : Write(DumpFile, '(Line status)');
3 : Write(DumpFile, '(Output buffer free)');
4 : Write(DumpFile, '(Output buffer used)');
5 : Write(DumpFile, '(Output sent)');
end;
end else begin
Col := StartColumn;
for I := 0 to (drMoreData - 1) do begin // SWB
C := (drBuffer + I)^; // SWB
if AllHex then begin
if drType = dtUser then begin
CheckCol(1);
Write(DumpFile, C);
end else begin
CheckCol(4);
Write(DumpFile, '[',IntToHex(Ord(C), 2),']');
end;
end else
if (Ord(C) < LowChar[InHex]) or (Ord(C) > 126) then begin
if InHex then begin
CheckCol(4);
Write(DumpFile, '[',IntToHex(Ord(C),2),']')
end else begin
if Ord(C) > 99 then
J := 5
else if Ord(C) > 9 then
J := 4
else
J := 3;
CheckCol(J);
Write(DumpFile, '[',Ord(C),']')
end;
end else begin
CheckCol(1);
Write(DumpFile, C);
end;
end;
end;
{Add modem status tags}
if drSubType = dstModemStatus then begin
S := ' (';
for I := 0 to 7 do
if Odd(drData shr I) then
S := S + AproLoadStr(MSTagBase + I);
Write(DumpFile, trim(S),')');
end;
WriteLn(DumpFile);
end;
end;
logBfr.Free; // SWB
end;
until (not Assigned(logBfr)); // SWB
Close(DumpFile);
Result := -IoResult;
// AbortDispatchLogging; // SWB
finally
LeaveCriticalSection(DataSection);
end;
end;
function TApdBaseDispatcher.DumpDispatchLog(
FName : string;
InHex, AllHex : Boolean) : Integer;
{-Dump the dispatch log}
begin
Result := DumpDispatchLogPrim(FName, False, InHex, AllHex);
end;
function TApdBaseDispatcher.AppendDispatchLog(
FName : string;
InHex, AllHex : Boolean) : Integer;
{-Append the dispatch log}
begin
Result := DumpDispatchLogPrim(FName, True, InHex, AllHex);
end;
function TApdBaseDispatcher.GetDispatchTime : DWORD;
{-Return elapsed time}
begin
Result := (AdTimeGetTime - TimeBase);
end;
procedure TApdBaseDispatcher.AddDispatchEntry(
DT : TDispatchType;
DST : TDispatchSubType;
Data : Cardinal;
Buffer : Pointer;
BufferLen : Cardinal);
var
logBuf : TLogBuffer; // SWB
begin
if DLoggingOn then {!!.02}
begin // SWB
// If there is a limit to the log queue size and we have // SWB
// exceeded it, pop the oldest entries from the queue until we // SWB
// are under the limit again. // SWB
while ((DLoggingMax > 0) and // SWB
(Cardinal(DLoggingQueue.BytesQueued) > DLoggingMax)) do // SWB
begin // SWB
logBuf := TLogBuffer(DLoggingQueue.Pop); // SWB
logBuf.Free; // SWB
end; // SWB
// Add the new entry to the queue // SWB
logBuf := TLogBuffer.Create(DT, // SWB
DST, // SWB
GetDispatchTime, // SWB
Data, // SWB
PAnsiChar(Buffer), // SWB
BufferLen); // SWB
DLoggingQueue.Push(logBuf); // SWB
end; // SWB
end;
function TApdBaseDispatcher.ClassifyStatusTrigger(
TriggerHandle : Cardinal) : Cardinal;
{-Return the type for TriggerHandle}
begin
Result := TriggerHandle and StatusTypeMask;
end;
procedure TApdBaseDispatcher.SetEventBusy(
var WasOn : Boolean;
SetOn : Boolean);
{-Set/Clear the event busy flag}
begin
EnterCriticalSection(DataSection);
try
WasOn := fEventBusy;
fEventBusy := SetOn;
finally
LeaveCriticalSection(DataSection);
end;
end;
function PortIn(Address: Word): Byte;
{-Use this instead of Port since it works in both 16 and 32-bit mode}
begin
asm
mov dx,Address
in al,dx
mov @Result,al
end;
end;
procedure TApdBaseDispatcher.SetRS485Mode(OnOff : Boolean);
{-Set/reset the RS485 flag}
var
LocalBaseAddress : Word;
begin
EnterCriticalSection(DataSection);
try
RS485Mode := OnOff;
if RS485Mode then begin
{Handle entering RS485 mode}
if Assigned(OutThread) then
OutThread.Priority :=
TThreadPriority(Ord(tpHigher) + ThreadBoost);
if Win32Platform <> VER_PLATFORM_WIN32_NT then begin
{Undocumented function returns the base address in edx}
EscapeCommFunction(CidEx, 10);
asm
mov LocalBaseAddress, dx
end;
BaseAddress := LocalBaseAddress;
end;
end else begin
if Assigned(OutThread) then
OutThread.Priority :=
TThreadPriority(Ord(tpNormal) + ThreadBoost);
end;
finally
LeaveCriticalSection(DataSection);
end;
end;
procedure TApdBaseDispatcher.SetBaseAddress(NewBaseAddress : Word);
{-Set the base address}
begin
EnterCriticalSection(DataSection);
try
BaseAddress := NewBaseAddress;
finally
LeaveCriticalSection(DataSection);
end;
end;
function TApdBaseDispatcher.GetBaseAddress : Word;
{-Get the base address}
begin
Result := BaseAddress;
end;
constructor TApdDispatcherThread.Create(Disp : TApdBaseDispatcher);
begin
H := Disp;
inherited Create(False);
FreeOnTerminate := True;
end;
procedure TApdDispatcherThread.SyncEvent;
begin
pTriggerEvent(pMsg,pTrigger,plParam);
end;
procedure TApdDispatcherThread.SyncNotify(Msg, Trigger : Cardinal;
lParam : LongInt; Event : TApdNotifyEvent);
begin
pMsg := Msg;
pTrigger := Trigger;
plParam := lParam;
pTriggerEvent := Event;
Synchronize(SyncEvent);
end;
procedure TApdDispatcherThread.Sync(Method: TThreadMethod);
{- public version of Synchronize}
begin
Synchronize(Method);
end;
{Output event thread}
procedure TOutThread.Execute;
{-Wait for and process output events}
var
Res : Integer;
OutOL : TOverlapped; {For output event waiting}
function DataInBuffer : Boolean;
{indicate whether the output buffer has data to be sent}
begin
with H do begin
EnterCriticalSection(OutputSection);
try
DataInBuffer := OBufFull or (OBufHead <> OBufTail);
finally
LeaveCriticalSection(OutputSection);
end;
end;
end;
procedure ProcessOutputEvent(H : TApdBaseDispatcher);
var
NumToWrite : Integer;
NumWritten : DWORD;
Ok : Boolean;
TempBuff : POBuffer;
begin
while DataInBuffer do begin
with H do begin
EnterCriticalSection(OutputSection);
try
{Check for buffer wrap-around. If wrap around has occurred,
use a temp buffer to shuffle around the buffer contents to make the
data in the buffer reside at contiguous locations. This is done to
prevent scheduling delays in the OS from causing us to emit data with
potentially large gaps in the output stream of bytes when buffer wrap-
around occurs.}
if OBufTail < OBufHead then
NumToWrite := OBufHead - OBufTail
else begin
if (OBufHead = 0) then
NumToWrite := OutQue - OBufTail
else begin
GetMem(TempBuff, OBufHead);
Move(OBuffer^, TempBuff^, SizeOf( OBufHead)); // --sm check
// Move(OBuffer^[OBufTail], OBuffer^, OutQue - OBufTail);
Move(GetPtr(OBuffer, OBufTail)^, OBuffer^, (OutQue - OBufTail));// --sm check
// Move(TempBuff^, OBuffer^[OutQue - OBufTail], OBufHead);
Move(TempBuff^, GetPtr(OBuffer, (OutQue - OBufTail))^, OBufHead);// --sm check
FreeMem(TempBuff);
Inc(OBufHead, OutQue - OBufTail);
NumToWrite := OBufHead;
OBufTail := 0;
end;
end;
finally
LeaveCriticalSection(OutputSection);
end;
// Ok := WriteFile(CidEx,
// OBuffer^[OBufTail],
// NumToWrite,
// NumWritten,
// @OutOL);
Ok := WriteFile(CidEx,
GetPtr(OBuffer, OBufTail)^,
NumToWrite,
NumWritten,
@OutOL);
if not Ok then begin
if GetLastError = ERROR_IO_PENDING then begin
{expected -- write is pending}
{$IFDEF DebugThreadConsole}
Writeln(ThreadStatus(OutSleep));
{$ENDIF}
Res := WaitForMultipleObjects(2,
@OutWaitObjects2,
False,
INFINITE);
{$IFDEF DebugThreadConsole}
Writeln(ThreadStatus(OutWake));
{$ENDIF}
case Res of
WAIT_OBJECT_0 :
begin
{overlapped i/o completed}
if GetOverLappedResult(CidEx, OutOL, NumWritten, False) then begin
EnterCriticalSection(OutputSection);
try
Inc(OBufTail, NumWritten);
if(OBufTail = OutQue) then
OBufTail := 0;
{ If nothing left in the buffer, reset the }
{ queue to avoid buffer wrap-arounds. }
if(OBufTail = OBufHead) then begin
OBufTail := 0;
OBufHead := 0;
end;
OBufFull := False;
ResetEvent(OutOL.hEvent);
finally
LeaveCriticalSection(OutputSection);
end;
end else begin
{GetOverLappedResult failed.}
end;
end;
WAIT_OBJECT_0 + 1 :
begin
{flush buffer requested, acknowledge and exit}
SetEvent(GeneralEvent);
Exit;
end;
WAIT_TIMEOUT :
{couldn't send all data}
else
{an unexpected error occurred with WaitForMultipleObjects}
end;
end else begin
{WriteFile failed, but not because of delayed write}
{ Give up on sending this block, update the queue
pointers, and continue. We get here if we lose
carrier during a transmit, and if we continue to
try to resend the data, we'll loop forever.}
EnterCriticalSection(OutputSection);
try
inc(OBufTail, NumToWrite);
if (OBufTail = OutQue) then
OBufTail := 0;
{ If nothing left in the buffer, reset the queue }
{ to avoid buffer wrap-arounds }
if (OBufTail = OBufHead) then begin
OBufTail := 0;
OBufHead := 0;
end;
OBufFull := False;
finally
LeaveCriticalSection(OutputSection);
end;
end;
end else begin
{ WriteFile completed immediately -- update buffer pointer }
EnterCriticalSection(OutputSection);
try
Inc(OBufTail, NumWritten);
if (OBufTail = OutQue) then
OBufTail := 0;
{ If nothing left in the buffer, reset the queue to }
{ avoid buffer wrap-arounds }
if (OBufTail = OBufHead) then begin
OBufTail := 0;
OBufHead := 0;
end;
OBufFull := False;
finally
LeaveCriticalSection(OutputSection);
end;
end;
{No more data in buffer, if in RS485 mode wait for TE}
if Win32Platform <> VER_PLATFORM_WIN32_NT then
if RS485Mode then begin
repeat
until (PortIn(BaseAddress+5) and $40) <> 0;
SetRTS(False);
end;
end;
end;
end;
begin
InterLockedIncrement(H.ActiveThreads);
try
FillChar(OutOL, SizeOf(OutOL), #0);
with H do begin
{set the event used for overlapped i/o to signal completion}
OutOL.hEvent := SentEvent;
{Ready to go, set the general event}
SetEvent(GeneralEvent);
{Repeat until port is closed}
repeat
{Wait for either an output event or a flush event}
{$IFDEF DebugThreadConsole}
Writeln(ThreadStatus(OutSleep));
{$ENDIF}
Res := WaitForMultipleObjects(2,
@OutWaitObjects1,
False,
INFINITE);
{$IFDEF DebugThreadConsole}
Writeln(ThreadStatus(OutWake));
{$ENDIF}
case Res of
WAIT_OBJECT_0 :
begin
{output event}
{Exit immediately if thread was killed while waiting}
if KillThreads then begin
{Finished here, okay to close the port}
H.ThreadGone(Self);
Exit;
end;
{We have data to send, so process it...}
ProcessOutputEvent(H);
end;
WAIT_OBJECT_0 + 1 :
begin
{flush buffer requested, acknowledge and continue}
SetEvent(GeneralEvent);
end;
else
{unexpected problem with WaitFor}
end;
until KillThreads or ClosePending;
end;
H.ThreadGone(Self);
except
ShowException(ExceptObject,ExceptAddr);
end;
end;
{Communications event thread}
procedure TComThread.Execute;
{-Wait for and process communications events}
var
Junk : DWORD;
LastMask : LongInt;
Timeouts : TCommTimeouts;
ComOL : TOverlapped; {For com event waiting}
begin
InterLockedIncrement(H.ActiveThreads);
try
FillChar(ComOL, SizeOf(ComOL), #0);
with H do begin
ComOL.hEvent := CreateEvent(nil, True, False, nil);
{Set our standard win32 events}
{ Note, NuMega's BoundsChecker will flag a bogus error on the }
{ following statement because we use the undocumented ring_te flag }
if Win32Platform = VER_PLATFORM_WIN32_NT then
LastMask := DefEventMask and not ev_RingTe
else
LastMask := DefEventMask;
SetCommMask(CidEx, LastMask);
FillChar(Timeouts, SizeOf(TCommTimeouts), 0);
Timeouts.ReadIntervalTimeout := MaxDWord;
SetCommTimeouts(CidEx, Timeouts);
{Ready to go, set the general event}
SetEvent(GeneralEvent);
{Repeat until port is closed}
repeat
{$IFDEF DebugThreadConsole}
Writeln(ThreadStatus(ComSleep));
{$ENDIF}
{Release time slice until we get a communications event}
if not WaitComEvent(CurrentEvent, @ComOL) then begin
if GetLastError = ERROR_IO_PENDING then begin
if GetOverLappedResult(CidEx,
ComOL,
Junk,
True) then begin
{WIN32 bug workaround: Apro gets the modem status bits
with a call (later) to GetCommModemStatus. Unfortunately,
that routine never seems to return either RI or TERI.
So, we note either EV_RING or EV_RINGTE here and later
manually merge the TERI bit into ModemStatus.}
if ((CurrentEvent and EV_RINGTE) <> 0) or
((CurrentEvent and EV_RING) <> 0) then
RingFlag := True;
{Read complete, reset event}
ResetEvent(ComOL.hEvent);
end else begin
{Port closed or other fatal condition, just exit the thread}
SetEvent(GeneralEvent);
CloseHandle(ComOL.hEvent);
H.ThreadGone(Self);
Exit;
end;
end else begin
{ If we get an ERROR_INVALID_PARAMETER, we assume it's our }
{ use of ev_RingTe -- clear the flag and try again }
if (GetLastError = ERROR_INVALID_PARAMETER) and
(LastMask and EV_RINGTE <> 0) then begin
LastMask := DefEventMask and not EV_RINGTE;
SetCommMask(CidEx, LastMask);
end;
end;
end;
{Exit immediately if thread was killed while waiting}
if KillThreads then begin
SetEvent(GeneralEvent);
CloseHandle(ComOL.hEvent);
H.ThreadGone(Self);
Exit;
end;
{$IFDEF DebugThreadConsole}
Writeln(ThreadStatus(ComWake));
{$ENDIF}
{Signal com event}
SetEvent(ComEvent);
{$IFDEF DebugThreadConsole}
Writeln(ThreadStatus(ComSleep));
{$ENDIF}
{Wait for the dispatcher thread to complete}
WaitForSingleObject(ReadyEvent, INFINITE);
{$IFDEF DebugThreadConsole}
Writeln(ThreadStatus(ComWake));
{$ENDIF}
until KillThreads;
{Finished here, okay to close the port}
SetEvent(GeneralEvent);
end;
CloseHandle(ComOL.hEvent);
H.ThreadGone(Self);
except
ShowException(ExceptObject,ExceptAddr);
end;
end;
procedure TDispThread.Execute;
{-Wait for and process communications events}
procedure ProcessComEvent(H : TApdBaseDispatcher);
{$IFNDEF UseAwWin32} // SWB
var // SWB
bfr : TIOBuffer; // SWB
{$ENDIF} // SWB
begin
with H do begin
{$IFNDEF UseAwWin32} // SWB
// Read the first status packet from the queue & copy its contents // SWB
// to CurrentEvent so that the status event handlers can process it.// SWB
bfr := FQueue.Peek; // SWB
if (Assigned(bfr)) then // SWB
begin // SWB
if (bfr is TStatusBuffer) then // SWB
begin // SWB
CurrentEvent := TStatusBuffer(bfr).Status; // SWB
FQueue.Pop; // SWB
TStatusBuffer(bfr).Free; // KGM
end else // SWB
begin // SWB
bfr.InUse := False; // SWB
CurrentEvent := 0; // SWB
end; // SWB
end else // SWB
CurrentEvent := 0; // SWB
{WIN32 bug workaround: Apro gets the modem status bits // SWB
with a call (later) to GetCommModemStatus. Unfortunately, // SWB
that routine never seems to return either RI or TERI. // SWB
So, we note either EV_RING or EV_RINGTE here and later // SWB
manually merge the TERI bit into ModemStatus.} // SWB
if ((CurrentEvent and (EV_RINGTE or EV_RING)) <> 0) then // SWB
RingFlag := True; // SWB
{$ENDIF} // SWB
{Check for modem events}
if CurrentEvent and ModemEvent <> 0 then begin
{A modem status event...}
MapEventsToMS(CurrentEvent);
{Check for status triggers}
if not fEventBusy then begin
while CheckStatusTriggers do
if ClosePending then
Exit;
{Allow status triggers to hit again}
if GlobalStatHit then
ResetStatusHits;
end;
end;
{Check for line events}
if CurrentEvent and LineEvent <> 0 then begin
{A line status/error event}
RefreshStatus;
{Check for status triggers}
if not fEventBusy then begin
while CheckStatusTriggers do
if ClosePending then
Exit;
{Allow status triggers to hit again}
if GlobalStatHit then
ResetStatusHits;
end;
end;
{ Get any available data }
ExtractData;
{Check for received status & data triggers}
if not fEventBusy then begin
ModemStatus := GetModemStatus; {!!.06}
while CheckStatusTriggers do
if ClosePending then
Exit;
while CheckReceiveTriggers do
if ClosePending then
Exit;
end;
if GlobalStatHit then
ResetStatusHits;
{Let the com thread continue...}
SetEvent(ReadyEvent);
end;
end;
procedure ProcessTimer(H : TApdBaseDispatcher);
begin
with H do begin
if ClosePending then
Exit;
if not fEventBusy then begin
GlobalStatHit := False;
{Issue all status and timer triggers}
while (CheckStatusTriggers or CheckTimerTriggers) and not ClosePending do
;
{Allow status triggers to hit again}
if GlobalStatHit then
ResetStatusHits;
end else begin
end;
end;
end;
begin
InterLockedIncrement(H.ActiveThreads);
try
with H do begin
try
{Ready to go, set the general event}
SetEvent(GeneralEvent);
{Repeat until port is closed}
repeat
{$IFDEF DebugThreadConsole}
Writeln(ThreadStatus(DispSleep));
{$ENDIF}
{Wait for either a com event or a timeout}
{$IFDEF UseAwWin32} // SWB
WaitForSingleObject(ComEvent, 50); // SWB
{$ELSE} // SWB
FQueue.WaitForBuffer(50); // SWB
{$ENDIF} // SWB
{$IFDEF DebugThreadConsole}
Writeln(ThreadStatus(DispWake));
{$ENDIF}
{Exit immediately if thread was killed while waiting}
if KillThreads then begin
{Finished here, okay to close the port}
Exit;
end;
{Process it...}
ProcessComEvent(H);
ProcessTimer(H);
until KillThreads or ClosePending;
{Finished here, okay to close the port}
SetEvent(GeneralEvent);
finally
{ Make sure DonePortPrim gets called }
DoDonePortPrim := (ClosePending or KillThreads);
{$IFDEF DebugThreadConsole}
Writeln(ThreadStatus(DispKill));
{$ENDIF}
H.ThreadGone(Self);
end;
end;
except
ShowException(ExceptObject,ExceptAddr);
end;
end;
procedure LockPortList;
begin
EnterCriticalSection(PortListSection);
end;
procedure UnlockPortList;
begin
LeaveCriticalSection(PortListSection);
end;
procedure FinalizeUnit; far;
begin
PortList.Free;
PortList := nil;
end;
procedure InitializeUnit;
begin
PortList := TList.Create;
FillChar(PortListSection, SizeOf(PortListSection), 0);
InitializeCriticalSection(PortListSection);
end;
initialization // SZ FIXME loader lock
InitializeUnit;
finalization
FinalizeUnit;
DeleteCriticalSection(PortListSection);
end.