forked from P33a/SimTwo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathenum_serial.pas
116 lines (95 loc) · 2.6 KB
/
enum_serial.pas
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
unit enum_serial;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils
{$IFDEF Windows}
,windows
{$ENDIF}
{$ifdef Linux}
,BaseUnix
{$ENDIF};
procedure ListComPorts(SL: TStrings);
implementation
{$IFDEF Windows}
procedure ListComPorts(SL: TStrings);
var i: integer;
securityAttributes: TSecurityAttributes;
ret: THandle;
GoodCom: boolean;
DeviceName: string;
dwError: DWORD;
begin
securityAttributes.nLength := SizeOf(TSecurityAttributes);
securityAttributes.lpSecurityDescriptor := nil;
securityAttributes.bInheritHandle := true;
SL.Clear;
for i := 1 to 64 do begin
GoodCom := FALSE;
//ATL::CHandle port(CreateFile(szPort, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0));
DeviceName := '\\.\COM' + IntToStr(i);
//ret := fileCreate(DeviceName, GENERIC_READ or GENERIC_WRITE);
ret := CreateFile(
PChar(DeviceName),
GENERIC_READ or GENERIC_WRITE,
0,
@securityAttributes,
OPEN_EXISTING,
0,
0);
if (ret = INVALID_HANDLE_VALUE) then begin
dwError := GetLastError();
//Check to see if the error was because some other app had the port open or a general failure
if (dwError = ERROR_ACCESS_DENIED) or (dwError = ERROR_GEN_FAILURE) or (dwError = ERROR_SHARING_VIOLATION) or (dwError = ERROR_SEM_TIMEOUT) then begin
GoodCom := TRUE;
end;
end else begin
//The port was opened successfully
GoodCom := TRUE;
CloseHandle(ret);
end;
if GoodCom then begin
SL.Add(DeviceName);
end;
end;
end;
{$ENDIF}
{$ifdef Linux}
procedure ListComPorts(SL: TStrings);
var i: integer;
ret: THandle;
GoodCom: boolean;
DeviceName: string;
dwError: DWORD;
begin
SL.Clear;
for i := 0 to 16 do begin
GoodCom := FALSE;
DeviceName := '/dev/ttyACM' + IntToStr(i);
//ret := fileCreate(DeviceName, fmOpenRead or fmOpenWrite);
ret := fpopen(DeviceName, O_RDWR or O_NOCTTY);
if (ret = feInvalidHandle) then begin
dwError := GetLastOSError();
//Check to see if the error was because some other app had the port open or a general failure
//if (dwError = EACCES) then begin
// GoodCom := TRUE;
//end;
end else begin
//The port was opened successfully
GoodCom := TRUE;
end;
if GoodCom then begin
SL.Add(DeviceName);
end;
end;
for i := 0 to 16 do begin
DeviceName := '/dev/ttyUSB' + IntToStr(i);
ret := fpopen(DeviceName, O_RDWR or O_NOCTTY);
if (ret <> feInvalidHandle) then begin
SL.Add(DeviceName);
fpclose(ret);
end;
end;
end;
{$ENDIF}
end.