Beispiel #1
0
        /// <summary>
        /// 打开端口
        /// </summary>
        public void Open()
        {
            _iHandle = Win32Com.CreateFile(Name, 0x40000000, 0, 0, 3, 0, 0);
            if (_iHandle != -1)
            {
                this.IsOpen = true;
            }
            else
            {
                this.IsOpen = false;
            }

            this.IsOpen = true;
            _isWork     = true;
            //开一个线程检测状态口状态
            new System.Threading.Thread(new System.Threading.ThreadStart(ReadState)).Start();
        }
Beispiel #2
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);
        }
Beispiel #3
0
        private void ReceiveSendThreadSerial()
        {
            var buffer           = new byte[64];
            var restart          = false;
            var sendMessageBytes = new byte[0];
            int sentBytes        = 0;
            var sendTimeout      = new Stopwatch();
            var portHandle       = IntPtr.Zero;

            Thread.Sleep(1000);
            _receivedBytes.Clear();
            var resetEvent    = new AutoResetEvent(false);
            var overlapped    = new OVERLAPPED();
            var ptrOverlapped = Marshal.AllocHGlobal(Marshal.SizeOf(overlapped));

            overlapped.Offset     = 0;
            overlapped.OffsetHigh = 0;
            overlapped.hEvent     = resetEvent.SafeWaitHandle.DangerousGetHandle();
            Marshal.StructureToPtr(overlapped, ptrOverlapped, true);
            bool waitingRead        = false;
            var  writeResetEvent    = new AutoResetEvent(false);
            var  writeOverlapped    = new OVERLAPPED();
            var  ptrWriteOverlapped = Marshal.AllocHGlobal(Marshal.SizeOf(writeOverlapped));

            writeOverlapped.Offset     = 0;
            writeOverlapped.OffsetHigh = 0;
            writeOverlapped.hEvent     = writeResetEvent.SafeWaitHandle.DangerousGetHandle();;
            Marshal.StructureToPtr(writeOverlapped, ptrWriteOverlapped, true);
            bool waitingWrite = false;

            while (!_receiveSendThreadStopped)
            {
                try
                {
                    if (portHandle == IntPtr.Zero)
                    {
                        int    portnumber = Int32.Parse(_comPort.Replace("COM", String.Empty));
                        string comPort    = _comPort;
                        if (portnumber > 9)
                        {
                            comPort = String.Format("\\\\.\\{0}", _comPort);
                        }
                        portHandle = Win32Com.CreateFile(comPort, Win32Com.GENERIC_READ | Win32Com.GENERIC_WRITE, 0, IntPtr.Zero,
                                                         Win32Com.OPEN_EXISTING, Win32Com.FILE_FLAG_OVERLAPPED, IntPtr.Zero);

                        if (portHandle == (IntPtr)Win32Com.INVALID_HANDLE_VALUE)
                        {
                            if (Marshal.GetLastWin32Error() == Win32Com.ERROR_ACCESS_DENIED)
                            {
                                throw new Exception(String.Format("Access denied for port {0}", _comPort));
                            }
                            else
                            {
                                throw new Exception(String.Format("Failed to open port {0}", _comPort));
                            }
                        }

                        COMMTIMEOUTS commTimeouts = new COMMTIMEOUTS
                        {
                            ReadIntervalTimeout         = 5,
                            ReadTotalTimeoutConstant    = 0,
                            ReadTotalTimeoutMultiplier  = 0,
                            WriteTotalTimeoutConstant   = 0,
                            WriteTotalTimeoutMultiplier = 0
                        };
                        DCB dcb = new DCB();
                        dcb.Init(false, false, false, 0, false, false, false, false, 0);
                        dcb.BaudRate = _baudRate;
                        dcb.ByteSize = 8;
                        dcb.Parity   = 0;
                        dcb.StopBits = 0;
                        if (!Win32Com.SetupComm(portHandle, 8192, 4096))
                        {
                            throw new Exception(String.Format("Failed to set queue settings for port {0}", _comPort));
                        }
                        if (!Win32Com.SetCommState(portHandle, ref dcb))
                        {
                            throw new Exception(String.Format("Failed to set comm settings for port {0}", _comPort));
                        }
                        if (!Win32Com.SetCommTimeouts(portHandle, ref commTimeouts))
                        {
                            throw new Exception(String.Format("Failed to set comm timeouts for port {0}", _comPort));
                        }
                        if (_rtsCts)
                        {
                            if (!Win32Com.EscapeCommFunction(portHandle, Win32Com.CLRRTS))
                            {
                                throw new Exception(String.Format("Failed to reset RTS pin{0}", _comPort));
                            }
                        }
                        Thread.Sleep(1000);
                    }

                    if (!Win32Com.GetHandleInformation(portHandle, out uint lpdwFlags))
                    {
                        throw new Exception(String.Format("Port {0} went offline", _comPort));
                    }

                    if (!waitingRead)
                    {
                        waitingRead = true;
                        if (!Win32Com.ReadFile(portHandle, buffer, (uint)buffer.Length, out uint readBytes, ptrOverlapped))
                        {
                            if (Marshal.GetLastWin32Error() != Win32Com.ERROR_IO_PENDING)
                            {
                                throw new Exception(String.Format("Failed to read port {0}", _comPort));
                            }
                        }
                    }
                    else
                    {
                        if (resetEvent.WaitOne(10))
                        {
                            waitingRead = false;
                            if (!Win32Com.GetOverlappedResult(portHandle, ptrOverlapped, out uint readBytes, false))
                            {
                                throw new Exception(String.Format("Failed to read port {0}", _comPort));
                            }

                            for (int i = 0; i < readBytes; i++)
                            {
                                _receivedBytes.Add(buffer[i]);
                            }
                        }
                    }

                    if (_sendMessageQueue.Count > 0 && sendMessageBytes.Length == 0)
                    {
                        lock (_syncobject)
                            sendMessageBytes = _sendMessageQueue.Dequeue();
                        sentBytes = 0;
                    }

                    if (sendMessageBytes.Length > 0)
                    {
                        if (_rtsCts)
                        {
                            if (!Win32Com.EscapeCommFunction(portHandle, Win32Com.SETRTS))
                            {
                                lock (_syncobject)
                                    _sendExceptionQueue.Enqueue(new SBPSendExceptionEventArgs(new Exception(String.Format("Failed to set RTS pin{0}", _comPort))));
                            }
                        }

                        uint lpmodemstat = 0;
                        if (_rtsCts)
                        {
                            if (!Win32Com.GetCommModemStatus(portHandle, out lpmodemstat))
                            {
                                _sendExceptionQueue.Enqueue(new SBPSendExceptionEventArgs(new Exception(String.Format("Failed to get RTS pin{0}", _comPort))));
                            }
                        }

                        if ((lpmodemstat & Win32Com.MS_CTS_ON) > 0 || !_rtsCts)
                        {
                            if (!waitingWrite)
                            {
                                waitingWrite = true;
                                sendTimeout.Restart();
                                if (!Win32Com.WriteFile(portHandle, sendMessageBytes, (uint)sendMessageBytes.Length, out uint sent, ptrWriteOverlapped))
                                {
                                    if (Marshal.GetLastWin32Error() != Win32Com.ERROR_IO_PENDING)
                                    {
                                        _sendExceptionQueue.Enqueue(new SBPSendExceptionEventArgs(new Exception(String.Format("Failed to write to port {0}", _comPort))));
                                    }
                                }
                            }
                            else
                            {
                                if (writeResetEvent.WaitOne(0))
                                {
                                    if (!Win32Com.GetOverlappedResult(portHandle, ptrWriteOverlapped, out uint sent, false))
                                    {
                                        _sendExceptionQueue.Enqueue(new SBPSendExceptionEventArgs(new Exception(String.Format("Failed to write to port {0}", _comPort))));
                                    }

                                    sentBytes += (int)sent;
                                }
                            }

                            if (sentBytes == sendMessageBytes.Length || sendTimeout.ElapsedMilliseconds > 200)
                            {
                                if (sendTimeout.ElapsedMilliseconds > 100)
                                {
                                    lock (_syncobject)
                                        _sendExceptionQueue.Enqueue(new SBPSendExceptionEventArgs(new Exception(String.Format("Failed to write all bytes to port {0}", _comPort))));
                                }

                                if (_rtsCts)
                                {
                                    if (!Win32Com.EscapeCommFunction(portHandle, Win32Com.CLRRTS))
                                    {
                                        lock (_syncobject)
                                            _sendExceptionQueue.Enqueue(new SBPSendExceptionEventArgs(new Exception(String.Format("Failed to reset RTS pin{0}", _comPort))));
                                    }
                                }

                                sendMessageBytes = new byte[0];
                                waitingWrite     = false;
                            }
                        }
                    }

                    ProcessReading(restart);
                    restart = false;
                }
                catch (Exception e)
                {
                    _receivedBytes.Clear();
                    Win32Com.CancelIo(portHandle);
                    Win32Com.CloseHandle(portHandle);
                    portHandle = IntPtr.Zero;
                    restart    = true;
                    lock (_syncobject)
                        _readExceptionQueue.Enqueue(new SBPReadExceptionEventArgs(e));

                    Thread.Sleep(5000);
                }
            }

            Win32Com.CancelIo(portHandle);
            Win32Com.CloseHandle(portHandle);
            Marshal.FreeHGlobal(ptrOverlapped);
            Marshal.FreeHGlobal(ptrWriteOverlapped);
        }
Beispiel #4
0
        public bool OpenCom(String strPort, int iBaudRate)
        {
            var portDcb      = new DCB();
            var commTimeouts = new COMMTIMEOUTS();

            _hPort = Win32Com.CreateFile(strPort,
                                         Win32Com.GENERIC_READ | Win32Com.GENERIC_WRITE,
                                         0,
                                         IntPtr.Zero,
                                         Win32Com.OPEN_EXISTING,
                                         0,
                                         IntPtr.Zero);
            if (_hPort == (IntPtr)Win32Com.INVALID_HANDLE_VALUE)
            {
                return(false);
            }
            if (GetCommState(_hPort, ref portDcb))
            {
                portDcb.BaudRate = iBaudRate;
                portDcb.ByteSize = (byte)8;
                portDcb.Parity   = (byte)0;
                portDcb.StopBits = (byte)0;
                portDcb.fNull    = 0;
                portDcb.fParity  = 0;               /*
                                                     * portDcb.XonLim = 32768;
                                                     * portDcb.XoffLim = 8192;
                                                     * portDcb.XonChar= 17;
                                                     * portDcb.XoffChar = 19;
                                                     * portDcb.XoffChar = 19;
                                                     * portDcb.fOutxCtsFlow = 0;
                                                     * portDcb.fOutxDsrFlow  = 0;*/
            }
            else
            {
                CloseHandle(_hPort);
                return(false);
            }
            SetupComm(_hPort, DATA_BUFFER, DATA_BUFFER);
            if (!SetCommState(_hPort, ref portDcb))
            {
                CloseHandle(_hPort);
                return(false);
            }
            GetCommTimeouts(_hPort, out commTimeouts);

            commTimeouts.ReadIntervalTimeout         = MAXDWORD;
            commTimeouts.ReadTotalTimeoutConstant    = 0;
            commTimeouts.ReadTotalTimeoutMultiplier  = 0;
            commTimeouts.WriteTotalTimeoutConstant   = MAXDWORD;
            commTimeouts.WriteTotalTimeoutMultiplier = 0;

            // Set the time-out parameters for all read and write operations on the port.
            if (!SetCommTimeouts(_hPort, ref commTimeouts))
            {
                // Could not create the read thread.
                CloseHandle(_hPort);
                return(false);
            }

            // Clear the port of any existing data.
            PurgeComm(_hPort, PURGE_TXCLEAR | PURGE_RXCLEAR);

            return(true);
        }