Пример #1
0
            internal static COMMTIMEOUTS Create(uint sendTimeoutMultiplier, uint sendTimeoutConstant)
            {
                COMMTIMEOUTS commTimeouts = new COMMTIMEOUTS();

                //JH1.1: Changed from 0 to "magic number" to give instant return on ReadFile:
                commTimeouts.ReadIntervalTimeout        = NativeMethods.MAXDWORD;
                commTimeouts.ReadTotalTimeoutConstant   = 0;
                commTimeouts.ReadTotalTimeoutMultiplier = 0;

                //JH1.2: 0 does not seem to mean infinite on non-NT platforms, so default it to 10
                //seconds per byte which should be enough for anyone.
                if (sendTimeoutMultiplier == 0)
                {
                    if (System.Environment.OSVersion.Platform == System.PlatformID.Win32NT)
                    {
                        commTimeouts.WriteTotalTimeoutMultiplier = 0;
                    }
                    else
                    {
                        commTimeouts.WriteTotalTimeoutMultiplier = 10000;
                    }
                }
                else
                {
                    commTimeouts.WriteTotalTimeoutMultiplier = sendTimeoutMultiplier;
                }
                commTimeouts.WriteTotalTimeoutConstant = sendTimeoutConstant;

                return(commTimeouts);
            }
Пример #2
0
        //////////////////////////////////////////////////////////////////////////////////////
        //SERIAL METHODS
        //////////////////////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Opens the serial Port
        /// </summary>
        /// <param name="port">Port Name i.e. "COM1:"</param>
        /// <param name="readTimeOutConst">How long is the serial port wait for an answer</param>
        /// <returns></returns>
        public bool Open(string port, int readTimeOutConst)                                                     //port syntax: "COM#:"
        {
            //Configure/Prepare to Open
            Close();                                                            //Close port if already open
            DCB          dcbCommPort = new DCB();                               //Call DCB struct
            COMMTIMEOUTS ctoCommPort = new COMMTIMEOUTS();                      //Call COMMTIMEOUTS struct
            COMMPROP     commprop    = new COMMPROP();                          //Call COMMPROP struct

            //Open the COM port
            hComm = CreateFile(
                port,                                                                           //Pointer to the name of the port
                GENERIC_READ | GENERIC_WRITE,                                                   //Access (read-write) mode
                0,                                                                              //Share mode
                0,                                                                              //Pointer to the security attribute
                OPEN_EXISTING,                                                                  //How to open the serial port
                0,                                                                              //Port attributes
                0);                                                                             //Handle to port with attribute to copy
            // If Port Can't be Opened, Return
            if (this.hComm == INVALID_HANDLE_VALUE)
            {
                return(false);                                                          //Return, update user
            }
            if (this.hComm == INVALID_HANDLE_VALUE)
            {
                throw(new ApplicationException("Comm Port Can Not Be Opened"));
            }

            // Set the COMM Port Type
            commprop.dwProvSubType = 0x00000001;

            // Set the COMM Timeouts
            GetCommTimeouts(hComm, ref ctoCommPort);
            ctoCommPort.ReadTotalTimeoutConstant    = readTimeOutConst;
            ctoCommPort.ReadTotalTimeoutMultiplier  = 0;
            ctoCommPort.WriteTotalTimeoutMultiplier = 0;
            ctoCommPort.WriteTotalTimeoutConstant   = 0;
            SetCommTimeouts(hComm, ref ctoCommPort);

            // Set BAUD RATE, PARITY, WORD SIZE, AND STOP BITS. (From Above Values)
            GetCommState(hComm, ref dcbCommPort);
            dcbCommPort.BaudRate = BaudRate;
            dcbCommPort.flags    = 0;
            dcbCommPort.flags   |= 1;
            if (Parity > 0)
            {
                dcbCommPort.flags |= 2;
            }
            dcbCommPort.Parity   = Parity;
            dcbCommPort.ByteSize = ByteSize;
            dcbCommPort.StopBits = StopBits;

            if (!SetCommState(hComm, ref dcbCommPort))                                  //Throw failure exception if needed
            {
                uint ErrorNum = GetLastError();
            }

            Opened = true;                                                                                      //Port open

            return(true);                                                                                       //Return bool
        }
Пример #3
0
        /**/
        /// <summary>
        ///並口的初始化函數
        ///lpFileName 端口名
        ///baudRate  波特率
        ///parity  校驗位
        ///byteSize  數據位
        ///stopBits  停止位
        /// <summary>
        public bool OpenPort(string lpFileName, int baudRate, byte parity, byte byteSize, byte stopBits)
        {
            // OPEN THE COMM PORT.
            //hComm = CreateFile(lpFileName ,GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0);
            // IF THE PORT CANNOT BE OPENED, BAIL OUT.
            if (hComm == INVALID_HANDLE_VALUE)
            {
                // OPEN THE COMM PORT.
                hComm = CreateFile(lpFileName, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0);
                SetCommMask(hComm, EV_RXCHAR);
                //hComm = CreateFile("COM" + PortNum, GENERIC_READ | GENERIC_WRITE,0, 0,OPEN_EXISTING,FILE_FLAG_OVERLAPPED,0);
                return(true);
            }
            else
            {
                //System.MessageBox.Show("並口已打開");
                throw (new ApplicationException("並口已打開"));
            }
            //SetCommMask();

            SetupComm(hComm, MAXBLOCK, MAXBLOCK);

            // SET THE COMM TIMEOUTS.
            COMMTIMEOUTS ctoCommPort = new COMMTIMEOUTS();

            GetCommTimeouts(hComm, ref ctoCommPort);
            ctoCommPort.ReadIntervalTimeout         = Int32.MaxValue;
            ctoCommPort.ReadTotalTimeoutConstant    = 0;
            ctoCommPort.ReadTotalTimeoutMultiplier  = 0;
            ctoCommPort.WriteTotalTimeoutMultiplier = 10;
            ctoCommPort.WriteTotalTimeoutConstant   = 1000;
            SetCommTimeouts(hComm, ref ctoCommPort);

            // SET BAUD RATE, PARITY, WORD SIZE, AND STOP BITS.
            // THERE ARE OTHER WAYS OF DOING SETTING THESE BUT THIS IS THE EASIEST.
            // IF YOU WANT TO LATER ADD CODE FOR OTHER BAUD RATES, REMEMBER
            // THAT THE ARGUMENT FOR BuildCommDCB MUST BE A POINTER TO A STRING.
            // ALSO NOTE THAT BuildCommDCB() DEFAULTS TO NO HANDSHAKING.
            DCB dcbCommPort = new DCB();

            dcbCommPort.DCBlength = Marshal.SizeOf(dcbCommPort);
            GetCommState(hComm, ref dcbCommPort);    //取得並口的狀態

            dcbCommPort.BaudRate = baudRate;
            dcbCommPort.Parity   = parity;
            dcbCommPort.ByteSize = byteSize;
            dcbCommPort.StopBits = stopBits;

            if (!SetCommState(hComm, ref dcbCommPort))
            {
                throw (new ApplicationException("非法操作不能打开并口"));
            }

            PurgeComm(hComm, PURGE_RXCLEAR | PURGE_RXABORT);  //清空發送緩沖區的所有數據
            PurgeComm(hComm, PURGE_TXCLEAR | PURGE_TXABORT);  //清空收掃沖的骨有據
            SetCommMask(hComm, EV_RXCHAR);
            bOpened = true;
            return(true);
        }
Пример #4
0
        public void Open()
        {
            DCB          dcbCommPort = new DCB();
            COMMTIMEOUTS ctoCommPort = new COMMTIMEOUTS();
            // 打开串口 OPEN THE COMM PORT.
            string num = PortName.Replace("COM", "");

            if (int.Parse(num) >= 10)
            {
                hComm = CreateFile("////.//" + PortName, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0);
            }
            else
            {
                hComm = CreateFile(PortName, 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 Exception("非法操作,不能打开串口!"));
            }
            try
            {
                // 设置通信超时时间 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 = DataBits;
                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;
                IsOpen = true;
            }
            catch (Exception e) {
                Opened = false;
                IsOpen = false;
            }
        }
Пример #5
0
        ///<summary>
        ///建立与串口的连接
        ///</summary>
        public int Open(string portName)
        {
            Port = portName;
            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);
        }
Пример #6
0
 /// <summary>
 /// Timeouts constructor. Creates and initializes the class structure.
 /// </summary>
 internal Win32Tmout()
 {
     this.ct = new COMMTIMEOUTS();
     this.ct.readIntervalTimeout         = 1;     // wade, UInt32.MaxValue;	// instant return on ReadFile
     this.ct.readTotalTimeoutConstant    = 0;
     this.ct.readTotalTimeoutMultiplier  = 0;
     this.ct.writeTotalTimeoutMultiplier = 0;
     this.ct.writeTotalTimeoutConstant   = 0;
     return;
 }
Пример #7
0
 /// <summary>
 /// Timeouts constructor. Creates and initializes the class structure.
 /// </summary>
 internal Win32Tmout()
 {
     this.ct = new COMMTIMEOUTS();
     this.ct.readIntervalTimeout = UInt32.MaxValue;	// instant return on ReadFile
     this.ct.readTotalTimeoutConstant = 0;
     this.ct.readTotalTimeoutMultiplier = 0;
     this.ct.writeTotalTimeoutMultiplier = 0;
     this.ct.writeTotalTimeoutConstant = 0;
     return;
 }
Пример #8
0
        public void SetTimeouts(UInt32 readIntervalTimeout, UInt32 readTotalTimeoutMultiplier, UInt32 readTotalTimeoutConstant, UInt32 writeTotalTimeoutMultiplier, UInt32 writeTotalTimeoutConstant)
        {
            COMMTIMEOUTS timeouts = new COMMTIMEOUTS {
                ReadIntervalTimeout = readIntervalTimeout, ReadTotalTimeoutMultiplier = readTotalTimeoutMultiplier, ReadTotalTimeoutConstant = readTotalTimeoutConstant, WriteTotalTimeoutMultiplier = writeTotalTimeoutMultiplier, WriteTotalTimeoutConstant = writeTotalTimeoutConstant
            };

            if (!SetCommTimeouts(_Handle, ref timeouts))
            {
                throw new Win32Exception(Marshal.GetLastWin32Error(), "Cannot set timeouts on a serial port");
            }
        }
Пример #9
0
        public SerialPortStream(string portName, int baudRate, System.IO.Ports.Handshake flowControl)
        {
            _Handle = CreateFile(@"\\.\" + portName, FileAccess.ReadWrite, FileShare.None, IntPtr.Zero, FileMode.Open, FileAttributes.Normal | (FileAttributes)0x40000000, IntPtr.Zero);
            if (_Handle.IsInvalid)
                throw new Win32Exception(Marshal.GetLastWin32Error(), "Cannot open " + portName);

            ApplyAdvancedSettings(baudRate, flowControl);

            COMMTIMEOUTS timeouts = new COMMTIMEOUTS { ReadIntervalTimeout = 1 };
            if (!SetCommTimeouts(_Handle, ref timeouts))
                throw new Win32Exception(Marshal.GetLastWin32Error(), "Cannot set timeouts on " + portName);
        }
Пример #10
0
        /// <summary>
        /// 打开串口操作
        /// </summary>
        public void Open()
        {
            if (Opened)
            {
                return;
            }
            else
            {
                DCB          dcbCommPort = new DCB();
                COMMTIMEOUTS ctoCommPort = new COMMTIMEOUTS();


                // OPEN THE COMM PORT.


                hComm = CreateFile("COM" + PortNum, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, 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.
                // THERE ARE OTHER WAYS OF DOING SETTING THESE BUT THIS IS THE EASIEST.
                // IF YOU WANT TO LATER ADD CODE FOR OTHER BAUD RATES, REMEMBER
                // THAT THE ARGUMENT FOR BuildCommDCB MUST BE A POINTER TO A STRING.
                // ALSO NOTE THAT BuildCommDCB() DEFAULTS TO NO HANDSHAKING.

                dcbCommPort.DCBlength = Marshal.SizeOf(dcbCommPort);
                GetCommState(hComm, ref dcbCommPort);
                dcbCommPort.BaudRate = BaudRate;
                dcbCommPort.Parity   = Parity;
                dcbCommPort.ByteSize = ByteSize;
                dcbCommPort.StopBits = StopBits;
                if (!SetCommState(hComm, ref dcbCommPort))
                {
                    throw(new ApplicationException("Comm Port Set Failed!"));
                }

                Opened = true;
            }
        }
Пример #11
0
        /// <summary>
        /// 建立与串口的连接
        /// </summary>
        public bool Open()
        {
            DCB          dcbCommPort = new DCB();
            COMMTIMEOUTS ctoCommPort = new COMMTIMEOUTS();

            string strPortNum = PortNum.Replace("COM", "");
            int    nPortNum   = Convert.ToInt32(strPortNum);

            if (nPortNum >= 10)
            {
                PortNum = "\\\\.\\" + PortNum;
            }

            // 打开串口
            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.ReadIntervalTimeout         = ReadIntervalTimeout;
            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);
        }
Пример #12
0
        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;
        }
Пример #13
0
        /// <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);
            hComm = CreateFile(PortNum, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_FLAG_WRITE_THROUGH, 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);
            }

            if (!SetupComm(hComm, BytesToRead, BytesToWrite))
            {
                return(false);
            }

            Opened = true;
            return(true);
        }
Пример #14
0
        /// <summary>
        /// 并口的初始化函数
        /// </summary>
        /// <param name="lpFileName">端口名</param>
        /// <param name="baudRate">波特率</param>
        /// <param name="parity">校驗位</param>
        /// <param name="byteSize">數據位</param>
        /// <param name="stopBits">停止位</param>
        /// <returns></returns>
        public bool OpenPort(string lpFileName, int baudRate, byte parity, byte byteSize, byte stopBits)
        {
            #region
            if (hComm == INVALID_HANDLE_VALUE)
            {
                //uint ui = GENERIC_READ | GENERIC_WRITE;
                hComm = CreateFile(lpFileName, 0x40000000, 0, 0, OPEN_EXISTING, 0, 0);
                SetCommMask(hComm, EV_RXCHAR);
                return(true);
            }
            else
            {
                //throw (new ApplicationException("並口已打開"));
            }
            SetupComm(hComm, MAXBLOCK, MAXBLOCK);

            COMMTIMEOUTS ctoCommPort = new COMMTIMEOUTS();
            GetCommTimeouts(hComm, ref ctoCommPort);
            ctoCommPort.ReadIntervalTimeout         = Int32.MaxValue;
            ctoCommPort.ReadTotalTimeoutConstant    = 0;
            ctoCommPort.ReadTotalTimeoutMultiplier  = 0;
            ctoCommPort.WriteTotalTimeoutMultiplier = 10;
            ctoCommPort.WriteTotalTimeoutConstant   = 1000;
            SetCommTimeouts(hComm, ref ctoCommPort);

            DCB dcbCommPort = new DCB();
            dcbCommPort.DCBlength = Marshal.SizeOf(dcbCommPort);
            GetCommState(hComm, ref dcbCommPort);    //取得並口的狀態

            dcbCommPort.BaudRate = baudRate;
            dcbCommPort.Parity   = parity;
            dcbCommPort.ByteSize = byteSize;
            dcbCommPort.StopBits = stopBits;

            if (!SetCommState(hComm, ref dcbCommPort))
            {
                //throw (new ApplicationException("非法操作不能打开并口"));
            }
            PurgeComm(hComm, PURGE_RXCLEAR | PURGE_RXABORT);  //清空發送緩沖區的所有數據
            PurgeComm(hComm, PURGE_TXCLEAR | PURGE_TXABORT);  //清空收掃沖的骨有據
            SetCommMask(hComm, EV_RXCHAR);
            bOpened = true;
            return(true);

            #endregion
        }
Пример #15
0
        public bool open(string com)
        {
            DCB          PortDCB      = new DCB();
            COMMTIMEOUTS CommTimeouts = new COMMTIMEOUTS();
            OVERLAPPED   wo           = new OVERLAPPED();
            COMMPROP     cp;

            com  = @"\\.\" + com.Trim().ToUpper();
            hCom = CreateFile(com, GENERIC_READ | GENERIC_WRITE, 0, IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero);
            if ((IntPtr)INVALID_HANDLE_VALUE == hCom)
            {
                return(false);
            }

            CommTimeouts.ReadIntervalTimeout         = 30;
            CommTimeouts.ReadTotalTimeoutMultiplier  = 0;
            CommTimeouts.ReadTotalTimeoutConstant    = 30;
            CommTimeouts.WriteTotalTimeoutMultiplier = 30;
            CommTimeouts.WriteTotalTimeoutConstant   = 0;
            if (!SetCommTimeouts(hCom, ref CommTimeouts))
            {
                CloseHandle(hCom);
                return(false);
            }

            /*Serial port init
             * Refer to the PN532 data sheet (see Error! Reference source not found.).
             *   HSU interface default configuration is:
             *   Data bit  : 8 bits,
             *   Parity bit  : none,
             *   Stop bit  : 1 bit,
             *   Baud rate  : 115 200 bauds,
             *  Data order  : LSB first.
             **/
            BuildCommDCBA("baud=115200 data=8 parity=N stop=1", ref PortDCB);


            if (!SetCommState(hCom, ref PortDCB))
            {
                CloseHandle(hCom);
                return(false);
            }
            isOpen = true;
            return(true);
        }
Пример #16
0
        public bool OpenSerial(string portName, int baudRate)
        {
            handle = CreateFile(portName, READ_WRITE, 0, IntPtr.Zero, OPEN_EXISTING, 0x0, IntPtr.Zero);
            if (handle == (IntPtr)INVALID_HANDLE_VALUE)
            {
                int error = Marshal.GetLastWin32Error();
                switch ((uint)error)
                {
                case ERROR_ACCESS_DENIED:
                    Debug.LogError("Could not open serial port. Access Denied to " + portName);
                    return(false);

                case ERROR_FILE_NOT_FOUND:
                    Debug.LogError("Could not open serial port. Could not find " + portName);
                    return(false);

                default:
                    Debug.LogError("Could not open serial port. Unknown error: " + error);
                    return(false);
                }
            }

            //generate the COMMTIMEOUT struct
            //this struct marks an immediate return read and
            //10ms per character + 250ms write timeout
            COMMTIMEOUTS timeouts = new COMMTIMEOUTS(UInt32.MaxValue, 0, 0, 10, 250);
            //allocate the unmanaged memory for the struct
            IntPtr lpTimeouts = Marshal.AllocCoTaskMem(Marshal.SizeOf(timeouts));

            //push the struct data over to the unmanaged side
            Marshal.StructureToPtr(timeouts, lpTimeouts, false);

            if (!SetCommTimeouts(handle, lpTimeouts))
            {
                int error = Marshal.GetLastWin32Error();
                Debug.LogError("SetCommTimeouts Failed. Error: " + error);

                Marshal.FreeCoTaskMem(lpTimeouts);
                return(false);
            }

            Marshal.FreeCoTaskMem(lpTimeouts);
            return(true);
        }
Пример #17
0
        /// <summary>
        ///串口的初始化函数
        ///lpFileName  端口名
        ///baudRate   波特率
        ///parity   校验位
        ///byteSize   数据位
        ///stopBits   停止位
        /// <summary>
        public bool OpenPort(string lpFileName, int baudRate, byte parity, byte byteSize, byte stopBits)
        {
            // OPEN THE COMM PORT.
            hComm = CreateFile(lpFileName, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0);
            // IF THE PORT CANNOT BE OPENED, BAIL OUT.
            if (hComm == INVALID_HANDLE_VALUE)
            {
                return(false);
            }

            SetupComm(hComm, MAXBLOCK, MAXBLOCK);

            // SET THE COMM TIMEOUTS.
            COMMTIMEOUTS ctoCommPort = new COMMTIMEOUTS();

            GetCommTimeouts(hComm, ref ctoCommPort);
            //ctoCommPort.ReadIntervalTimeout = Int32.MaxValue;
            ctoCommPort.ReadTotalTimeoutConstant    = 100; //此数据是readfile返回的时间,非常重要
            ctoCommPort.ReadTotalTimeoutMultiplier  = 0;
            ctoCommPort.WriteTotalTimeoutMultiplier = 0;
            ctoCommPort.WriteTotalTimeoutConstant   = 0;
            SetCommTimeouts(hComm, ref ctoCommPort);

            // SET BAUD RATE, PARITY, WORD SIZE, AND STOP BITS.
            // THERE ARE OTHER WAYS OF DOING SETTING THESE BUT THIS IS THE EASIEST.
            // IF YOU WANT TO LATER ADD CODE FOR OTHER BAUD RATES, REMEMBER
            // THAT THE ARGUMENT FOR BuildCommDCB MUST BE A POINTER TO A STRING.
            // ALSO NOTE THAT BuildCommDCB() DEFAULTS TO NO HANDSHAKING.
            DCB dcbCommPort = new DCB();

            dcbCommPort.DCBlength = Marshal.SizeOf(dcbCommPort);
            GetCommState(hComm, ref dcbCommPort);
            dcbCommPort.BaudRate = baudRate;
            dcbCommPort.Parity   = parity;
            dcbCommPort.ByteSize = byteSize;
            dcbCommPort.StopBits = stopBits;
            SetCommState(hComm, ref dcbCommPort);

            PurgeComm(hComm, PURGE_RXCLEAR | PURGE_RXABORT);
            PurgeComm(hComm, PURGE_TXCLEAR | PURGE_TXABORT);

            bOpened = true;
            return(true);
        }
Пример #18
0
        public SerialPortStream(string portName, int baudRate, System.IO.Ports.Handshake flowControl)
        {
            _Handle = CreateFile(@"\\.\" + portName, FileAccess.ReadWrite, FileShare.None, IntPtr.Zero, FileMode.Open, FileAttributes.Normal | (FileAttributes)0x40000000, IntPtr.Zero);
            if (_Handle.IsInvalid)
            {
                throw new Win32Exception(Marshal.GetLastWin32Error(), "Cannot open " + portName);
            }

            ApplyAdvancedSettings(baudRate, flowControl);

            COMMTIMEOUTS timeouts = new COMMTIMEOUTS {
                ReadIntervalTimeout = 1
            };

            if (!SetCommTimeouts(_Handle, ref timeouts))
            {
                throw new Win32Exception(Marshal.GetLastWin32Error(), "Cannot set timeouts on " + portName);
            }
        }
Пример #19
0
        private const uint PURGE_RXCLEAR = 0x0008; // Kill the typeahead buffer if there.
        public void Open()
        {
            if (!IsOpen)
            {
                handle = CreateFile(@"\\.\COM" + portNum,                               // for COM1—COM9 only
                                    FileAccess.GENERIC_READ | FileAccess.GENERIC_WRITE, //Read/Write
                                    FileShare.NONE,                                     // No Sharing
                                    IntPtr.Zero,                                        // No Security
                                    FileMode.OPEN_EXISTING,                             // Open existing port only
                                    0,                                                  // Non Overlapped I/O
                                    IntPtr.Zero);
                int errorCode = Marshal.GetLastWin32Error();
                if (0 != errorCode)
                {
                    throw new IOException("Win32 API CreateFile() failed", errorCode);
                }

                bool OK;

                OK = SetCommMask(handle, 0);
                if (!OK)
                {
                    throw new IOException("Win32 API SetCommMask() failed", Marshal.GetLastWin32Error());
                }

                COMMTIMEOUTS comTimeouts = timeouts;
                OK = SetCommTimeouts(handle, ref comTimeouts);
                if (!OK)
                {
                    throw new IOException("Win32 API SetCommTimeouts() failed", Marshal.GetLastWin32Error());
                }

                refreshPortConfig();

                OK = PurgeComm(handle, PURGE_TXCLEAR | PURGE_RXCLEAR);
                if (!OK)
                {
                    throw new IOException("Win32 API PurgeComm() failed", Marshal.GetLastWin32Error());
                }

                IsOpen = true;
            }
        }
Пример #20
0
        public bool SetBlocking(bool block)
        {
            // set the serial connection timeouts
            COMMTIMEOUTS timeouts = new COMMTIMEOUTS();

            timeouts.ReadIntervalTimeout         = block ? 100 : uint.MaxValue;
            timeouts.ReadTotalTimeoutMultiplier  = 0;
            timeouts.ReadTotalTimeoutConstant    = 0;
            timeouts.WriteTotalTimeoutMultiplier = 0;
            timeouts.WriteTotalTimeoutConstant   = 0;
            if (SetCommTimeouts(pHandle, ref timeouts))
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
Пример #21
0
 /// <summary>
 /// Timeouts constructor. Creates and initializes the class structure.
 /// </summary>
 internal Win32Tmout(uint wttc, uint wttm)
 {
     this.ct = new COMMTIMEOUTS();
     this.ct.readIntervalTimeout = UInt32.MaxValue;	// instant return on ReadFile
     this.ct.readTotalTimeoutConstant = 0;
     this.ct.readTotalTimeoutMultiplier = 0;
     if(wttm == 0)
     {
         if(System.Environment.OSVersion.Platform == System.PlatformID.Win32NT)
             this.ct.writeTotalTimeoutMultiplier = 0;
         else
             this.ct.writeTotalTimeoutMultiplier = 10000;
     }
     else
     {
         this.ct.writeTotalTimeoutMultiplier = wttm;
     }
     this.ct.writeTotalTimeoutConstant = wttc;
     return;
 }
Пример #22
0
            public unsafe bool Init(uint BaudRate, byte ByteSize, byte Parity, byte StopBits)
            {
                if (handle == IntPtr.Zero)
                {
                    return(false);
                }

                // Init the com state
                DCB dcb = new DCB();

                if (!GetCommState(handle, ref dcb))
                {
                    return(false);
                }

                dcb.BaudRate = BaudRate;
                dcb.ByteSize = ByteSize;
                dcb.Parity   = Parity;
                dcb.StopBits = StopBits;

                if (!SetCommState(handle, ref dcb))
                {
                    return(false);
                }

                // Init the com timeouts
                COMMTIMEOUTS Commtimeouts = new COMMTIMEOUTS();

                if (!GetCommTimeouts(handle, ref Commtimeouts))
                {
                    return(false);
                }

                Commtimeouts.ReadIntervalTimeout = 600;
                if (!SetCommTimeouts(handle, ref Commtimeouts))
                {
                    return(false);
                }

                return(true);
            }
Пример #23
0
        public static bool InitCOM(IntPtr hCOMPort, String Str, int iTimeOut)
        {
            DCB          dcb = new DCB(), dcb1 = new DCB();
            COMMTIMEOUTS CommTimeOuts = new COMMTIMEOUTS();

            //if ( < 0) return FALSE;
            //PurgeComm(hCOMPort, -1);
            //CloseCOM();
            SetupComm(hCOMPort, 65535, 0xffff);
            GetCommState(hCOMPort, ref dcb);
            if (!BuildCommDCB(Str, ref dcb1))
            {
                return(false);
            }
            // Filling in the DCB
            dcb.BaudRate       = dcb1.BaudRate;
            dcb.ByteSize       = dcb1.ByteSize;
            dcb.Parity         = dcb1.Parity;
            dcb.StopBits       = dcb1.StopBits;
            dcb.Binary         = true;  // binary mode, no EOF check
            dcb.Parity         = 0;     // enable parity checking
            dcb.AbortOnError   = false; // abort reads/writes on error
            dcb.DtrControl     = DtrControl.Disable;
            dcb.RtsControl     = RtsControl.Disable;
            dcb.OutxCtsFlow    = false;
            dcb.OutxDsrFlow    = false;
            dcb.DsrSensitivity = false;
            dcb.OutX           = false;
            //---------------
            if (!SetCommState(hCOMPort, ref dcb))
            {
                return(false);
            }
            CommTimeOuts.ReadTotalTimeoutConstant    = 1500;
            CommTimeOuts.ReadTotalTimeoutMultiplier  = 11;
            CommTimeOuts.WriteTotalTimeoutConstant   = 200;
            CommTimeOuts.WriteTotalTimeoutMultiplier = 11;
            return(SetCommTimeouts(hCOMPort, ref CommTimeOuts));

            //------------------------
        }
Пример #24
0
        // 往并口写数据
        public bool WritePort(byte[] WriteBytes)
        {
            if (hComm == INVALID_HANDLE_VALUE)  //如果并口未打开
            {
                return(false);
            }

            COMSTAT ComStat      = new COMSTAT();
            int     dwErrorFlags = 0;

            ClearCommError(hComm, ref dwErrorFlags, ref ComStat);
            if (dwErrorFlags != 0)
            {
                PurgeComm(hComm, PURGE_TXCLEAR | PURGE_TXABORT);
            }

            OVERLAPPED ovlCommPort  = new OVERLAPPED();
            int        BytesWritten = 0;
            // SET THE COMM TIMEOUTS.
            COMMTIMEOUTS ctoCommPort = new COMMTIMEOUTS();

            GetCommTimeouts(hComm, ref ctoCommPort);
            ctoCommPort.ReadIntervalTimeout         = Int32.MaxValue;
            ctoCommPort.ReadTotalTimeoutConstant    = 0;
            ctoCommPort.ReadTotalTimeoutMultiplier  = 0;
            ctoCommPort.WriteTotalTimeoutMultiplier = 10;
            ctoCommPort.WriteTotalTimeoutConstant   = 3000;
            if (!SetCommTimeouts(hComm, ref ctoCommPort))
            {
                return(false);
            }
            WriteFile(hComm, WriteBytes, WriteBytes.Length, ref BytesWritten, ref ovlCommPort);
            if (BytesWritten > 0)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
Пример #25
0
        /// <summary>
        /// 发送命令
        /// </summary>
        /// <param name="SendData"></param>
        /// <param name="ReceiveData"></param>
        /// <param name="Overtime"></param>
        /// <returns></returns>
        public int SendCommand(byte[] SendData, ref byte[] ReceiveData, int Overtime)
        {
            if (hComm != INVALID_HANDLE_VALUE)
            {
                COMMTIMEOUTS ctoCommPort = new COMMTIMEOUTS();
                // 设置通信超时时间
                GetCommTimeouts(hComm, ref ctoCommPort);
                ctoCommPort.ReadTotalTimeoutConstant    = Overtime;
                ctoCommPort.ReadTotalTimeoutMultiplier  = 0;
                ctoCommPort.WriteTotalTimeoutMultiplier = 0;
                ctoCommPort.WriteTotalTimeoutConstant   = 200;              //叶帆 2007年11月21日
                SetCommTimeouts(hComm, ref ctoCommPort);

                ClearSendBuf();
                ClearReceiveBuf();

                Write(SendData, SendData.Length);
                return(Read(ref ReceiveData, ReceiveData.Length));
            }
            return(-1);
        }
Пример #26
0
        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);


            if (!GetCommState(hComm, ref dcb))
            {
                return(-1);
            }


            if (!BuildCommDCB(CommSetting, ref dcb))
            {
                return(-1);
            }
            if (!SetCommState(hComm, ref dcb))
            {
                return(-1);
            }
            Opened = true;
            return(0);
        }
Пример #27
0
 /// <summary>
 /// Timeouts constructor. Creates and initializes the class structure.
 /// </summary>
 internal Win32Tmout(uint wttc, uint wttm)
 {
     this.ct = new COMMTIMEOUTS();
     this.ct.readIntervalTimeout        = 1;      // wade, UInt32.MaxValue;	// instant return on ReadFile
     this.ct.readTotalTimeoutConstant   = 0;
     this.ct.readTotalTimeoutMultiplier = 0;
     if (wttm == 0)
     {
         if (System.Environment.OSVersion.Platform == System.PlatformID.Win32NT)
         {
             this.ct.writeTotalTimeoutMultiplier = 0;
         }
         else
         {
             this.ct.writeTotalTimeoutMultiplier = 10000;
         }
     }
     else
     {
         this.ct.writeTotalTimeoutMultiplier = wttm;
     }
     this.ct.writeTotalTimeoutConstant = wttc;
     return;
 }
Пример #28
0
 /// <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 = 10;//设置度仪表间隔时间10毫秒
         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;
     }
 }
 internal static extern bool GetCommTimeouts(IntPtr hFile, out COMMTIMEOUTS lpCommTimeouts);
Пример #30
0
 public static extern bool SetCommTimeouts(IntPtr hFile, [In] ref COMMTIMEOUTS lpCommTimeouts);
Пример #31
0
 internal static extern bool SetCommTimeouts(
     SafeFileHandle hFile,            // handle to comm device
     ref COMMTIMEOUTS lpCommTimeouts  // time-out values
     );
Пример #32
0
 public static extern bool SetCommTimeouts(IntPtr handle, out COMMTIMEOUTS timeouts);
Пример #33
0
 public static extern Boolean GetCommTimeouts(IntPtr hFile, out COMMTIMEOUTS lpCommTimeouts);
Пример #34
0
 private static extern bool SetCommTimeouts(int hFile, ref COMMTIMEOUTS lpCommTimeouts);
 internal static extern bool BuildCommDCBAndTimeouts(string lpDef, ref DCB lpDCB, ref COMMTIMEOUTS lpCommTimeouts);
Пример #36
0
		private static extern bool SetCommTimeouts(
		  int hFile,                  // handle to comm device
		  ref COMMTIMEOUTS lpCommTimeouts  // time-out values
		);
Пример #37
0
		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;
		  
		}
Пример #38
0
 ///<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;
 }
Пример #39
0
        private IntPtr PortOpen(string PortName, int Baudrate, byte Data, byte Parity, byte StopBit, int SendTime, int RecvTime)
        {
            IntPtr ipRet;
            DCB PortDCB = new DCB();
            COMMTIMEOUTS CommTimeouts = new COMMTIMEOUTS();

            ipRet = CreateFile(
                PortName,
                GENERIC_WRITE | GENERIC_READ,
                0,
                IntPtr.Zero,
                OPEN_EXISTING,
                FILE_ATTRIBUTE_NORMAL,
                IntPtr.Zero);

            if ((int)ipRet == INVALID_HANDLE_VALUE)
                return (ipRet);

            GetCommTimeouts(ipRet, CommTimeouts);
            CommTimeouts.ReadIntervalTimeout = 0;
            CommTimeouts.ReadTotalTimeoutMultiplier = 0;
            CommTimeouts.WriteTotalTimeoutConstant = RecvTime;
            CommTimeouts.WriteTotalTimeoutMultiplier = 0;
            CommTimeouts.WriteTotalTimeoutConstant = SendTime;
            SetCommTimeouts(ipRet, CommTimeouts);

            GetCommState(ipRet, PortDCB);
            PortDCB.BaudRate = Baudrate;
            PortDCB.Parity = Parity;
            PortDCB.ByteSize = Data;
            PortDCB.StopBits = StopBit;
            SetCommState(ipRet, PortDCB);
            return (ipRet);
        }
Пример #40
0
        /// <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;
            }
        }
Пример #41
0
 public static extern bool GetCommTimeouts(IntPtr hFile, ref COMMTIMEOUTS timeouts);
Пример #42
0
 public void SetTimeouts(UInt32 readIntervalTimeout, UInt32 readTotalTimeoutMultiplier, UInt32 readTotalTimeoutConstant, UInt32 writeTotalTimeoutMultiplier, UInt32 writeTotalTimeoutConstant)
 {
     COMMTIMEOUTS timeouts = new COMMTIMEOUTS { ReadIntervalTimeout = readIntervalTimeout, ReadTotalTimeoutMultiplier = readTotalTimeoutMultiplier, ReadTotalTimeoutConstant = readTotalTimeoutConstant, WriteTotalTimeoutMultiplier = writeTotalTimeoutMultiplier, WriteTotalTimeoutConstant = writeTotalTimeoutConstant };
     if (!SetCommTimeouts(_Handle, ref timeouts))
         throw new Win32Exception(Marshal.GetLastWin32Error(), "Cannot set timeouts on a serial port");
 }
Пример #43
0
        /// <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;
        }
Пример #44
0
 public static extern Boolean GetCommTimeouts(IntPtr hFile, out COMMTIMEOUTS lpCommTimeouts);
        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;
                }
            }
Пример #46
0
        /// <summary>
        /// Відкриття СОМ-порту
        /// </summary>
        /// <param name="portIndex">Номер порту</param>
        /// <returns>Якщо true то СОМ-порт відкритий успішно</returns>
        public bool Open(int portIndex)
        {
            string portName = "COM" + portIndex.ToString() + ":";
            handle = WApi.CreateFile(portName, (UInt32)(dwDesiredAccess.GENERIC_READ | dwDesiredAccess.GENERIC_WRITE),
                0, IntPtr.Zero, (UInt32)dwCreationDisposion.OPEN_EXISTING, (UInt32)dwFileFlags.FILE_FLAG_OVERLAPPED, IntPtr.Zero);

            if (handle == (IntPtr)WApi.INVALID_HANDLE_VALUE)
                return false;

            DCB _dcb = new DCB();
            WApi.GetCommState(handle, ref _dcb);
            //Setup dcb
            _dcb.BaudRate = (int)this.baudRate;
            //Clear RtsControl
            _dcb.Flags &= 0x7FFFCFFF;
            //Clear DsrControl
            _dcb.Flags &= 0x7FFFFFCF;
            //Set fBinary to 1
            _dcb.Flags |= 0x00000001;
            //Set fParity to 1
            _dcb.Flags |= 0x00000002;
            _dcb.ByteSize = (byte)this.dataBits;
            _dcb.Parity = (byte)this.parity;
            _dcb.StopBits = (byte)this.stopBits;

            //Handflow
            _dcb.XonLim = 2048;
            _dcb.XoffLim = 512;
            _dcb.XonChar = (char)0x11;
            _dcb.XoffChar = (char)0x13;

            if (!WApi.SetCommState(handle, ref _dcb))
            {
                System.Windows.Forms.MessageBox.Show("Задані неправильні параметри порту", "COM Порт",
                    System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                return false;
            }
            COMMTIMEOUTS _tOut = new COMMTIMEOUTS();
            WApi.GetCommTimeouts(handle, out _tOut);

            //Setup timeouts
            _tOut.ReadIntervalTimeout = ReadIntervalTimeout;
            _tOut.ReadTotalTimeoutConstant = ReadTotalTimeoutConstant;
            _tOut.ReadTotalTimeoutMultiplier = ReadTotalTimeoutMultiplier;
            _tOut.WriteTotalTimeoutConstant = WriteTotalTimeoutConstant;
            _tOut.WriteTotalTimeoutMultiplier = WriteTotalTimeoutMultiplier;

            if (!WApi.SetCommTimeouts(handle, ref _tOut))
            {
                System.Windows.Forms.MessageBox.Show("Задані неправильні таймаути порту", "COM Порт",
                    System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                return false;
            }

            WApi.PurgeComm(handle, WApi.PURGE_TXCLEAR);
            WApi.PurgeComm(handle, WApi.PURGE_RXCLEAR);

            isOpen = true;
            return true;
        }
Пример #47
0
 public static extern Boolean BuildCommDCBAndTimeouts(String lpDef, ref DCB lpDCB, ref COMMTIMEOUTS lpCommTimeouts);
Пример #48
0
	public static bool SetCommTimeouts (IntPtr hFile, ref COMMTIMEOUTS lpCommTimeouts)
	{
		Console.WriteLine ("Kernel32:SetCommTimeouts called");
		return true;
	}
Пример #49
0
        /// <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);
        }
Пример #50
0
        /// <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;
        }
Пример #51
0
 public static extern Boolean SetCommTimeouts([In()] CreateFileWHandle hFile, [In()] ref COMMTIMEOUTS lpCommTimeouts);
Пример #52
0
 private static extern bool GetCommTimeouts(
   int hFile,                                // 通信设备句柄 handle to comm device
   ref COMMTIMEOUTS lpCommTimeouts           // 超时时间 time-out values
 );
Пример #53
0
 public static extern Boolean BuildCommDCBAndTimeouts(String lpDef, ref DCB lpDCB, 
     ref COMMTIMEOUTS lpCommTimeouts);
Пример #54
0
		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;
		}
Пример #55
0
 internal static extern bool SetCommTimeouts(
     SafeFileHandle hFile,                  // handle to comm device
     ref COMMTIMEOUTS lpCommTimeouts  // time-out values
     );
Пример #56
0
 static extern bool SetCommTimeouts(SafeHandle hFile, ref COMMTIMEOUTS lpCommTimeouts);
Пример #57
0
 static extern bool SetCommTimeouts(IntPtr hFile, ref COMMTIMEOUTS lpCommTimeouts);
Пример #58
0
 private static extern bool SetCommTimeouts(IntPtr hObject, COMMTIMEOUTS pIntersectCTO);