?? commcode.c
字號:
// Write thread what to write provides a natural desynchronization between
// the UI and the Write thread.
//
//
DWORD WINAPI StartWriteThreadProc(LPVOID lpvParam)
{
MSG msg;
DWORD dwHandleSignaled;
// Needed for overlapped I/O.
OVERLAPPED overlappedWrite = {0, 0, 0, 0, NULL};
overlappedWrite.hEvent = CreateEvent(NULL, TRUE, TRUE, NULL);
if (overlappedWrite.hEvent == NULL)
{
OutputDebugLastError(GetLastError(), "Unable to CreateEvent: ");
PostHangupCall();
goto EndWriteThread;
}
// This is the main loop. Loop until we break out.
while (TRUE)
{
if (!PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
// If there are no messages pending, wait for a message or
// the CloseEvent.
dwHandleSignaled =
MsgWaitForMultipleObjects(1, &g_hCloseEvent, FALSE,
INFINITE, QS_ALLINPUT);
switch(dwHandleSignaled)
{
case WAIT_OBJECT_0: // CloseEvent signaled!
{
// Time to exit.
goto EndWriteThread;
}
case WAIT_OBJECT_0 + 1: // New message was received.
{
// Get the message that woke us up by looping again.
continue;
}
case WAIT_FAILED: // Wait failed. Shouldn't happen.
{
OutputDebugLastError(GetLastError(),"Write WAIT_FAILED: ");
PostHangupCall();
goto EndWriteThread;
}
default: // This case should never occur.
{
OutputDebugPrintf("Unexpected Wait return value '%lx'",
dwHandleSignaled);
PostHangupCall();
goto EndWriteThread;
}
}
}
// Make sure the CloseEvent isn't signaled while retrieving messages.
if (WAIT_TIMEOUT != WaitForSingleObject(g_hCloseEvent,0))
goto EndWriteThread;
// Process the message.
// This could happen if a dialog is created on this thread.
// This doesn't occur in this sample, but might if modified.
if (msg.hwnd != NULL)
{
TranslateMessage(&msg);
DispatchMessage(&msg);
continue;
}
// Handle the message.
switch(msg.message)
{
case PWM_COMMWRITE: // New string to write to Comm port.
{
OutputDebugString("Writing to comm port\n");
// Write the string to the comm port. HandleWriteData
// does not return until the whole string has been written,
// an error occurs or until the CloseEvent is signaled.
if (!HandleWriteData(&overlappedWrite,
(LPSTR) msg.lParam, (DWORD) msg.wParam))
{
// If it failed, either we got a signal to end or there
// really was a failure.
LocalFree((HLOCAL) msg.lParam);
goto EndWriteThread;
}
// Data was sent in a LocalAlloc()d buffer. Must free it.
LocalFree((HLOCAL) msg.lParam);
break;
}
// What other messages could the thread get?
default:
{
char Output[256];
wsprintf(Output,
"Unexpected message posted to Write thread: %ui\n",
msg.message );
OutputDebugString(Output);
break;
}
} // End of switch(message)
} // End of main loop.
// Thats the end. Now clean up.
EndWriteThread:
OutputDebugString("Write thread shutting down\n");
PurgeComm(g_hCommFile, PURGE_TXABORT | PURGE_TXCLEAR);
CloseHandle(overlappedWrite.hEvent);
g_dwWriteThreadID = 0;
CloseHandle(g_hWriteThread);
g_hWriteThread = 0;
return 0;
}
//
// FUNCTION: HandleWriteData(LPOVERLAPPED, LPCSTR, DWORD)
//
// PURPOSE: Writes a given string to the comm file handle.
//
// PARAMETERS:
// lpOverlappedWrite - Overlapped structure to use in WriteFile
// lpszStringToWrite - String to write.
// dwNumberOfBytesToWrite - Length of String to write.
//
// RETURN VALUE:
// TRUE if all bytes were written. False if there was a failure to
// write the whole string.
//
// COMMENTS:
//
// This function is a helper function for the Write Thread. It
// is this call that actually writes a string to the comm file.
// Note that this call blocks and waits for the Write to complete
// or for the CloseEvent object to signal that the thread should end.
// Another possible reason for returning FALSE is if the comm port
// is closed by the service provider.
//
//
BOOL HandleWriteData(LPOVERLAPPED lpOverlappedWrite,
LPCSTR lpszStringToWrite, DWORD dwNumberOfBytesToWrite)
{
DWORD dwLastError;
DWORD dwNumberOfBytesWritten = 0;
DWORD dwWhereToStartWriting = 0; // Start at the beginning.
DWORD dwHandleSignaled;
HANDLE HandlesToWaitFor[2];
HandlesToWaitFor[0] = g_hCloseEvent;
HandlesToWaitFor[1] = lpOverlappedWrite -> hEvent;
// Keep looping until all characters have been written.
do
{
// Start the overlapped I/O.
if (!WriteFile(g_hCommFile,
&lpszStringToWrite[ dwWhereToStartWriting ],
dwNumberOfBytesToWrite, &dwNumberOfBytesWritten,
lpOverlappedWrite))
{
// WriteFile failed. Expected; lets handle it.
dwLastError = GetLastError();
// Its possible for this error to occur if the
// service provider has closed the port. Time to end.
if (dwLastError == ERROR_INVALID_HANDLE)
{
OutputDebugString("ERROR_INVALID_HANDLE, "
"Likely that the Service Provider has closed the port.\n");
return FALSE;
}
// Unexpected error. No idea what.
if (dwLastError != ERROR_IO_PENDING)
{
OutputDebugLastError(dwLastError,
"Error to writing to CommFile");
OutputDebugString("Closing TAPI\n");
PostHangupCall();
return FALSE;
}
// This is the expected ERROR_IO_PENDING case.
// Wait for either overlapped I/O completion,
// or for the CloseEvent to get signaled.
dwHandleSignaled =
WaitForMultipleObjects(2, HandlesToWaitFor,
FALSE, INFINITE);
switch(dwHandleSignaled)
{
case WAIT_OBJECT_0: // CloseEvent signaled!
{
// Time to exit.
return FALSE;
}
case WAIT_OBJECT_0 + 1: // Wait finished.
{
// Time to get the results of the WriteFile
break;
}
case WAIT_FAILED: // Wait failed. Shouldn't happen.
{
OutputDebugLastError(GetLastError(),
"Write WAIT_FAILED: ");
PostHangupCall();
return FALSE;
}
default: // This case should never occur.
{
OutputDebugPrintf(
"Unexpected Wait return value '%lx'",
dwHandleSignaled);
PostHangupCall();
return FALSE;
}
}
if (!GetOverlappedResult(g_hCommFile,
lpOverlappedWrite,
&dwNumberOfBytesWritten, TRUE))
{
dwLastError = GetLastError();
// Its possible for this error to occur if the
// service provider has closed the port.
if (dwLastError == ERROR_INVALID_HANDLE)
{
OutputDebugString("ERROR_INVALID_HANDLE, "
"Likely that the Service Provider has closed the port.\n");
return FALSE;
}
// No idea what could cause another error.
OutputDebugLastError(dwLastError,
"Error writing to CommFile while waiting");
OutputDebugString("Closing TAPI\n");
PostHangupCall();
return FALSE;
}
}
// Some data was written. Make sure it all got written.
dwNumberOfBytesToWrite -= dwNumberOfBytesWritten;
dwWhereToStartWriting += dwNumberOfBytesWritten;
}
while(dwNumberOfBytesToWrite > 0); // Write the whole thing!
// Wrote the whole string.
return TRUE;
}
//
// FUNCTION: StartReadThreadProc(LPVOID)
//
// PURPOSE: This is the starting point for the Read Thread.
//
// PARAMETERS:
// lpvParam - unused.
//
// RETURN VALUE:
// DWORD - unused.
//
// COMMENTS:
//
// The Read Thread uses overlapped ReadFile and sends any strings
// read from the comm port to the UI to be printed. This is
// eventually done through a PostMessage so that the Read Thread
// is never away from the comm port very long. This also provides
// natural desynchronization between the Read thread and the UI.
//
// If the CloseEvent object is signaled, the Read Thread exits.
//
// Note that there is absolutely *no* interpretation of the data,
// which means no terminal emulation. It basically means that this
// sample is pretty useless as a TTY program.
//
// Separating the Read and Write threads is natural for a application
// like this sample where there is no need for synchronization between
// reading and writing. However, if there is such a need (for example,
// most file transfer algorithms synchronize the reading and writing),
// then it would make a lot more sense to have a single thread to handle
// both reading and writing.
//
//
DWORD WINAPI StartReadThreadProc(LPVOID lpvParam)
{
char szInputBuffer[INPUTBUFFERSIZE];
DWORD nNumberOfBytesRead;
HANDLE HandlesToWaitFor[3];
DWORD dwHandleSignaled;
DWORD fdwEvtMask;
// Needed for overlapped I/O (ReadFile)
OVERLAPPED overlappedRead = {0, 0, 0, 0, NULL};
// Needed for overlapped Comm Event handling.
OVERLAPPED overlappedCommEvent = {0, 0, 0, 0, NULL};
// Lets put an event in the Read overlapped structure.
overlappedRead.hEvent = CreateEvent(NULL, TRUE, TRUE, NULL);
if (overlappedRead.hEvent == NULL)
{
OutputDebugLastError(GetLastError(), "Unable to CreateEvent: ");
PostHangupCall();
goto EndReadThread;
}
// And an event for the CommEvent overlapped structure.
overlappedCommEvent.hEvent = CreateEvent(NULL, TRUE, TRUE, NULL);
if (overlappedCommEvent.hEvent == NULL)
{
OutputDebugLastError(GetLastError(), "Unable to CreateEvent: ");
PostHangupCall();
goto EndReadThread;
}
// We will be waiting on these objects.
HandlesToWaitFor[0] = g_hCloseEvent;
HandlesToWaitFor[1] = overlappedCommEvent.hEvent;
HandlesToWaitFor[2] = overlappedRead.hEvent;
// Setup CommEvent handling.
// Set the comm mask so we receive error signals.
if (!SetCommMask(g_hCommFile, EV_ERR))
{
OutputDebugLastError(GetLastError(),"Unable to SetCommMask: ");
PostHangupCall();
goto EndReadThread;
}
// Start waiting for CommEvents (Errors)
if (!SetupCommEvent(&overlappedCommEvent, &fdwEvtMask))
{
PostHangupCall();
goto EndReadThread;
}
// Start waiting for Read events.
if (!SetupReadEvent(&overlappedRead,
szInputBuffer, INPUTBUFFERSIZE,
&nNumberOfBytesRead))
{
PostHangupCall();
goto EndReadThread;
}
// Keep looping until we break out.
while (TRUE)
{
// Wait until some event occurs (data to read; error; stopping).
dwHandleSignaled =
WaitForMultipleObjects(3, HandlesToWaitFor,
FALSE, INFINITE);
// Which event occured?
switch(dwHandleSignaled)
{
case WAIT_OBJECT_0: // Signal to end the thread.
{
// Time to exit.
goto EndReadThread;
}
case WAIT_OBJECT_0 + 1: // CommEvent signaled.
{
// Handle the CommEvent.
if (!HandleCommEvent(&overlappedCommEvent, &fdwEvtMask, TRUE))
{
PostHangupCall();
goto EndReadThread;
}
// Start waiting for the next CommEvent.
if (!SetupCommEvent(&overlappedCommEvent, &fdwEvtMask))
{
PostHangupCall();
goto EndReadThread;
}
break;
}
case WAIT_OBJECT_0 + 2: // Read Event signaled.
{
// Get the new data!
if (!HandleReadEvent(&overlappedRead,
szInputBuffer, INPUTBUFFERSIZE,
&nNumberOfBytesRead))
{
PostHangupCall();
goto EndReadThread;
}
// Wait for more new data.
if (!SetupReadEvent(&overlappedRead,
szInputBuffer, INPUTBUFFERSIZE,
&nNumberOfBytesRead))
{
PostHangupCall();
goto EndReadThread;
}
break;
}
case WAIT_FAILED: // Wait failed. Shouldn't happen.
OutputDebugLastError(GetLastError(),"Read WAIT_FAILED: ");
goto EndReadThread;
?? 快捷鍵說明
復(fù)制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -