views:

459

answers:

1

In my .NET application I need to achieve serial port setup equivalent to this C++ managed code:

::SetCommMask(m_hCOMM, EV_RXCHAR);  
::SetupComm(m_hCOMM, 9*2*128*10, 400);
::PurgeComm(m_hCOMM, PURGE_TXABORT|PURGE_RXABORT|PURGE_TXCLEAR|PURGE_RXCLEAR);

COMMTIMEOUTS timeOut;
timeOut.ReadIntervalTimeout        = 3;
timeOut.ReadTotalTimeoutConstant   = 3;
timeOut.ReadTotalTimeoutMultiplier = 1; 
timeOut.WriteTotalTimeoutConstant  = 0;
timeOut.WriteTotalTimeoutMultiplier= 0;
int nRet= ::SetCommTimeouts(m_hCOMM, &timeOut); 

::EscapeCommFunction(m_hCOMM, SETDTR);  
::EscapeCommFunction(m_hCOMM, SETRTS);      

DCB dcb;
memset(&dcb, 0, sizeof(DCB));
dcb.BaudRate= m_nSpeed; 
dcb.ByteSize= 8;
dcb.fParity = FALSE;
dcb.Parity  = NOPARITY;
dcb.StopBits= ONESTOPBIT;
dcb.fBinary = TRUE;


dcb.fDsrSensitivity= FALSE; 

dcb.fOutxDsrFlow= FALSE;        
dcb.fOutxCtsFlow= FALSE;            


dcb.fDtrControl = DTR_CONTROL_HANDSHAKE;
dcb.fRtsControl = RTS_CONTROL_TOGGLE;

nRet= ::SetCommState(m_hCOMM, &dcb);

Is it possible at all? How do I approach this problem? Are there any (preferable free) libraries that allow such low level serial port control or should I create my own wrapper on top of Win32 api? Anyone did anything similar or has an idea how to 'glue' win32 serial port api with .net so that I can use neat .NET DataReceived() events ? Or maybe I can create .NET SerialPort instance and then modify it using managed API?

A: 

The .NET SerialPort class has most of what you need.

p = SerialPort.SerialPort(); //use whichever constructor you need

p.DiscarInBuffer();
p.DiscardOutbuffer();
p.ReadBufferSize = 9*2*128*10;
p.WriteBufferSize = 400;


p.ReadTimeout = 10; //not exactly equivalent to COMMTIMEOUTS
p.WriteTimeout = 0;

p.DtrEnable = true;
p.RtsEnable = true;

p.BaudRate = m_nSpeed;
p.DataBits = 8;
p.Parity = Parity.None;
p.StopBits = StopBits.One;

//I think DSR and CTS states are pollable by app but ignored by driver 
mtrw
Isp.DtrEnable = true;p.RtsEnable = true;equivalent to:dcb.fDtrControl = DTR_CONTROL_HANDSHAKE;dcb.fRtsControl = RTS_CONTROL_TOGGLE;?What about::EscapeCommFunction(m_hCOMM, SETDTR); ::EscapeCommFunction(m_hCOMM, SETRTS); Thanks for your help!
adrin
@adrin - I think `p.DtrEnable = true` is equivalent to ``::EscapeCommFunction(m_hCOMM, SETDTR)`, and the same for RTS. I'm not sure how to set handshaking in .NET, I've never needed to before. Sorry I can't be of more help.
mtrw