éä¸ä¸ä¸ªä¸²å£æä½ç±»
using System;
using System.Runtime.InteropServices;
namespace JustinIO {
class CommPort {
public string PortNum; //端å£å·
public int BaudRate;//æ³¢ç¹ç
public byte ByteSize;//åè大å°
public byte Parity; // 0-4=no,odd,even,mark,space
public byte StopBits; // 0,1,2 = 1, 1.5, 2
public int ReadTimeout;
//comm port win32 file handle
private int hComm = -1;
public bool Opened = false;
//win32 api constants
private const uint GENERIC_READ = 0x80000000;
private const uint GENERIC_WRITE = 0x40000000;
private const int OPEN_EXISTING = 3;
private const int INVALID_HANDLE_VALUE = -1;
[StructLayout(LayoutKind.Sequential)]
public struct DCB {
//taken from c struct in platform sdk
public int DCBlength; // sizeof(DCB)
public int BaudRate; // æå®å½åæ³¢ç¹ç current baud rate
// these are the c struct bit fields, bit twiddle flag to set
public int fBinary; // æå®æ¯å¦å
许äºè¿å¶æ¨¡å¼,å¨windows95ä¸å¿
须主TRUE binary mode, no EOF check
public int fParity; // æå®æ¯å¦å
许å¥å¶æ ¡éª enable parity checking
public int fOutxCtsFlow; // æå®CTSæ¯å¦ç¨äºæ£æµåéæ§å¶ï¼å½ä¸ºTRUEæ¯CTS为OFFï¼åéå°è¢«æèµ·ã CTS output flow control
public int fOutxDsrFlow; // æå®CTSæ¯å¦ç¨äºæ£æµåéæ§å¶ DSR output flow control
public int fDtrControl; // DTR_CONTROL_DISABLEå¼å°DTR置为OFF, DTR_CONTROL_ENABLEå¼å°DTR置为ON, DTR_CONTROL_HANDSHAKEå
许DTR"æ¡æ" DTR flow control type
public int fDsrSensitivity; // å½è¯¥å¼ä¸ºTRUEæ¶DSR为OFFæ¶æ¥æ¶çåèè¢«å¿½ç¥ DSR sensitivity
public int fTXContinueOnXoff; // æå®å½æ¥æ¶ç¼å²åºå·²æ»¡,并ä¸é©±å¨ç¨åºå·²ç»åéåºXoffCharå符æ¶åéæ¯å¦åæ¢ãTRUEæ¶ï¼å¨æ¥æ¶ç¼å²åºæ¥æ¶å°ç¼å²åºå·²æ»¡çåèXoffLimä¸é©±å¨ç¨åºå·²ç»åéåºXoffCharå符ä¸æ¢æ¥æ¶åèä¹åï¼åé继ç»è¿è¡ã FALSEæ¶ï¼å¨æ¥æ¶ç¼å²åºæ¥æ¶å°ä»£è¡¨ç¼å²åºå·²ç©ºçåèXonCharä¸é©±å¨ç¨åºå·²ç»åéåºæ¢å¤åéçXonCharä¹åï¼åé继ç»è¿è¡ãXOFF continues Tx
public int fOutX; // TRUEæ¶ï¼æ¥æ¶å°XoffCharä¹å便åæ¢åéæ¥æ¶å°XonCharä¹åå°éæ°å¼å§ XON/XOFF out flow control
public int fInX; // TRUEæ¶ï¼æ¥æ¶ç¼å²åºæ¥æ¶å°ä»£è¡¨ç¼å²åºæ»¡çXoffLimä¹åï¼XoffCharåéåºå»æ¥æ¶ç¼å²åºæ¥æ¶å°ä»£è¡¨ç¼å²åºç©ºçXonLimä¹åï¼XonCharåéåºå» XON/XOFF in flow control
public int fErrorChar; // 该å¼ä¸ºTRUEä¸fParity为TRUEæ¶ï¼ç¨ErrorChar æåæå®çå符代æ¿å¥å¶æ ¡éªé误çæ¥æ¶å符 enable error replacement
public int fNull; // eTRUEæ¶ï¼æ¥æ¶æ¶å»æ空ï¼0å¼ï¼åè enable null stripping
public int fRtsControl; // RTS flow control
/*RTS_CONTROL_DISABLEæ¶,RTS置为OFF
RTS_CONTROL_ENABLEæ¶, RTS置为ON
RTS_CONTROL_HANDSHAKEæ¶,
å½æ¥æ¶ç¼å²åºå°äºå满æ¶RTS为ON
å½æ¥æ¶ç¼å²åºè¶
è¿ååä¹ä¸æ»¡æ¶RTS为OFF
RTS_CONTROL_TOGGLEæ¶,
å½æ¥æ¶ç¼å²åºä»æå©ä½åèæ¶RTS为ON ,å¦å缺ç为OFF*/
public int fAbortOnError; // TRUEæ¶,æé误åçæ¶ä¸æ¢è¯»ååæä½ abort on error
public int fDummy2; // æªä½¿ç¨ reserved
public uint flags;
public ushort wReserved; // æªä½¿ç¨,å¿
须为0 not currently used
public ushort XonLim; // æå®å¨XONå符åéè¿åæ¥æ¶ç¼å²åºä¸å¯å
许çæå°åèæ° transmit XON threshold
public ushort XoffLim; // æå®å¨XOFFå符åéè¿åæ¥æ¶ç¼å²åºä¸å¯å
许çæå°åèæ° transmit XOFF threshold
public byte ByteSize; // æå®ç«¯å£å½å使ç¨çæ°æ®ä½ number of bits/byte, 4-8
public byte Parity; // æå®ç«¯å£å½å使ç¨çå¥å¶æ ¡éªæ¹æ³,å¯è½ä¸º:EVENPARITY,MARKPARITY,NOPARITY,ODDPARITY 0-4=no,odd,even,mark,space
public byte StopBits; // æå®ç«¯å£å½å使ç¨çåæ¢ä½æ°,å¯è½ä¸º:ONESTOPBIT,ONE5STOPBITS,TWOSTOPBITS 0,1,2 = 1, 1.5, 2
public char XonChar; // æå®ç¨äºåéåæ¥æ¶å符XONçå¼ Tx and Rx XON character
public char XoffChar; // æå®ç¨äºåéåæ¥æ¶å符XOFFå¼ Tx and Rx XOFF character
public char ErrorChar; // æ¬å符ç¨æ¥ä»£æ¿æ¥æ¶å°çå¥å¶æ ¡éªåçé误æ¶çå¼ error replacement character
public char EofChar; // å½æ²¡æ使ç¨äºè¿å¶æ¨¡å¼æ¶,æ¬å符å¯ç¨æ¥æ示æ°æ®çç»æ end of input character
public char EvtChar; // å½æ¥æ¶å°æ¤å符æ¶,ä¼äº§çä¸ä¸ªäºä»¶ received event character
public ushort wReserved1; // æªä½¿ç¨ reserved; do not use
}
[StructLayout(LayoutKind.Sequential)]
private struct COMMTIMEOUTS {
public int ReadIntervalTimeout;
public int ReadTotalTimeoutMultiplier;
public int ReadTotalTimeoutConstant;
public int WriteTotalTimeoutMultiplier;
public int WriteTotalTimeoutConstant;
}
[StructLayout(LayoutKind.Sequential)]
private struct OVERLAPPED {
public int Internal;
public int InternalHigh;
public int Offset;
public int OffsetHigh;
public int hEvent;
}
[DllImport("kernel32.dll")]
private static extern int CreateFile(
string lpFileName, // è¦æå¼ç串å£å称
uint dwDesiredAccess, // æå®ä¸²å£ç访é®æ¹å¼ï¼ä¸è¬è®¾ç½®ä¸ºå¯è¯»å¯åæ¹å¼
int dwShareMode, // æå®ä¸²å£çå
±äº«æ¨¡å¼ï¼ä¸²å£ä¸è½å
±äº«ï¼æ以设置为0
int lpSecurityAttributes, // 设置串å£çå®å
¨å±æ§ï¼WIN9Xä¸ä¸æ¯æï¼åºè®¾ä¸ºNULL
int dwCreationDisposition, // 对äºä¸²å£éä¿¡ï¼å建æ¹å¼åªè½ä¸ºOPEN_EXISTING
int dwFlagsAndAttributes, // æå®ä¸²å£å±æ§ä¸æ å¿ï¼è®¾ç½®ä¸ºFILE_FLAG_OVERLAPPED(éå I/Oæä½)ï¼æå®ä¸²å£ä»¥å¼æ¥æ¹å¼éä¿¡
int hTemplateFile // 对äºä¸²å£éä¿¡å¿
须设置为NULL
);
[DllImport("kernel32.dll")]
private static extern bool GetCommState(
int hFile, //é信设å¤å¥æ
ref DCB lpDCB // 设å¤æ§å¶åDCB
);
[DllImport("kernel32.dll")]
private static extern bool BuildCommDCB(
string lpDef, // 设å¤æ§å¶å符串
ref DCB lpDCB // 设å¤æ§å¶å
);
[DllImport("kernel32.dll")]
private static extern bool SetCommState(
int hFile, // é信设å¤å¥æ
ref DCB lpDCB // 设å¤æ§å¶å
);
[DllImport("kernel32.dll")]
private static extern bool GetCommTimeouts(
int hFile, // é信设å¤å¥æ handle to comm device
ref COMMTIMEOUTS lpCommTimeouts // è¶
æ¶æ¶é´ time-out values
);
[DllImport("kernel32.dll")]
private static extern bool SetCommTimeouts(
int hFile, // é信设å¤å¥æ handle to comm device
ref COMMTIMEOUTS lpCommTimeouts // è¶
æ¶æ¶é´ time-out values
);
[DllImport("kernel32.dll")]
private static extern bool ReadFile(
int hFile, // é信设å¤å¥æ handle to file
byte[] lpBuffer, // æ°æ®ç¼å²åº data buffer
int nNumberOfBytesToRead, // å¤å°åèçå¾
读å number of bytes to read
ref int lpNumberOfBytesRead, // 读åå¤å°åè number of bytes read
ref OVERLAPPED lpOverlapped // 溢åºç¼å²åº overlapped buffer
);
[DllImport("kernel32.dll")]
private static extern bool WriteFile(
int hFile, // é信设å¤å¥æ handle to file
byte[] lpBuffer, // æ°æ®ç¼å²åº data buffer
int nNumberOfBytesToWrite, // å¤å°åèçå¾
åå
¥ number of bytes to write
ref int lpNumberOfBytesWritten, // å·²ç»åå
¥å¤å°åè number of bytes written
ref OVERLAPPED lpOverlapped // 溢åºç¼å²åº overlapped buffer
);
[DllImport("kernel32.dll")]
private static extern bool CloseHandle(
int hObject // handle to object
);
[DllImport("kernel32.dll")]
private static extern uint GetLastError();
public void Open()
{
DCB dcbCommPort = new DCB();
COMMTIMEOUTS ctoCommPort = new COMMTIMEOUTS();
// æå¼ä¸²å£ OPEN THE COMM PORT.
hComm = CreateFile(PortNum ,GENERIC_READ | GENERIC_WRITE,0, 0,OPEN_EXISTING,0,0);
// å¦æ串å£æ²¡ææå¼ï¼å°±æå¼ IF THE PORT CANNOT BE OPENED, BAIL OUT.
if(hComm == INVALID_HANDLE_VALUE)
{
throw(new ApplicationException("éæ³æä½ï¼ä¸è½æå¼ä¸²å£ï¼"));
}
// 设置éä¿¡è¶
æ¶æ¶é´ SET THE COMM TIMEOUTS.
GetCommTimeouts(hComm,ref ctoCommPort);
ctoCommPort.ReadTotalTimeoutConstant = ReadTimeout;
ctoCommPort.ReadTotalTimeoutMultiplier = 0;
ctoCommPort.WriteTotalTimeoutMultiplier = 0;
ctoCommPort.WriteTotalTimeoutConstant = 0;
SetCommTimeouts(hComm,ref ctoCommPort);
// è®¾ç½®ä¸²å£ SET BAUD RATE, PARITY, WORD SIZE, AND STOP BITS.
GetCommState(hComm, ref dcbCommPort);
dcbCommPort.BaudRate=BaudRate;
dcbCommPort.flags=0;
//dcb.fBinary=1;
dcbCommPort.flags|=1;
if (Parity>0)
{
//dcb.fParity=1
dcbCommPort.flags|=2;
}
dcbCommPort.Parity=Parity;
dcbCommPort.ByteSize=ByteSize;
dcbCommPort.StopBits=StopBits;
if (!SetCommState(hComm, ref dcbCommPort))
{
//uint ErrorNum=GetLastError();
throw(new ApplicationException("éæ³æä½ï¼ä¸è½æå¼ä¸²å£ï¼"));
}
//unremark to see if setting took correctly
//DCB dcbCommPort2 = new DCB();
//GetCommState(hComm, ref dcbCommPort2);
Opened = true;
}
public void Close() {
if (hComm!=INVALID_HANDLE_VALUE) {
CloseHandle(hComm);
}
}
public byte[] Read(int NumBytes) {
byte[] BufBytes;
byte[] OutBytes;
BufBytes = new byte[NumBytes];
if (hComm!=INVALID_HANDLE_VALUE) {
OVERLAPPED ovlCommPort = new OVERLAPPED();
int BytesRead=0;
ReadFile(hComm,BufBytes,NumBytes,ref BytesRead,ref ovlCommPort);
OutBytes = new byte[BytesRead];
Array.Copy(BufBytes,OutBytes,BytesRead);
}
else {
throw(new ApplicationException("串å£æªæå¼ï¼"));
}
return OutBytes;
}
public void Write(byte[] WriteBytes) {
if (hComm!=INVALID_HANDLE_VALUE) {
OVERLAPPED ovlCommPort = new OVERLAPPED();
int BytesWritten = 0;
WriteFile(hComm,WriteBytes,WriteBytes.Length,ref BytesWritten,ref ovlCommPort);
}
else {
throw(new ApplicationException("串å£æªæå¼ï¼"));
}
}
}
class HexCon {
// æåå
è¿å¶å符串转æ¢æåèååæåèå转æ¢æåå
è¿å¶å符串 converter hex string to byte and byte to hex string
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;
温馨提示:内容为网友见解,仅供参考