15,471
社区成员
发帖
与我相关
我的任务
分享
//执行Dlg工作线程
static DWORD WINAPI RunCmcucontrollerDlg_Thread(LPVOID arg)
{
CmcucontrollerDlg *dlg = (CmcucontrollerDlg *)arg;
return dlg->uartWorkThread();
}
//创建信号量
this->readSem = CreateSemaphore(0, 0, 1, 0);
if (this->readSem == NULL)
{
CString str;
DWORD errCode;
errCode = GetLastError();
str.Format(L"创建信号量失败,错误(%d):%s", errCode, GetLastErrorToString(errCode));
::MessageBox(0, str, L"初始化失败", MB_OK);
AfxGetMainWnd()->SendMessage(WM_CLOSE);
return FALSE;
}
//创建工作线程
uartWorkHandle = CreateThread(NULL, 0, RunCmcucontrollerDlg_Thread, (LPVOID)this, 0, &uartWorkThreadId);
if (uartWorkHandle == NULL)
{
CString str;
DWORD errCode;
errCode = GetLastError();
str.Format(L"创建工作线程失败,错误(%d):%s", errCode, GetLastErrorToString(errCode));
::MessageBox(0, str, L"初始化失败", MB_OK);
AfxGetMainWnd()->SendMessage(WM_CLOSE);
}
//打开串口
this->uartHandle = CreateFileW(str,
GENERIC_READ | GENERIC_WRITE,
0,
NULL,
OPEN_EXISTING,
0,
NULL);
if (!this->uartHandle || this->uartHandle == INVALID_HANDLE_VALUE)
{
this->uartHandle = 0;
errCode = GetLastError();
str.Format(L"串口打开失败,错误(%d):%s", errCode, GetLastErrorToString(errCode));
::MessageBox(0, str, L"打开失败", MB_OK);
return;
}
//设置串口参数
errCode = SetUartParam(this->uartHandle,
baudrate,
dataBits,
parityCheck,
stopBits);
if (errCode)
{
CloseHandle(this->uartHandle);
this->uartHandle = 0;
str.Format(L"串口参数设置失败,错误(%d):%s", errCode, GetLastErrorToString(errCode));
::MessageBox(0, str, L"串口设置失败", MB_OK);
return;
}
//通知线程接收数据
::ReleaseSemaphore(this->readSem, 1, NULL);
DWORD CmcucontrollerDlg::uartWorkThread()
{
HWND hwnd = this->GetSafeHwnd();
while (1)
{
WaitForSingleObject(this->readSem, INFINITE);
if (this->uartWorkerTheadExit)
{
break;
}
//读取串口
if (ReadFile(this->uartHandle, this->recvBuffer, sizeof(this->recvBuffer), &this->recvCount, NULL))
{
this->recvError = 0;
}
else
{
this->recvError = GetLastError();
}
//通知主线程
::PostMessage(hwnd, WM_ON_UART_READ, 0, 0);
}
return 0;
}
//关闭串口
if (this->uartHandle)
{
CloseHandle(this->uartHandle);
this->uartHandle = NULL;
openButton->SetWindowTextW(L"打开");
portsBox->EnableWindow(true);
baudrateBox->EnableWindow(true);
dataBitsBox->EnableWindow(true);
parityCheckBox->EnableWindow(true);
stopBitsBox->EnableWindow(true);
dataTimeoutBox->EnableWindow(true);
}
//关闭串口
if (this->uartHandle)
{
//取消读操作
CancelSynchronousIo(this->uartWorkHandle);
//关闭串口
CloseHandle(this->uartHandle);
this->uartHandle = NULL;
openButton->SetWindowTextW(L"打开");
portsBox->EnableWindow(true);
baudrateBox->EnableWindow(true);
dataBitsBox->EnableWindow(true);
parityCheckBox->EnableWindow(true);
stopBitsBox->EnableWindow(true);
dataTimeoutBox->EnableWindow(true);
}