Click here to Skip to main content
15,889,034 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i have tried below code in win32 api. before create the thread i used to wait of data while loop. that time receving is work fine but when i create the thread as in below i am getting error in setCommask and waitCommask... what is the error on that...

error shows according to the my app output

Error! in Setting CommMask
Error! in Setting WaitCommEvent()

What I have tried:

C++
//header file
#include 
#include "Serial.h"
#include  "resource.h"
#include 


#define AMOUNT_TO_READ          512

HANDLE hComm;                          // Handle to the Serial port
char  ComPortName[] = "\\\\.\\COM5";  // Name of the Serial port(May Change) to be opened,
BOOL  Status;                          // Status of the various operations 
                    // Event mask to trigger
char  TempChar;                        // Temperory Character
char  lpBuf[AMOUNT_TO_READ];               // Buffer Containing Rxed Data
DWORD NoBytesRead;                     // Bytes read by ReadFile()
int i = 0;

BOOL flag;
HANDLE readerThread;
DWORD readThreadID;


void show(char*);

C++
// Cpp file
#include "Main.h"

HWND windowG;
bool wirtePort()
{
	char   lpBuffer[] = "A";		       // lpBuffer should be  char or byte array, otherwise write wil fail
	DWORD  dNoOFBytestoWrite;              // No of bytes to write into the port
	DWORD  dNoOfBytesWritten = 0;          // No of bytes written to the port

	dNoOFBytestoWrite = sizeof(lpBuffer); // Calculating the no of bytes to write into the port

	Status = WriteFile(hComm,               // Handle to the Serialport
		lpBuffer,            // Data to be written to the port 
		dNoOFBytestoWrite,   // No of bytes to write into the port
		&dNoOfBytesWritten,  // No of bytes written to the port
		NULL);

	//if (Status == TRUE)
	//show("\n\n    %s - Written to %s", lpBuffer, ComPortName);
	//else
	//show("\n\n   Error %d in Writing to Serial Port", GetLastError());
	return 0;
}
void ErrorExit(LPTSTR lpszFunction)
{
	// Retrieve the system error message for the last-error code

	LPVOID lpMsgBuf;
	LPVOID lpDisplayBuf;
	DWORD dw = GetLastError();

	FormatMessage(
		FORMAT_MESSAGE_ALLOCATE_BUFFER |
		FORMAT_MESSAGE_FROM_SYSTEM |
		FORMAT_MESSAGE_IGNORE_INSERTS,
		NULL,
		dw,
		MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
		(LPTSTR)&lpMsgBuf,
		0, NULL);

	// Display the error message and exit the process

	lpDisplayBuf = (LPVOID)LocalAlloc(LMEM_ZEROINIT,
		(lstrlen((LPCTSTR)lpMsgBuf) + lstrlen((LPCTSTR)lpszFunction) + 40) * sizeof(TCHAR));
	StringCchPrintf((LPTSTR)lpDisplayBuf,
		LocalSize(lpDisplayBuf) / sizeof(TCHAR),
		TEXT("%s failed with error %d: %s"),
		lpszFunction, dw, lpMsgBuf);
	MessageBox(NULL, (LPCTSTR)lpDisplayBuf, TEXT("Error"), MB_OK);

	LocalFree(lpMsgBuf);
	LocalFree(lpDisplayBuf);
	ExitProcess(dw);
}
bool readPort(LPVOID lpV)
{
	HANDLE tCom = (HANDLE)lpV;
	DWORD dwEventMask;

	//Configure Windows to Monitor the serial device for Character Reception
	Status = SetCommMask(tCom, EV_RXCHAR); 

	if (Status == FALSE)
		show("\n\n    Error! in Setting CommMask");
	else
		show("\n\n    Setting CommMask successfull");

	while (true)
	{
		i = 0;
		//Setting WaitComm() Event 

		//printf("\n\n    Waiting for Data Reception");

		Status = WaitCommEvent(tCom, &dwEventMask, NULL); //Wait for the character to be received
		
		// Program will Wait here till a Character is received 

		if (Status == FALSE)
		{
			
			show("\n    Error! in Setting WaitCommEvent()");
	
			ErrorExit(TEXT("WaitCommEvent"));


			break;
		}
		else 
		{
			

			Status = ReadFile(tCom, lpBuf, sizeof(lpBuf), &NoBytesRead, NULL);

			show("\n");
			show(lpBuf);
			show("  ");
			wirtePort();
		}
	}
	return 0;
}

void setupPort()
{
	// Initializing DCB structure
	DCB dcbSerialParams = { 0 };                         
	dcbSerialParams.DCBlength = sizeof(dcbSerialParams);
	//retreives  the current settings
	Status = GetCommState(hComm, &dcbSerialParams);      

	if (Status == FALSE)
		show("\n    Error! in GetCommState()");

	dcbSerialParams.BaudRate = CBR_9600;      // Setting BaudRate = 9600
	dcbSerialParams.ByteSize = 8;             // Setting ByteSize = 8
	dcbSerialParams.StopBits = ONESTOPBIT;    // Setting StopBits = 1
	dcbSerialParams.Parity = NOPARITY;        // Setting Parity = None 

	Status = SetCommState(hComm, &dcbSerialParams);  

	if (Status == FALSE)
	{
		show("\n    Error! in Setting DCB Structure");
	}
	else 
	{
		show("\n\n    Setting DCB Structure Successfull\n");
	}

	// Setting Timeouts

	COMMTIMEOUTS timeouts = { 0 };
	timeouts.ReadIntervalTimeout = 50;
	timeouts.ReadTotalTimeoutConstant = 50;
	timeouts.ReadTotalTimeoutMultiplier = 10;
	timeouts.WriteTotalTimeoutConstant = 50;
	timeouts.WriteTotalTimeoutMultiplier = 10;

	if (SetCommTimeouts(hComm, &timeouts) == FALSE)
		show("\n\n    Error! in Setting Time Outs");
	else
		show("\n\n    Setting Serial Port Timeouts Successfull");

}

void openPort()
{

	hComm = CreateFile(ComPortName,   // Name of the Port to be Opened
		GENERIC_READ | GENERIC_WRITE, // Read/Write Access
		0,                            // No Sharing, ports cant be shared
		NULL,                         // No Security
		OPEN_EXISTING,                // Open existing port only
		0,                            // Non Overlapped I/O
		NULL);                        // Null for Comm Devices

	if (hComm == INVALID_HANDLE_VALUE)
		show("\n    Error! - Port %s can't be opened\n");
	else
		show("\n    Port %s Opened\n ");

}

void closePort()
{
	//Closing the Serial Port
	CloseHandle(hComm);

}

void show(char* userMessage)
{

	// send message to the dialog
	HWND OutputWindow = GetDlgItem(windowG, IDC_EDIT1);
	if (OutputWindow)
	{
		SendMessageA(OutputWindow, EM_REPLACESEL, 0, (long)userMessage);
	}
}


int _stdcall handler(HWND window, UINT msg, WPARAM window_pram, LPARAM long_pram)
{
	windowG = window;
	switch (msg)
	{
	case WM_COMMAND:
	{
					   switch (window_pram)
					   {
					   case IDC_BUTTON_CONNECT:
					   {
								show("init the connect buttion");
								openPort();
								setupPort();
								readerThread = CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)readPort,(LPVOID)hComm,0,&readThreadID); 
								closePort();

					   }break;
					   default:
						   break;
					   }
	}break;
	case WM_CLOSE:
	{
					 DestroyWindow(window);
	}break;
	default:
		return DefWindowProcA(window, msg, window_pram, long_pram);
		break;
	}
	return 0;
}

   WinMain(HINSTANCE cur_base, HINSTANCE prv_base, char* args, int display)
{
	DialogBoxA(cur_base, MAKEINTRESOURCEA(IDD_DIALOG1), 0, handler);
	return 1;
}



// debug information

'PMDG_MCP.exe' (Win32): Loaded 'C:\Users\SIC-002\Documents\Visual Studio 2013\Projects\PMDG_MCP\Debug\PMDG_MCP.exe'. Symbols loaded.
'PMDG_MCP.exe' (Win32): Loaded 'C:\Windows\SysWOW64\ntdll.dll'. Cannot find or open the PDB file.
'PMDG_MCP.exe' (Win32): Loaded 'C:\Windows\SysWOW64\kernel32.dll'. Cannot find or open the PDB file.
'PMDG_MCP.exe' (Win32): Loaded 'C:\Windows\SysWOW64\KernelBase.dll'. Cannot find or open the PDB file.
'PMDG_MCP.exe' (Win32): Loaded 'C:\Windows\SysWOW64\user32.dll'. Cannot find or open the PDB file.
'PMDG_MCP.exe' (Win32): Loaded 'C:\Windows\SysWOW64\win32u.dll'. Cannot find or open the PDB file.
'PMDG_MCP.exe' (Win32): Loaded 'C:\Windows\SysWOW64\gdi32.dll'. Cannot find or open the PDB file.
'PMDG_MCP.exe' (Win32): Loaded 'C:\Windows\SysWOW64\gdi32full.dll'. Cannot find or open the PDB file.
'PMDG_MCP.exe' (Win32): Loaded 'C:\Windows\SysWOW64\msvcp_win.dll'. Cannot find or open the PDB file.
'PMDG_MCP.exe' (Win32): Loaded 'C:\Windows\SysWOW64\ucrtbase.dll'. Cannot find or open the PDB file.
'PMDG_MCP.exe' (Win32): Loaded 'C:\Windows\SysWOW64\msvcr120d.dll'. Cannot find or open the PDB file.
'PMDG_MCP.exe' (Win32): Loaded 'C:\Windows\SysWOW64\imm32.dll'. Cannot find or open the PDB file.
'PMDG_MCP.exe' (Win32): Loaded 'C:\Windows\SysWOW64\uxtheme.dll'. Cannot find or open the PDB file.
'PMDG_MCP.exe' (Win32): Loaded 'C:\Windows\SysWOW64\msvcrt.dll'. Cannot find or open the PDB file.
'PMDG_MCP.exe' (Win32): Loaded 'C:\Windows\SysWOW64\combase.dll'. Cannot find or open the PDB file.
'PMDG_MCP.exe' (Win32): Loaded 'C:\Windows\SysWOW64\rpcrt4.dll'. Cannot find or open the PDB file.
'PMDG_MCP.exe' (Win32): Loaded 'C:\Windows\SysWOW64\sspicli.dll'. Cannot find or open the PDB file.
'PMDG_MCP.exe' (Win32): Loaded 'C:\Windows\SysWOW64\cryptbase.dll'. Cannot find or open the PDB file.
'PMDG_MCP.exe' (Win32): Loaded 'C:\Windows\SysWOW64\bcryptprimitives.dll'. Cannot find or open the PDB file.
'PMDG_MCP.exe' (Win32): Loaded 'C:\Windows\SysWOW64\sechost.dll'. Cannot find or open the PDB file.
'PMDG_MCP.exe' (Win32): Loaded 'C:\Windows\SysWOW64\msctf.dll'. Cannot find or open the PDB file.
'PMDG_MCP.exe' (Win32): Loaded 'C:\Windows\SysWOW64\oleaut32.dll'. Cannot find or open the PDB file.
'PMDG_MCP.exe' (Win32): Loaded 'C:\Windows\SysWOW64\advapi32.dll'. Cannot find or open the PDB file.
'PMDG_MCP.exe' (Win32): Loaded 'C:\Windows\WinSxS\x86_microsoft.windows.common-controls_6595b64144ccf1df_6.0.18362.752_none_2e6decc4278ee012\comctl32.dll'. Cannot find or open the PDB file.
'PMDG_MCP.exe' (Win32): Loaded 'C:\Windows\SysWOW64\kernel.appcore.dll'. Cannot find or open the PDB file.
'PMDG_MCP.exe' (Win32): Loaded 'C:\Windows\SysWOW64\TextInputFramework.dll'. Cannot find or open the PDB file.
'PMDG_MCP.exe' (Win32): Loaded 'C:\Windows\SysWOW64\CoreUIComponents.dll'. Cannot find or open the PDB file.
'PMDG_MCP.exe' (Win32): Loaded 'C:\Windows\SysWOW64\CoreMessaging.dll'. Cannot find or open the PDB file.
'PMDG_MCP.exe' (Win32): Loaded 'C:\Windows\SysWOW64\SHCore.dll'. Cannot find or open the PDB file.
'PMDG_MCP.exe' (Win32): Loaded 'C:\Windows\SysWOW64\ntmarta.dll'. Cannot find or open the PDB file.
'PMDG_MCP.exe' (Win32): Loaded 'C:\Windows\SysWOW64\WinTypes.dll'. Cannot find or open the PDB file.
'PMDG_MCP.exe' (Win32): Loaded 'C:\Windows\SysWOW64\WinTypes.dll'. Cannot find or open the PDB file.
'PMDG_MCP.exe' (Win32): Loaded 'C:\Windows\SysWOW64\WinTypes.dll'. Cannot find or open the PDB file.
'PMDG_MCP.exe' (Win32): Unloaded 'C:\Windows\SysWOW64\WinTypes.dll'
'PMDG_MCP.exe' (Win32): Unloaded 'C:\Windows\SysWOW64\WinTypes.dll'
'PMDG_MCP.exe' (Win32): Loaded 'C:\Windows\SysWOW64\iertutil.dll'. Cannot find or open the PDB file.
'PMDG_MCP.exe' (Win32): Loaded 'C:\Program Files (x86)\Internet Download Manager\idmmkb.dll'. Cannot find or open the PDB file.
'PMDG_MCP.exe' (Win32): Loaded 'C:\Windows\SysWOW64\ole32.dll'. Cannot find or open the PDB file.
Posted
Updated 16-Apr-20 2:45am
v3
Comments
Richard MacCutchan 16-Apr-20 5:12am    
Those messages are not exactly helpful. Use your debugger to find out why they are being produced.

1 solution

When a system call fails you need to call GetLastError to find out why. See SetCommMask function (winbase.h) - Win32 apps | Microsoft Docs[^] for example.
 
Share this answer
 
Comments
CPallini 16-Apr-20 8:48am    
5.
Member 12278335 17-Apr-20 12:31pm    
Fom the error its shows error 6: The handle is invalid after calling SetCommMask() iam getting the ERROR_INVALID_HANDLE 6 (0x6) but cannot figure out why....?
Richard MacCutchan 17-Apr-20 12:46pm    
Check exactly what value is in hComm at the line:
readerThread = CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)readPort,(LPVOID)hComm,0,&readThreadID); 


There is not much we can do here, since the only way to trace the problem is by running the code in the debugger.
And check it again at the start of readPort.
Member 12278335 23-Apr-20 1:15am    
The hComm value is 0x000002b0 which the value is same when it created. Is the problem opening port in main thread and the call its event from other thread.
i check the MTTTY example they have done the same as me.

this is the link
https://docs.microsoft.com/en-us/previous-versions/ff802693(v=msdn.10)?redirectedfrom=MSDN
Richard MacCutchan 23-Apr-20 4:41am    
Sorry, I have no answer to that. And, unfortunately I have no way to test these system calls without some device to talk to.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900