📄 serialcommiopacket.cs
字号:
private static extern bool CloseHandle(
int hObject // handle to object
);
#endif
#if COMPACT_FRAMEWORK
[DllImport("coredll",SetLastError=true)]
private static extern uint GetLastError();
#else
[DllImport("kernel32.dll")]
private static extern uint GetLastError();
#endif
#if COMPACT_FRAMEWORK
[DllImport("coredll",SetLastError=true)]
private static extern bool ClearCommError(
int hObject,
ref int lpErrors,
ref COMSTAT lpStat
);
#else
[DllImport("kernel32.dll",SetLastError=true)]
private static extern bool ClearCommError(
int hObject,
ref int lpErrors,
ref COMSTAT lpStat
);
#endif
#if COMPACT_FRAMEWORK
[DllImport("coredll",SetLastError=true)]
private static extern bool PurgeComm(
int hObject,
uint dwFlags
);
#else
[DllImport("kernel32.dll",SetLastError=true)]
private static extern bool PurgeComm(
int hObject,
uint dwFlags
);
#endif
#if COMPACT_FRAMEWORK
[DllImport("coredll",SetLastError=true)]
private static extern bool GetOverlappedResult(
int hObject,
ref OVERLAPPED lpOverlapped,
ref int lpNumberOfBytesTransferred,
bool bWait
);
#else
[DllImport("kernel32.dll",SetLastError=true)]
private static extern bool GetOverlappedResult(
int hObject,
ref OVERLAPPED lpOverlapped,
ref int lpNumberOfBytesTransferred,
bool bWait
);
#endif
#if COMPACT_FRAMEWORK
[DllImport("coredll")]
private static extern bool SetupComm(
int hFile,
int dwInQueue,
int dwOutQueue
);
#else
[DllImport("kernel32")]
private static extern bool SetupComm(
int hFile,
int dwInQueue,
int dwOutQueue
);
#endif
//打开串口
public void Open()
{
try
{
string strComNo = "";
strComNo = String.Format("Com{0}:",PortNum.ToString());
hComm = CreateFile(strComNo, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0);
if( hComm == INVALID_HANDLE_VALUE )
{
string str ="";
str = String.Format("Com{0}不存在或者已经被占用,请选择另外的串口",PortNum.ToString());
MessageBox.Show(str);
Opened = false;
CloseHandle(hComm);
return ;
}
SetupComm(hComm, MAXBLOCK, MAXBLOCK);
// SET THE COMM TIMEOUTS.
COMMTIMEOUTS ctoCommPort = new COMMTIMEOUTS();
GetCommTimeouts(hComm,ref ctoCommPort);
ctoCommPort.ReadTotalTimeoutConstant = ReadTimeout;
ctoCommPort.ReadTotalTimeoutMultiplier = 0;
ctoCommPort.WriteTotalTimeoutMultiplier = 10;
ctoCommPort.WriteTotalTimeoutConstant = 100;
SetCommTimeouts(hComm,ref ctoCommPort);
//
DCB dcbCommPort = new DCB();
dcbCommPort.DCBlength = Marshal.SizeOf(dcbCommPort);
GetCommState(hComm, ref dcbCommPort);
dcbCommPort.fParity = 1;
dcbCommPort.fBinary = 1;
dcbCommPort.BaudRate = BaudRate;
dcbCommPort.Parity = Parity;//0-4=no,odd,even,mark,space
dcbCommPort.ByteSize = 8;//ByteSize
dcbCommPort.StopBits = 0;//StopBits;
//
if (!SetCommState(hComm, ref dcbCommPort))
{
MessageBox.Show("if (!SetCommState(hComm, ref dcbCommPort)) 出现错误");
Opened = false;
CloseHandle(hComm);
return ;
}
}
catch(Exception e)
{
MessageBox.Show("串口打开失败:" + e.Message);
Opened = false;
CloseHandle(hComm);
return ;
}
Opened = true;
//打开串口的时候清空缓冲区
try
{
PurgeComm(hComm, PURGE_RXCLEAR | PURGE_RXABORT);
PurgeComm(hComm, PURGE_TXCLEAR | PURGE_TXABORT);
}
catch(Exception e)
{
MessageBox.Show("When Open Com ,PurgeComm Error:" + e.Message);
Opened = false;
CloseHandle(hComm);
return ;
}
}
public void Close()
{
if (hComm!=INVALID_HANDLE_VALUE)
{
CloseHandle(hComm);
}
}
/// <summary>
/// Read data from serail comport
/// </summary>
/// <returns>
/// 返回读到得字节数组
/// </returns>
public byte[] Read()
{
byte[] inBuff;
byte[] outBuff = null;
int num = 0;
int num_read;
COMSTAT cs = new COMSTAT();
OVERLAPPED o = new OVERLAPPED();
int dwError = 0;
try
{
ClearCommError(hComm, ref dwError , ref cs);//检测接收缓冲区是否有数据
}
catch(Exception e)
{
MessageBox.Show("ClearCommError(hComm, ref dwError , ref cs)发生错误" + e.Message);
}
try
{
//if(cs.cbInQue > 0)
{
num_read = (int)cs.cbInQue;
if(cs.cbInQue > 0)
{
MessageBox.Show("cs.cbInQue > 0");
}
/*出现异常,清空缓冲区*/
if(num_read > 1000)
{
try
{
PurgeComm(hComm, PURGE_RXCLEAR | PURGE_TXCLEAR | PURGE_RXABORT | PURGE_TXABORT);
}
catch(Exception e)
{
MessageBox.Show("PurgeComm 出现错误" + e.Message);
}
return outBuff;
}
/////
if(num_read > 256)
num_read = 256;
else
num_read = 5;//testing
inBuff = new byte[num_read];
if(ReadFile(hComm,inBuff,num_read,ref num, ref o))//
{
outBuff = new byte[num];
if(num > 0)
{
Array.Copy(inBuff,0,outBuff,0,num);
}
}
}
}
catch
{
}
return outBuff;
}
/// <summary>
/// 输出Debug Info
/// </summary>
///
/// <param name="data">
///
/// </param>
/// <param name="orient">
/// 方向,0=read data,1=write data
/// </param>
private void ExportDebugInfo(byte [] data,int orient)
{
if( data.Length > 0)
{
string str;
str = "";
string str0;
str0 = "";
if(orient == 0)
Debug.WriteLine("Read data <---- ");
else
Debug.WriteLine("Write data ----> ");
try
{
for(int i = 0; i < data.Length; i++)
{
str0 = String.Format("{0:X2}",data[i]);
str += str0 + " " ;
}
Debug.WriteLine(str);
}
catch(Exception e)
{
Debug.WriteLine("转换错误:{0}",e.Message);
}
}
}
public void Write(byte[] WriteBytes)
{
if (hComm!=INVALID_HANDLE_VALUE)
{
OVERLAPPED ovlCommPort = new OVERLAPPED();
int BytesWritten = 0;
try
{
WriteFile(hComm,WriteBytes,WriteBytes.Length,ref BytesWritten,ref ovlCommPort);
}
catch
{
}
}
}
}
/// <summary>
/// converter hex string to byte and byte to hex string
/// </summary>
class HexCon
{
public static string ByteToString(byte[] InBytes)
{
string StringOut = "";
foreach (byte InByte in InBytes)
{
StringOut = StringOut + String.Format("{0:X2} ",InByte);
}
return StringOut;
}
public static byte[] StringToByte(string InString)
{
string[] ByteStrings;
ByteStrings = InString.Split(" ".ToCharArray());
byte[] ByteOut;
ByteOut = new byte[ByteStrings.Length - 1];
for (int i = 0;i <= ByteStrings.Length - 1;i++)
{
ByteOut[i] = Convert.ToByte(("0x" + ByteStrings[i]));
}
return ByteOut;
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -