public static void SetDCB(this SerialPort com, DCB dcb) { com.BaudRate = dcb.BaudRate; com.DataBits = dcb.DataBits; com.StopBits = dcb.StopBits; com.Parity = dcb.Parity; }
public void Open() { DCB dcbCommPort = new DCB(); COMMTIMEOUTS ctoCommPort = new COMMTIMEOUTS(); // OPEN THE COMM PORT. hComm = CreateFile("COM" + 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("Comm Port Can Not Be Opened")); } // 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("Comm Port Can Not Be Opened")); } //unremark to see if setting took correctly //DCB dcbCommPort2 = new DCB(); //GetCommState(hComm, ref dcbCommPort2); Opened = true; }
public static extern Boolean GetCommState(IntPtr hFile, ref DCB lpDCB);
private static extern bool SetCommState(int hFile, ref DCB lpDCB);
public static extern bool GetCommState(IntPtr handle, ref DCB dcb);
private static extern int SetCommState(int hCommDev, DCB lpDCB);
public static extern bool SetCommState( int hFile, // 通信设备句柄 ref DCB lpDCB // 设备控制块 );
static unsafe extern bool SetCommState(int hFile, DCB* lpDCB);
public static extern bool SetCommState(SafeFileHandle hFile, ref DCB lpDCB);
internal static extern bool GetCommState( SafeFileHandle hFile, ref DCB lpDCB);
public static extern DCB GetBoundsRect(HDC hdc, out RECT lprect, DCB flags);
static extern unsafe bool GetCommState( IntPtr hFile, ref DCB lpDCB);
private static extern bool SetCommState(IntPtr hFile, DCB lpDCB);
public bool Open(int PortNum, int BaudRate, char cParity, byte ByteSize, byte StopBits) { uint lastError; DCB lpDCB = new DCB(); COMMTIMEOUTS lpCommTimeouts = new COMMTIMEOUTS(); this.hComm = CreateFile("COM" + PortNum, 0xc0000000, 0, 0, 3, 0, 0); if (this.hComm == -1) { throw new ApplicationException("打开端口[COM" + PortNum + "]失败!"); } GetCommTimeouts(this.hComm, ref lpCommTimeouts); lpCommTimeouts.ReadTotalTimeoutConstant = 0x7d0; lpCommTimeouts.ReadTotalTimeoutMultiplier = 0; lpCommTimeouts.WriteTotalTimeoutMultiplier = 0; lpCommTimeouts.WriteTotalTimeoutConstant = 0x1388; SetCommTimeouts(this.hComm, ref lpCommTimeouts); if (!GetCommState(this.hComm, ref lpDCB)) { lastError = GetLastError(); this.Close(); throw new ApplicationException(string.Concat(new object[] { "打开端口[COM", PortNum, "]时执行GetCommState()失败!\r\n错误号: ", lastError.ToString() })); } lpDCB.BaudRate = BaudRate; lpDCB.ByteSize = ByteSize; switch (cParity) { case 'm': case 'M': lpDCB.Parity = 3; break; case 'n': case 'N': lpDCB.Parity = 0; break; case 'o': case 'O': lpDCB.Parity = 1; break; case 's': case 'S': lpDCB.Parity = 4; break; case 'e': case 'E': lpDCB.Parity = 2; break; } switch (StopBits) { case 1: lpDCB.StopBits = 0; break; case 2: lpDCB.StopBits = 2; break; } if (!SetCommState(this.hComm, ref lpDCB)) { lastError = GetLastError(); this.Close(); throw new ApplicationException(string.Concat(new object[] { "打开端口[COM", PortNum, "]执行SetCommState()失败!\r\n错误号: ", lastError.ToString() })); } this.Opened = true; return(true); }
/// <summary> /// Create the device control block (DCB) for the associated comm port. /// Sets the DCB fields to match the passed configuration. /// </summary> /// <param name="cfg">Reference to user defined port config.</param> internal Win32DCB(SerialCnfg cfg) { this.dcb = new DCB(); this.dcb.dcbLength = Marshal.SizeOf(this.dcb); this.dcb.baudRate = (int) cfg.BaudRate; this.dcb.bitfield = 0x8001; if((cfg.Parity == Parity.Odd) || (cfg.Parity == Parity.Even)) this.dcb.bitfield |= 0x0002; if (cfg.TxFlowCTS) this.dcb.bitfield |= 0x0004; if (cfg.TxFlowDSR) this.dcb.bitfield |= 0x0008; this.dcb.bitfield |= ( ((int) cfg.DtrControl & 0x0003) << 4); if (cfg.RxDSRsense) this.dcb.bitfield |= 0x0040; if (cfg.TxContinue) this.dcb.bitfield |= 0x0080; if (cfg.TxFlowXoff) this.dcb.bitfield |= 0x0100; if (cfg.RxFlowXoff) this.dcb.bitfield |= 0x0200; this.dcb.bitfield |= ( ((int) cfg.RtsControl & 0x0003) << 12); this.dcb.byteSize = (byte) cfg.DataBits; this.dcb.prtyByte = (byte) cfg.Parity; this.dcb.stopBits = (byte) cfg.StopBits; this.dcb.xoffChar = (byte) cfg.XoffChar; this.dcb.xonChar = (byte) cfg.XonChar; return; }
public bool SetPortSettings(uint baudrate, byte databits, StopBits stopbits, Parity parity, FlowControl flowcontrol) { unsafe { DCB dcb = new DCB(); dcb.DCBlength = sizeof(DCB); dcb.BaudRate = baudrate; dcb.ByteSize = databits; dcb.StopBits = (byte)stopbits; dcb.Parity = (byte)parity; dcb.fParity = (parity > 0)? 1U : 0U; dcb.fBinary = dcb.fDtrControl = dcb.fTXContinueOnXoff = 1; dcb.fOutxCtsFlow = dcb.fAbortOnError = (flowcontrol == FlowControl.Hardware)? 1U : 0U; dcb.fOutX = dcb.fInX = (flowcontrol == FlowControl.XOnXOff)? 1U : 0U; dcb.fRtsControl = (flowcontrol == FlowControl.Hardware)? 2U : 1U; dcb.XonLim = 2048; dcb.XoffLim = 512; dcb.XonChar = 0x11; // Ctrl-Q dcb.XoffChar = 0x13; // Ctrl-S return SetCommState(m_hFile, &dcb); } }
public static extern bool SetCommState(IntPtr handle, [In, Out] ref DCB dcb);
private static extern bool BuildCommDCB( string lpDef, // device-control string ref DCB lpDCB // device-control block );
private static extern bool SetCommState( int hFile, // handle to communications device ref DCB lpDCB // device-control block );
///<summary> ///设置DCB标志位 ///</summary> ///<param name="whichFlag"></param> ///<param name="setting"></param> ///<param name="dcb"></param> internal void SetDcbFlag(int whichFlag, int setting, DCB dcb) { uint num; setting = setting << whichFlag; if ((whichFlag == 4) || (whichFlag == 12)) { num = 3; } else if (whichFlag == 15) { num = 0x1ffff; } else { num = 1; } dcb.flags &= ~(num << whichFlag); dcb.flags |= (uint)setting; }
public static extern bool GetCommState( int hFile, ref DCB lpDCB );
/// <summary> /// 打开串口 /// </summary> public bool Connect(ref int commHandle) { if (this._isOpened) return true; // 创建一个设备控制块和一个超时参数 DCB dcbCommPort = new DCB(); COMMTIMEOUTS ctoCommPort = new COMMTIMEOUTS(); // 打开串口 commHandle = CreateFile(PortNum, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0); // 如果串口没有打开,则返回false if (commHandle == INVALID_HANDLE_VALUE) { this._isOpened = false; return false; } char[] szBaud = new char[50]; dcbCommPort.flags = 0; // 设置通信超时时间 SET THE COMM TIMEOUTS. GetCommTimeouts(commHandle, ref ctoCommPort); ctoCommPort.ReadIntervalTimeout = 300; ctoCommPort.ReadTotalTimeoutConstant = 10; ctoCommPort.ReadTotalTimeoutMultiplier = 10; ctoCommPort.WriteTotalTimeoutMultiplier = 10; ctoCommPort.WriteTotalTimeoutConstant = 10; SetCommTimeouts(commHandle, ref ctoCommPort); if (dcbCommPort.fParity != 1) dcbCommPort.fParity = 1; // 设置串口 SET BAUD RATE, PARITY, WORD SIZE, AND STOP BITS. string szbaud = "baud=" + BaudRate + " parity=" + Parity + " data=" + ByteSize + " stop=" + StopBits; dcbCommPort.DCBlength = Marshal.SizeOf(dcbCommPort); if (GetCommState(commHandle, ref dcbCommPort)) { if (BuildCommDCB(szbaud, ref dcbCommPort)) { if (SetCommState(commHandle, ref dcbCommPort)) { ; // normal operation... continue } else { throw (new ApplicationException("串口参数设置失败SetCommState!")); } } else { throw (new ApplicationException("串口参数设置失败BuildCommDCB!")); } } else { throw (new ApplicationException("串口参数设置失败GetCommState!")); } this._isOpened = true; return true; }
internal static extern Boolean GetCommState(IntPtr hFile, ref DCB lpDCB);
public static extern bool SetCommState(int hPort, ref DCB lpDCB);
/// <summary> /// Opens the com port and configures it with the required settings /// </summary> /// <returns>false if the port could not be opened</returns> public bool Open() { var portDcb = new DCB(); var commTimeouts = new COMMTIMEOUTS(); var wo = new OVERLAPPED(); if (_online) { return(false); } _hPort = Win32Com.CreateFile(PortName, Win32Com.GENERIC_READ | Win32Com.GENERIC_WRITE, 0, IntPtr.Zero, Win32Com.OPEN_EXISTING, Win32Com.FILE_FLAG_OVERLAPPED, IntPtr.Zero); if (_hPort == (IntPtr)Win32Com.INVALID_HANDLE_VALUE) { if (Marshal.GetLastWin32Error() == Win32Com.ERROR_ACCESS_DENIED) { return(false); } throw new CommPortException("Port Open Failure"); } _online = true; commTimeouts.ReadIntervalTimeout = 0; commTimeouts.ReadTotalTimeoutConstant = 0; commTimeouts.ReadTotalTimeoutMultiplier = 0; commTimeouts.WriteTotalTimeoutConstant = SendTimeoutConstant; commTimeouts.WriteTotalTimeoutMultiplier = SendTimeoutMultiplier; portDcb.Init(((Parity == Parity.Odd) || (Parity == Parity.Even)), TxFlowCts, TxFlowDsr, (int)UseDtr, RxGateDsr, !TxWhenRxXoff, TxFlowX, RxFlowX, (int)UseRts); portDcb.BaudRate = BaudRate; portDcb.ByteSize = (byte)DataBits; portDcb.Parity = (byte)Parity; portDcb.StopBits = (byte)StopBits; portDcb.XoffChar = (byte)XoffChar; portDcb.XonChar = (byte)XonChar; portDcb.XoffLim = (short)RxHighWater; portDcb.XonLim = (short)RxLowWater; if ((RxQueue != 0) || (TxQueue != 0)) { if (!Win32Com.SetupComm(_hPort, (uint)RxQueue, (uint)TxQueue)) { ThrowException("Bad queue settings"); } } if (!Win32Com.SetCommState(_hPort, ref portDcb)) { ThrowException("Bad com settings"); } if (!Win32Com.SetCommTimeouts(_hPort, ref commTimeouts)) { ThrowException("Bad timeout settings"); } _stateBrk = 0; if (UseDtr == HsOutput.None) { _stateDtr = 0; } if (UseDtr == HsOutput.Online) { _stateDtr = 1; } if (UseRts == HsOutput.None) { _stateRts = 0; } if (UseRts == HsOutput.Online) { _stateRts = 1; } _checkSends = CheckAllSends; wo.Offset = 0; wo.OffsetHigh = 0; wo.hEvent = _checkSends ? _writeEvent.Handle : IntPtr.Zero; _ptrUwo = Marshal.AllocHGlobal(Marshal.SizeOf(wo)); Marshal.StructureToPtr(wo, _ptrUwo, true); _writeCount = 0; _rxException = null; _rxExceptionReported = false; _rxThread = new Thread(ReceiveThread) { Name = "CommBaseRx", Priority = ThreadPriority.AboveNormal }; //If not set to true, my application process will not exit completely after UI closed _rxThread.IsBackground = true; _rxThread.Start(); Thread.Sleep(1); //Give rx thread time to start. By documentation, 0 should work, but it does not! _auto = false; if (AfterOpen()) { _auto = AutoReopen; return(true); } Close(); return(false); }
/// <summary> /// Configures the serial device based on the connection parameters pased in by the user. /// </summary> /// <returns>Whether or not the operation succeeded</returns> private bool ConfigureSerialPort() { DCB serialConfig = new DCB(); if (GetCommState(pHandle, ref serialConfig)) { // setup the DCB struct with the serial settings we need serialConfig.BaudRate = (uint)this.iBaudRate; serialConfig.ByteSize = this.byteSize; serialConfig.fBinary = 1; // must be true serialConfig.fDtrControl = 1; // DTR_CONTROL_ENABLE "Enables the DTR line when the device is opened and leaves it on." serialConfig.fAbortOnError = 0; // false serialConfig.fTXContinueOnXoff = 0; // false serialConfig.fParity = 1; // true so that the Parity member is looked at switch (this.parity) { case Parity.Even: serialConfig.Parity = 2; break; case Parity.Mark: serialConfig.Parity = 3; break; case Parity.Odd: serialConfig.Parity = 1; break; case Parity.Space: serialConfig.Parity = 4; break; case Parity.None: default: serialConfig.Parity = 0; break; } switch (this.stopBits) { case StopBits.One: serialConfig.StopBits = 0; break; case StopBits.OnePointFive: serialConfig.StopBits = 1; break; case StopBits.Two: serialConfig.StopBits = 2; break; case StopBits.None: default: throw new ArgumentException("stopBits cannot be StopBits.None"); } if (SetCommState(pHandle, ref serialConfig)) { // set the serial connection timeouts COMMTIMEOUTS timeouts = new COMMTIMEOUTS(); timeouts.ReadIntervalTimeout = 1; timeouts.ReadTotalTimeoutMultiplier = 0; timeouts.ReadTotalTimeoutConstant = 0; timeouts.WriteTotalTimeoutMultiplier = 0; timeouts.WriteTotalTimeoutConstant = 0; if (SetCommTimeouts(pHandle, ref timeouts)) { return true; } else { return false; } } else { return false; } } else { return false; } }
/// <summary> /// 建立与串口的连接 /// </summary> public bool Open() { COMMTIMEOUTS ctoCommPort = new COMMTIMEOUTS(); // 打开串口 hComm = CreateFile("COM" + PortNum, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0); if (hComm == INVALID_HANDLE_VALUE) { return(false); } // 设置通信超时时间 GetCommTimeouts(hComm, ref ctoCommPort); ctoCommPort.ReadIntervalTimeout = UInt32.MaxValue; ctoCommPort.ReadTotalTimeoutConstant = ReadTimeout; ctoCommPort.ReadTotalTimeoutMultiplier = 0; ctoCommPort.WriteTotalTimeoutMultiplier = 0; ctoCommPort.WriteTotalTimeoutConstant = WriteTimeout; SetCommTimeouts(hComm, ref ctoCommPort); // 设置串口 DCB dcb = new DCB(); GetCommState(hComm, ref dcb); dcb.DCBlength = Marshal.SizeOf(dcb); dcb.BaudRate = BaudRate; dcb.flags = 0; //////////////////////////////////sr dcb.flags |= 1; if (Parity > 0) { dcb.flags |= 2; } ////////////////////////////////////// dcb.Parity = Parity; dcb.ByteSize = ByteSize; dcb.StopBits = StopBits; //------------------------------ SetDcbFlag(0, 1, dcb); //二进制方式 SetDcbFlag(1, (Parity == 0) ? 0 : 1, dcb); SetDcbFlag(2, 0, dcb); //不用CTS检测发送流控制 SetDcbFlag(3, 0, dcb); //不用DSR检测发送流控制 SetDcbFlag(4, 0, dcb); //禁止DTR流量控制 SetDcbFlag(6, 0, dcb); //对DTR信号线不敏感 SetDcbFlag(9, 1, dcb); //检测接收缓冲区 SetDcbFlag(8, 0, dcb); //不做发送字符控制 SetDcbFlag(10, 0, dcb); //是否用指定字符替换校验错的字符 SetDcbFlag(11, 0, dcb); //保留NULL字符 SetDcbFlag(12, 0, dcb); //允许RTS流量控制 SetDcbFlag(14, 0, dcb); //发送错误后,继续进行下面的读写操作 //-------------------------------- dcb.wReserved = 0; //没有使用,必须为0 dcb.XonLim = 0; //指定在XOFF字符发送之前接收到缓冲区中可允许的最小字节数 dcb.XoffLim = 0; //指定在XOFF字符发送之前缓冲区中可允许的最小可用字节数 dcb.XonChar = 0; //发送和接收的XON字符 dcb.XoffChar = 0; //发送和接收的XOFF字符 dcb.ErrorChar = 0; //代替接收到奇偶校验错误的字符 dcb.EofChar = 0; //用来表示数据的结束 dcb.EvtChar = 0; //事件字符,接收到此字符时,会产生一个事件 dcb.wReserved1 = 0; //没有使用 #region 防止第一次通讯时不能进行通讯 #region 校验字符串 //0-4=no,odd,even,mark,space string L_Parity = "n"; switch (Parity) { case 0: L_Parity = "n"; break; case 1: L_Parity = "o"; break; case 2: L_Parity = "e"; break; case 3: L_Parity = "m"; break; case 4: L_Parity = "s"; break; default: break; } #endregion #region 停止位 //StopBits; // 0,1,2 = 1, 1.5, 2 string L_Stopbit = "1"; switch (StopBits) { case 0: L_Stopbit = "1"; break; case 1: L_Stopbit = "1.5"; break; case 2: L_Stopbit = "2"; break; default: break; } #endregion string L_Set = BaudRate.ToString() + "," + L_Parity + "," + ByteSize.ToString() + "," + L_Stopbit; if (!BuildCommDCB(L_Set, ref dcb)) { return(false); } #endregion if (!SetCommState(hComm, ref dcb)) { return(false); } Opened = true; return(true); }
/// <summary> /// 建立与串口的连接 /// </summary> public bool Open() { DCB dcbCommPort = new DCB(); COMMTIMEOUTS ctoCommPort = new COMMTIMEOUTS(); // 打开串口 hComm = CreateFile(PortNum, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0); if (hComm == INVALID_HANDLE_VALUE) { return false; } // 设置通信超时时间 GetCommTimeouts(hComm, ref ctoCommPort); ctoCommPort.ReadTotalTimeoutConstant = ReadTimeout; ctoCommPort.ReadTotalTimeoutMultiplier = 0; ctoCommPort.WriteTotalTimeoutMultiplier = 0; ctoCommPort.WriteTotalTimeoutConstant = 0; SetCommTimeouts(hComm, ref ctoCommPort); // 设置串口 GetCommState(hComm, ref dcbCommPort); dcbCommPort.fOutxCtsFlow = 524800; dcbCommPort.BaudRate = BaudRate; dcbCommPort.flags = 0; dcbCommPort.flags |= 1; if (Parity > 0) { dcbCommPort.flags |= 2; } dcbCommPort.Parity = Parity; dcbCommPort.ByteSize = ByteSize; dcbCommPort.StopBits = StopBits; dcbCommPort.fOutxCtsFlow = 524800; if (!SetCommState(hComm, ref dcbCommPort)) { return false; } Opened = true; return true; }
int dwFlags); // 需要完成的操作 #endregion #region 串口初始化方法(打开、关闭) /// <summary> /// 串口初始化,打开串口。 /// </summary> public bool InitPort() { DCB dcbCommPort = new DCB(); COMMTIMEOUTS ctoCommPort = new COMMTIMEOUTS(); //// 如果串口没有打开,就打开 IF THE PORT CANNOT BE OPENED, BAIL OUT. //if (hComm != INVALID_HANDLE_VALUE) //{ // CloseHandle(hComm); //} // 打开串口 OPEN THE COMM PORT. hComm = CreateFile(PortNum, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0); if (hComm != INVALID_HANDLE_VALUE) { char[] szBaud = new char[50]; dcbCommPort.flags = 0; // 设置通信超时时间 SET THE COMM TIMEOUTS. GetCommTimeouts(hComm, ref ctoCommPort); ctoCommPort.ReadIntervalTimeout = 300; ctoCommPort.ReadTotalTimeoutConstant = 10; ctoCommPort.ReadTotalTimeoutMultiplier = 10; ctoCommPort.WriteTotalTimeoutMultiplier = 10; ctoCommPort.WriteTotalTimeoutConstant = 10; SetCommTimeouts(hComm, ref ctoCommPort); if (dcbCommPort.fParity != 1) { dcbCommPort.fParity = 1; } // 设置串口 SET BAUD RATE, PARITY, WORD SIZE, AND STOP BITS. string szbaud = "baud=" + BaudRate + " parity=" + Parity + " data=" + ByteSize + " stop=" + StopBits; dcbCommPort.DCBlength = Marshal.SizeOf(dcbCommPort); if (GetCommState(hComm, ref dcbCommPort)) { if (BuildCommDCB(szbaud, ref dcbCommPort)) { if (SetCommState(hComm, ref dcbCommPort)) { ; // normal operation... continue } else { uint ErrorNum = GetLastError(); ErrorMsg = "串口参数设置失败SetCommState!" + ErrorNum; } } else { uint ErrorNum = GetLastError(); ErrorMsg = "串口参数设置失败BuildCommDCB!" + ErrorNum; } } else { uint ErrorNum = GetLastError(); ErrorMsg = "串口参数获取失败GetCommState!" + ErrorNum; } return(true); } else { return(false); } }
public bool GetPortSettings(out DCB dcb) { unsafe { DCB dcb2 = new DCB(); dcb2.DCBlength = sizeof(DCB); bool ret = GetCommState(m_hFile, &dcb2); dcb = dcb2; return ret; } }
private static extern bool BuildCommDCB(string lpDef, ref DCB lpDCB);
static unsafe extern bool BuildCommDCB(string def, DCB* lpDCB);
private static extern bool BuildCommDCB( string lpDef, // 设备控制字符串 ref DCB lpDCB // 设备控制块 );
internal static extern bool SetCommState( IntPtr hFile, ref DCB lpDCB );
private static extern bool GetCommState( int hFile, //通信设备句柄 ref DCB lpDCB // 设备控制块DCB );
public bool SetPortSettings(DCB dcb) { return(SetCommState(m_hFile, ref dcb)); }
///<summary> ///建立与串口的连接 ///</summary> public int Open() { DCB dcb = new DCB(); COMMTIMEOUTS ctoCommPort = new COMMTIMEOUTS(); // 打开串口 hComm = CreateFile(Port, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0); if (hComm == INVALID_HANDLE_VALUE) { return -1; } // 设置通信超时时间 GetCommTimeouts(hComm, ref ctoCommPort); ctoCommPort.ReadTotalTimeoutConstant = ReadTimeout; ctoCommPort.ReadTotalTimeoutMultiplier = 0; ctoCommPort.WriteTotalTimeoutMultiplier = 0; ctoCommPort.WriteTotalTimeoutConstant = 0; SetCommTimeouts(hComm, ref ctoCommPort); //设置串口参数 GetCommState(hComm, ref dcb); dcb.DCBlength = Marshal.SizeOf(dcb); dcb.BaudRate = BaudRate; dcb.flags = 0; dcb.ByteSize = (byte)ByteSize; dcb.StopBits = StopBits; dcb.Parity = (byte)Parity; //------------------------------ SetDcbFlag(0, 1, dcb); //二进制方式 SetDcbFlag(1, (Parity == 0) ? 0 : 1, dcb); SetDcbFlag(2, 0, dcb); //不用CTS检测发送流控制 SetDcbFlag(3, 0, dcb); //不用DSR检测发送流控制 SetDcbFlag(4, 0, dcb); //禁止DTR流量控制 SetDcbFlag(6, 0, dcb); //对DTR信号线不敏感 SetDcbFlag(9, 1, dcb); //检测接收缓冲区 SetDcbFlag(8, 0, dcb); //不做发送字符控制 SetDcbFlag(10, 0, dcb); //是否用指定字符替换校验错的字符 SetDcbFlag(11, 0, dcb); //保留NULL字符 SetDcbFlag(12, 0, dcb); //允许RTS流量控制 SetDcbFlag(14, 0, dcb); //发送错误后,继续进行下面的读写操作 //-------------------------------- dcb.wReserved = 0; //没有使用,必须为0 dcb.XonLim = 0; //指定在XOFF字符发送之前接收到缓冲区中可允许的最小字节数 dcb.XoffLim = 0; //指定在XOFF字符发送之前缓冲区中可允许的最小可用字节数 dcb.XonChar = 0; //发送和接收的XON字符 dcb.XoffChar = 0; //发送和接收的XOFF字符 dcb.ErrorChar = 0; //代替接收到奇偶校验错误的字符 dcb.EofChar = 0; //用来表示数据的结束 dcb.EvtChar = 0; //事件字符,接收到此字符时,会产生一个事件 dcb.wReserved1 = 0; //没有使用 if (!SetCommState(hComm, ref dcb)) { return -2; } Opened = true; return 0; }
static extern bool SetCommState(IntPtr hFile, ref DCB lpDCB);
private static extern int BuildCommDCB(string lpDef, DCB lpDCB);
static extern bool BuildCommDCB(string def, ref DCB lpDCB);
internal static extern bool SetCommState(IntPtr hFile, [In] ref DCB lpDCB);
public void Open() { DCB dcbCommPort = new DCB(); COMMTIMEOUTS ctoCommPort = new COMMTIMEOUTS(); // OPEN THE COMM PORT. // see http://support.microsoft.com/default.aspx?scid=kb;%5BLN%5D;115831 for the reasons for // the bizarre comm port syntax hComm = CreateFile("\\\\.\\COM" + 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("Comm Port \"COM" + PortNum + "\" Can Not Be Opened")); } // SET THE COMM TIMEOUTS. GetCommTimeouts(hComm,ref ctoCommPort); ctoCommPort.ReadIntervalTimeout = -1; ctoCommPort.ReadTotalTimeoutConstant = 0; /* ReadTimeout */ ctoCommPort.ReadTotalTimeoutMultiplier = 0; ctoCommPort.WriteTotalTimeoutConstant = 50; ctoCommPort.WriteTotalTimeoutMultiplier = 35; // @ 300 bps, about 27 msecs per char if ( SetCommTimeouts(hComm,ref ctoCommPort) == false ) { Console.WriteLine("SetCommTO failed\n"); } // SET BAUD RATE, PARITY, WORD SIZE, AND STOP BITS. GetCommState(hComm, ref dcbCommPort); dcbCommPort.BaudRate=BaudRate; dcbCommPort.flags=0; // dcbCommPort.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("Comm Port COM" + PortNum + " Can Not Be Opened. Error=" + ErrorNum + ".")); } //unremark to see if setting took correctly //DCB dcbCommPort2 = new DCB(); //GetCommState(hComm, ref dcbCommPort2); Opened = true; }
internal static extern bool BuildCommDCBAndTimeouts(string lpDef, ref DCB lpDCB, ref COMMTIMEOUTS lpCommTimeouts);
public static extern bool SetCommState(IntPtr hFile, ref DCB dcb);
internal static extern bool GetCommState(IntPtr hFile, ref DCB lpDCB);
override internal bool GetCommState(IntPtr hPort, DCB dcb) { return(Convert.ToBoolean(WinGetCommState(hPort, dcb))); }
public override bool Open(bool fTraceFailure=true) { try { // Get a file handle to the serial port. // REVIEW: How can we control the timeout used in this operation? // this.hSerialPort = WIN32.CreateFile(@"\\.\" + this.portName, WIN32.GENERIC_READ|WIN32.GENERIC_WRITE, 0, // share mode IntPtr.Zero, // security attributes OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, IntPtr.Zero ); if (this.SerialPortHandleIsValid) { // TO DO: call SetupComm // TO DO: consider COMMCONFIG, COMMPROP // Set the stuff we set using the DCB. Do a 'get' first // so that we only change the stuff we're looking to actually change // WIN32.DCB dcb = new DCB(); dcb.Initialize(); ThrowIfFail(WIN32.GetCommState(this.hSerialPort, ref dcb)); dcb.BaudRate = 115200; // arbitrary/historical, but seems to work dcb.SetFlag(WIN32.DCBFLAG.DISCARDNULL, 0); ThrowIfFail(WIN32.SetCommState(this.hSerialPort, ref dcb)); // Set the timeouts. We specify all the fields do // don't need to do a 'get' first. WIN32.COMMTIMEOUTS timeouts = new COMMTIMEOUTS(); timeouts.ReadTotalTimeoutConstant = 500; timeouts.ReadTotalTimeoutMultiplier = -1; timeouts.ReadIntervalTimeout = -1; timeouts.WriteTotalTimeoutMultiplier = 0; timeouts.WriteTotalTimeoutConstant = 500; ThrowIfFail(WIN32.SetCommTimeouts(this.hSerialPort, ref timeouts)); this.readThread = new ThreadContext((ctx) => ReadThread((ThreadContext)ctx)); this.readThread.Start(); this.readThreadRunning.WaitOne(); } else WIN32.ThrowWin32Error(); Program.TheForm.ConnectionWantsTelemetryPolling = false; return base.Open(fTraceFailure); } catch (Exception) { if (fTraceFailure) Program.ReportError("warning: can't open serial port {0} (is the NXT connected?)", this.portName); this.Close(); return false; } }
private static extern int WinSetCommState(IntPtr hFile, DCB dcb);
public static extern Boolean BuildCommDCBAndTimeouts(String lpDef, ref DCB lpDCB, ref COMMTIMEOUTS lpCommTimeouts);
private static extern bool SetCommState(uint hFile, ref DCB lpDCB);
internal static extern bool SetCommState( SafeFileHandle hFile, // handle to communications device ref DCB lpDCB // device-control block );
public bool Open() { bool fRet = false; DCB dcbCommPort = new DCB(); COMMTIMEOUTS ctoCommPort = new COMMTIMEOUTS(); //ensure comport is closed Close(); // Open select Gps COM port m_hCOMPort = CreateFile("\\\\.\\COM" + m_iCOMPort.ToString().Trim(), GENERIC_READ, 0, 0, OPEN_EXISTING, 0, 0); if (m_hCOMPort != INVALID_HANDLE_VALUE) { uint uxErrors = 0; COMSTAT xstat = new COMSTAT(); ClearCommError(m_hCOMPort, ref uxErrors, ref xstat); PurgeComm(m_hCOMPort, PURGE_RXCLEAR); // SET THE COMM TIMEOUTS. GetCommTimeouts(m_hCOMPort, ref ctoCommPort); ctoCommPort.ReadIntervalTimeout = 0; //200ms read timeout ctoCommPort.ReadTotalTimeoutConstant = 100; ctoCommPort.ReadTotalTimeoutMultiplier = 0; SetCommTimeouts(m_hCOMPort, ref ctoCommPort); // SET BAUD RATE, PARITY, WORD SIZE, AND STOP BITS. dcbCommPort.DCBlength = (uint)Marshal.SizeOf(dcbCommPort); GetCommState(m_hCOMPort, ref dcbCommPort); dcbCommPort.DCBlength = (uint)Marshal.SizeOf(dcbCommPort); dcbCommPort.BaudRate = m_iBaudRate; dcbCommPort.Parity = m_byParity; dcbCommPort.ByteSize = m_byByteSize; dcbCommPort.StopBits = m_byStopBits; dcbCommPort.flags = 1; switch (m_iFlowControl) { case 0: //None dcbCommPort.flags = 0x1091; //use 1091 for no abort on error 50 break; case 1: //Hardware dcbCommPort.flags = 0x2095; //use 2095 for no abort on error 60 break; case 2: //Sw dcbCommPort.flags = 0x1391; //use 1391 for no abort on error 53 break; } dcbCommPort.XonLim = 0x50; dcbCommPort.XoffLim = 0xC8; dcbCommPort.XonChar = Convert.ToChar(0x11); dcbCommPort.XoffChar = Convert.ToChar(0x13); dcbCommPort.wReserved = 0; dcbCommPort.wReserved1 = 0; dcbCommPort.ErrorChar = Convert.ToChar(0); dcbCommPort.EvtChar = Convert.ToChar(0); dcbCommPort.EofChar = Convert.ToChar(0); if (SetCommState(m_hCOMPort, ref dcbCommPort)) { fRet = true; } } IsOpen = fRet; m_bClose = !fRet; return(fRet); }
static extern bool GetCommState(IntPtr hFile, ref DCB lpDCB);
public void Open() { DCB dcbCommPort = new DCB(); COMMTIMEOUTS ctoCommPort = new COMMTIMEOUTS(); // OPEN THE COMM PORT. // see http://support.microsoft.com/default.aspx?scid=kb;%5BLN%5D;115831 for the reasons for // the bizarre comm port syntax hComm = CreateFile("\\\\.\\COM" + 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("Comm Port \"COM" + PortNum + "\" Can Not Be Opened")); } // SET THE COMM TIMEOUTS. GetCommTimeouts(hComm, ref ctoCommPort); ctoCommPort.ReadIntervalTimeout = -1; ctoCommPort.ReadTotalTimeoutConstant = 0; /* ReadTimeout */ ctoCommPort.ReadTotalTimeoutMultiplier = 0; ctoCommPort.WriteTotalTimeoutConstant = 50; ctoCommPort.WriteTotalTimeoutMultiplier = 35; // @ 300 bps, about 27 msecs per char if (SetCommTimeouts(hComm, ref ctoCommPort) == false) { Console.WriteLine("SetCommTO failed\n"); } // SET BAUD RATE, PARITY, WORD SIZE, AND STOP BITS. GetCommState(hComm, ref dcbCommPort); dcbCommPort.BaudRate = BaudRate; dcbCommPort.flags = 0; // dcbCommPort.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("Comm Port COM" + PortNum + " Can Not Be Opened. Error=" + ErrorNum + ".")); } //unremark to see if setting took correctly //DCB dcbCommPort2 = new DCB(); //GetCommState(hComm, ref dcbCommPort2); Opened = true; }