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
| function MPUSBOpen(instance : DWord; pVID_PID, pEP : PChar;
dwDir, dwReserved : DWord) = Handle;
var PathArr, PathIOArr : array[0..MAX_PATH-1] of Char;
Path, PathIO : PChar;
dwReqLen : DWord;
begin
Result := INVALID_HANDLE_VALUE;
Path := @PathArr[0];
PathIO := @PathIOArr[0];
// Check arguments first
if (pVID_PID <> nil) and ((dwDir = MP_WRITE) or (dwDir == MP_READ)) then
begin
StrCopy(PathIO, Path);
if (pEP <> nil) then
StrCat(PathIO, pEP);
if dwDir == MP_READ then
begin
Result := CreateFile(PathIO, GENERIC_READ, 0, nil, OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL or FILE_FLAG_OVERLAPPED, nil);
end else
begin
Result := CreateFile(PathIO, GENERIC_WRITE, 0, nil, OPEN_EXISTNG,
FILE_ATTRIBUTE_NORMAL or FILE_FLAG_OVERLAPPED, nil);
end;
end;
end;
function MPUSBRead(hand : Handle; pData : Pointer; dwLen : DWord;
pLength : PDWord; dwMillisecons : DWord) : DWord;
var bResult : DWordBool;
nBytesRead : DWord;
gOverlapped : OVERLAPPED;
begin
Result := MPUSB_FAIL;
// set up overlapped structure fields
with gOverlapped do
begin
Internal := 0;
InternalHigh := 0;
Offset := 0;
OffsetHigh := 0;
hEvent := CreateEvent(nil, False, False, nil);
end;
if pLength <> nil then
pLength^ := 0;
// attemps an asynchronous read operation
bResult := ReadFile(hand, pData, dwLen, @nBytesRead, @gOverlapped);
if not bResult then
begin
// deal with error code
case GetLastError() of
ERROR_HANCLE_EOF : ; // reached end of file during ReadFile
ERROR_IO_PENDING :
begin
case WaitForSingleObject(gOverlapped.hEvent, dwMilliseconds) of
WAIT_OBJECT_0 :
begin
// check on the results of the asynchronous read
// and update the nBytesRead...
bResult := GetOverlappedResult(hand,
@gOverlapped, @nBytesRead, False);
if not bResult) then WriteLn('Error: ', GetLastError()) else
begin
if pLength <> nil then
pLength^ := nBytesRead;
Result := MPUSB_SUCCESS;
end;
end;
WAIT_TIME_OUT : CancelIo(hand);
else CancelIo(hand);
end;
end;
else CancelIo(hand);
end;
end else
begin
if pLength <> nil then
pLength^ := nBytesRead;
Result := MPUSB_SUCCESS;
end;
ResetEvent(gOverlapped.hEvent);
CloseHandle(gOverlapped.hEvent);
end; |