Beispiel #1
0
        public Int32 ReadCom(byte[] toSend, int uiCount)
        {
            bool   bRes = false, bComEvent;
            UInt32 retlen;

            bComEvent = Win32Com.SetCommMask(_hPort, EV_RXCHAR);
            if (bComEvent)
            {
                bRes = ReadFile(_hPort,             // handle of file to read
                                toSend,             // pointer to buffer that receives data
                                (uint)uiCount,      // number of bytes to read
                                out retlen,         // pointer to number of bytes read
                                IntPtr.Zero         // pointer to structure for data
                                );
                if (!(bRes))
                {
                    return(0);
                }


                if (retlen > 0)                                 //If we have data
                {
                    return((Int32)retlen);                      //return the length
                }
                else
                {
                    return(0);                                                  //else no data has been read
                }
            }
            else
            {
                return(0);
            }
        }
Beispiel #2
0
        internal static bool send_init_to_master()
        {
            uint    retval = 0;
            COMSTAT cs;
            uint    er;

            writePacket(JVS_ADDR_BROADCAST, new[] { JVS_OP_RESET, JVS_OP_RESET_ARG });
            if (!Win32Com.ClearCommError(HPort, out er, out cs))
            {
                return(false);
            }
            if (!Win32Com.EscapeCommFunction(HPort, Win32Com.SETRTS))
            {
                return(false);
            }
            Thread.Sleep(1000);
            JVS_DEVICE_COUNT = 0;
            while (JVS_DEVICE_COUNT != 1)
            {
                JVS_DEVICE_COUNT++;
                //info(true, "Sending reset to JVS %08d", JVS_DEVICE_COUNT);
                send_init_to_JVS_board(JVS_DEVICE_COUNT);
            }
            return(true);
        }
Beispiel #3
0
 private bool CheckOnline()
 {
     if ((_rxException != null) && (!_rxExceptionReported))
     {
         _rxExceptionReported = true;
         ThrowException("rx");
     }
     if (_online)
     {
         uint f;
         if (Win32Com.GetHandleInformation(_hPort, out f))
         {
             return(true);
         }
         ThrowException("Offline");
         return(false);
     }
     if (_auto)
     {
         if (Open())
         {
             return(true);
         }
     }
     ThrowException("Offline");
     return(false);
 }
Beispiel #4
0
 /// <summary>
 /// Sends a protocol byte immediately ahead of any queued bytes.
 /// </summary>
 /// <param name="tosend">Byte to send</param>
 /// <returns>False if an immediate byte is already scheduled and not yet sent</returns>
 public void SendImmediate(byte tosend)
 {
     CheckOnline();
     if (!Win32Com.TransmitCommChar(_hPort, tosend))
     {
         ThrowException("Transmission failure");
     }
 }
Beispiel #5
0
        /// <summary>
        /// Gets the status of the modem control input signals.
        /// </summary>
        /// <returns>Modem status object</returns>
        protected ModemStatus GetModemStatus()
        {
            uint f;

            CheckOnline();
            if (!Win32Com.GetCommModemStatus(_hPort, out f))
            {
                ThrowException("Unexpected failure");
            }
            return(new ModemStatus(f));
        }
Beispiel #6
0
        internal static List <byte> GetJvsReply(byte node, byte[] package)
        {
            List <byte> result = new List <byte>();

            writePacket(node, package);

            //if (!ClearCommError(hPort, 0, 0))
            //return false;
            if (!Win32Com.EscapeCommFunction(HPort, Win32Com.SETRTS))
            {
                return(result);
            }

            uint    count = 0;
            uint    Err;
            COMSTAT CST;

            while (true)
            {
                Win32Com.ClearCommError(HPort, out Err, out CST);

                if ((CST.cbInQue > 0) || (count > 1000000))
                {
                    break;
                }
                count++;
            }
            result.AddRange(readPacket());

            if (result[0] != JVS_STATUS_OK)
            {
                Console.WriteLine("JVS Status not ok!");
                return(null);
            }
            if (result[1] != JVS_REPORT_OK)
            {
                Console.WriteLine("JVS Report not ok!");
                return(null);
            }

            //Console.WriteLine("Reply ok!");

            //info(true, "first eight bytes from reply buffer: %02x %02x %02x %02x %02x %02x %02x %02x", readData[0], readData[1], readData[2], readData[3], readData[4], readData[5], readData[6], readData[7]);

            // We remove status and report.
            result.RemoveAt(0);
            result.RemoveAt(0);

            return(result);
        }
Beispiel #7
0
        private static bool ReadTheComData()
        {
            COMSTAT cs;
            uint    er;

            if (!Win32Com.ClearCommError(HPort, out er, out cs))
            {
                return(false);
            }
            if (!Win32Com.EscapeCommFunction(HPort, Win32Com.CLRRTS))
            {
                return(false);
            }
            Thread.Sleep(1000);

            uint    count = 0;
            uint    Err;
            COMSTAT CST;

            while (true)
            {
                Win32Com.ClearCommError(HPort, out Err, out CST);

                if ((CST.cbInQue > 0) || (count > 1000000))
                {
                    break;
                }
                count++;
            }

            if (CST.cbInQue == 0)
            {
                return(false);
            }

            var result = readPacket();

            if (result[0] != JVS_STATUS_OK)
            {
                return(false);
            }
            if (result[1] != JVS_REPORT_OK)
            {
                return(false);
            }

            return(true);
        }
Beispiel #8
0
        /// <summary>
        /// Get the status of the queues
        /// </summary>
        /// <returns>Queue status object</returns>
        protected QueueStatus GetQueueStatus()
        {
            COMSTAT  cs;
            COMMPROP cp;
            uint     er;

            CheckOnline();
            if (!Win32Com.ClearCommError(_hPort, out er, out cs))
            {
                ThrowException("Unexpected failure");
            }
            if (!Win32Com.GetCommProperties(_hPort, out cp))
            {
                ThrowException("Unexpected failure");
            }
            return(new QueueStatus(cs.Flags, cs.cbInQue, cs.cbOutQue, cp.dwCurrentRxQueue, cp.dwCurrentTxQueue));
        }
Beispiel #9
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 #10
0
 private void InternalClose()
 {
     Win32Com.CancelIo(_hPort);
     if (_rxThread != null)
     {
         _rxThread.Abort();
         _rxThread = null;
     }
     Win32Com.CloseHandle(_hPort);
     if (_ptrUwo != IntPtr.Zero)
     {
         Marshal.FreeHGlobal(_ptrUwo);
     }
     _stateRts = 2;
     _stateDtr = 2;
     _stateBrk = 2;
     _online   = false;
 }
Beispiel #11
0
        /// <summary>
        /// Queues bytes for transmission.
        /// </summary>
        /// <param name="toSend">Array of bytes to be sent</param>
        public void Write(byte[] toSend)
        {
            uint sent;

            CheckOnline();
            CheckResult();
            _writeCount = toSend.GetLength(0);
            if (Win32Com.WriteFile(_hPort, toSend, (uint)_writeCount, out sent, _ptrUwo))
            {
                _writeCount -= (int)sent;
            }
            else
            {
                if (Marshal.GetLastWin32Error() != Win32Com.ERROR_IO_PENDING)
                {
                    ThrowException("Unexpected failure");
                }
            }
        }
Beispiel #12
0
        public bool WriteCom(byte[] toSend, uint uiCount)
        {
            uint sent;

            Win32Com.WriteFile(_hPort,          // Port handle
                               toSend,          // Pointer to the data to write
                               uiCount,         // Number of bytes to write
                               out sent,        // Pointer to the number of bytes written
                               IntPtr.Zero);    // Must be NULL

            if (sent > 0)
            {
                return(true);                                                   //Transmission was success
            }
            else
            {
                return(false);
            }
        }
Beispiel #13
0
        /// <summary>
        /// 向端口写入指定的数据
        /// </summary>
        /// <param name="Data">指定的数据</param>
        /// <returns></returns>
        public bool WriteData(byte[] Data)
        {
            //for (int i = 0; i < Data.Length; i++)
            //    Output(BasePort, Data[i]); 这里原来也想用inpout32实现,但是从字节到int转换比较麻烦,试了几次没达到效果
            //return true;

            if (_iHandle != -1)
            {
                Win32Com.OVERLAPPED x = new Win32Com.OVERLAPPED();
                int i = 0;
                Win32Com.WriteFile(_iHandle, Data, Data.Length, ref i, ref x);
                return(true);
            }
            else
            {
                //不能连接到打印机;
                return(false);
            }
        }
Beispiel #14
0
        private void CheckResult()
        {
            if (_writeCount <= 0)
            {
                return;
            }
            uint sent;

            if (Win32Com.GetOverlappedResult(_hPort, _ptrUwo, out sent, _checkSends))
            {
                _writeCount -= (int)sent;
                if (_writeCount != 0)
                {
                    ThrowException("Send Timeout");
                }
            }
            else
            {
                if (Marshal.GetLastWin32Error() != Win32Com.ERROR_IO_PENDING)
                {
                    ThrowException("Unexpected failure");
                }
            }
        }
Beispiel #15
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 #16
0
 /// <summary>
 /// 关闭端口
 /// </summary>
 public void Close()
 {
     this.IsOpen = !Win32Com.CloseHandle(_iHandle);
     _isWork     = false;
 }
Beispiel #17
0
		/// <summary>
		/// Check to see if the named com port is available.
		/// </summary>
		/// <returns>True if port available.</returns>
		public bool Available(string portName) 
		{
			Win32Com temp = new Win32Com();
			bool status = temp.Open(portName, false);
			if(status)
			{
				temp.Close();
			}
			temp = null;
			return status;
		}
Beispiel #18
0
		/// <summary>
		/// Closes and destroys the com port.
		/// </summary>
		protected void Destroy()
		{
			// Cancel I/O, kill receiver & close port.
			if(this.portOpen)
			{
				this.port.Cancel();
				if(this.rxThread != null)
				{
					this.rxThread.Abort();
					this.rxThread = null;
				}
				this.port.Close();
				this.portOpen = false;
			}

			// Reinit resources.
			this.dcb    = null;
			this.port   = null;
			this.stats  = null;
			this.props  = null;
			this.tmout  = null;
			this.rxOvr  = null;
			this.txOvr  = null;
			this.escape = null;
			this.writeEvent = null;
			this.recvrEvent = null;
			return;
		}
Beispiel #19
0
        private void ReceiveThread()
        {
            var buf = new Byte[1];

            var sg          = new AutoResetEvent(false);
            var ov          = new OVERLAPPED();
            var unmanagedOv = Marshal.AllocHGlobal(Marshal.SizeOf(ov));

            ov.Offset = 0; ov.OffsetHigh = 0;
            ov.hEvent = sg.Handle;
            Marshal.StructureToPtr(ov, unmanagedOv, true);

            uint eventMask = 0;
            var  uMask     = Marshal.AllocHGlobal(Marshal.SizeOf(eventMask));

            try
            {
                while (true)
                {
                    if (!Win32Com.SetCommMask(_hPort, Win32Com.EV_RXCHAR | Win32Com.EV_TXEMPTY | Win32Com.EV_CTS | Win32Com.EV_DSR
                                              | Win32Com.EV_BREAK | Win32Com.EV_RLSD | Win32Com.EV_RING | Win32Com.EV_ERR))
                    {
                        throw new CommPortException("IO Error [001]");
                    }
                    Marshal.WriteInt32(uMask, 0);
                    if (!Win32Com.WaitCommEvent(_hPort, uMask, unmanagedOv))
                    {
                        if (Marshal.GetLastWin32Error() == Win32Com.ERROR_IO_PENDING)
                        {
                            sg.WaitOne();
                        }
                        else
                        {
                            throw new CommPortException("IO Error [002]");
                        }
                    }
                    eventMask = (uint)Marshal.ReadInt32(uMask);
                    if ((eventMask & Win32Com.EV_ERR) != 0)
                    {
                        UInt32 errs;
                        if (Win32Com.ClearCommError(_hPort, out errs, IntPtr.Zero))
                        {
                            var s = new StringBuilder("UART Error: ", 40);
                            if ((errs & Win32Com.CE_FRAME) != 0)
                            {
                                s = s.Append("Framing,");
                            }
                            if ((errs & Win32Com.CE_IOE) != 0)
                            {
                                s = s.Append("IO,");
                            }
                            if ((errs & Win32Com.CE_OVERRUN) != 0)
                            {
                                s = s.Append("Overrun,");
                            }
                            if ((errs & Win32Com.CE_RXOVER) != 0)
                            {
                                s = s.Append("Receive Cverflow,");
                            }
                            if ((errs & Win32Com.CE_RXPARITY) != 0)
                            {
                                s = s.Append("Parity,");
                            }
                            if ((errs & Win32Com.CE_TXFULL) != 0)
                            {
                                s = s.Append("Transmit Overflow,");
                            }
                            s.Length = s.Length - 1;
                            throw new CommPortException(s.ToString());
                        }
                        throw new CommPortException("IO Error [003]");
                    }
                    if ((eventMask & Win32Com.EV_RXCHAR) != 0)
                    {
                        uint gotbytes;
                        do
                        {
                            if (!Win32Com.ReadFile(_hPort, buf, 1, out gotbytes, unmanagedOv))
                            {
                                if (Marshal.GetLastWin32Error() == Win32Com.ERROR_IO_PENDING)
                                {
                                    Win32Com.CancelIo(_hPort);
                                    gotbytes = 0;
                                }
                                else
                                {
                                    throw new CommPortException("IO Error [004]");
                                }
                            }
                            if (gotbytes == 1)
                            {
                                OnRxChar(buf[0]);
                            }
                        } while (gotbytes > 0);
                    }
                    if ((eventMask & Win32Com.EV_TXEMPTY) != 0)
                    {
                        OnTxDone();
                    }
                    if ((eventMask & Win32Com.EV_BREAK) != 0)
                    {
                        OnBreak();
                    }

                    uint i = 0;
                    if ((eventMask & Win32Com.EV_CTS) != 0)
                    {
                        i |= Win32Com.MS_CTS_ON;
                    }
                    if ((eventMask & Win32Com.EV_DSR) != 0)
                    {
                        i |= Win32Com.MS_DSR_ON;
                    }
                    if ((eventMask & Win32Com.EV_RLSD) != 0)
                    {
                        i |= Win32Com.MS_RLSD_ON;
                    }
                    if ((eventMask & Win32Com.EV_RING) != 0)
                    {
                        i |= Win32Com.MS_RING_ON;
                    }
                    if (i != 0)
                    {
                        uint f;
                        if (!Win32Com.GetCommModemStatus(_hPort, out f))
                        {
                            throw new CommPortException("IO Error [005]");
                        }
                        OnStatusChange(new ModemStatus(i), new ModemStatus(f));
                    }
                }
            }
            catch (Exception e)
            {
                if (uMask != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(uMask);
                }
                if (unmanagedOv != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(unmanagedOv);
                }
                if (!(e is ThreadAbortException))
                {
                    _rxException = e;
                    OnRxException(e);
                }
            }
        }
Beispiel #20
0
 private static byte readByte(out uint bytesRead)
 {
     byte[] c = new byte[256];
     Win32Com.ReadFile(HPort, c, 1, out bytesRead, IntPtr.Zero);
     return(c[0]);
 }
Beispiel #21
0
        private static void sendByte(byte b)
        {
            uint written = 0;

            Win32Com.WriteFile(HPort, new[] { b }, 1, out written, IntPtr.Zero);
        }
Beispiel #22
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 #23
0
		/// <summary>
		/// Create & opens the com port and configures it with the required settings.
		/// </summary>
		/// <param name="cfg">Reference to port user config.</param>
		/// <returns>True if port opened successfully.</returns>
		protected bool Create(SerialCnfg cfg) 
		{
			// If port already open, return.
			if(portOpen)
			{
				this.CommError("Com Port Already Open.");
				return false;
			}

			// Init members.
			this.fault = "";
			this.rxThread = null;
			this.writeEvent = new ManualResetEvent(false);
			this.recvrEvent = new ManualResetEvent(false);

			// Copy config to DCB.
			this.dcb = new Win32DCB(cfg);

			// Create handle to comm port.
			this.port = new Win32Com();
			if((this.portOpen = this.port.Open(cfg.PortName, true)) == false)
			{
				this.CommError(this.port.Fault);
				return false;
			}
			this.portName = cfg.PortName;

			// Instantiate support classes.
			this.stats  = new Win32Status();
			this.tmout  = new Win32Tmout();
			this.props  = new Win32Props();
			this.escape = new Win32Escape(port.Handle);

			// Set read/write timeouts.
			this.tmout.WriteConstant = cfg.TxTmoConst;
			this.tmout.WriteMultiplier = cfg.TxTmoMulti;
			if(this.tmout.Set(this.port.Handle) == false)
			{
				this.Destroy();
				this.CommError(this.tmout.Fault);
				return false;
			}

			// Overide OS default queue sizes.
			if((cfg.RxQueLen != 0) || (cfg.TxQueLen != 0))
			{
				if(this.props.Set(this.port.Handle, (uint)cfg.RxQueLen, (uint)cfg.TxQueLen) == false)
				{
					this.Destroy();
					this.CommError(this.props.Fault);
					return false;
				}
			}

			// Get the current properties.
			if(this.props.Get(this.port.Handle) == false)
			{
				this.Destroy();
				this.CommError(this.props.Fault);
				return false;
			}

			// Set flow control limits.
			this.dcb.Limits(cfg, this.props.RxCurSize);

			// Update the port settings.
			if(this.dcb.Set(this.port.Handle) == false)
			{
				this.Destroy();
				this.CommError(this.dcb.Fault);
				return false;
			}

			// XON/OFF extended functionality.
			this.escape.XOFFavailable = true;

			// RTS extended functionality.
			if(cfg.RtsControl == PinState.Disable)
				this.escape.RTS = false;
			else if(cfg.RtsControl == PinState.Enable)
				this.escape.RTS = true;
			else if(cfg.RtsControl == PinState.Handshake)
				this.escape.RTSavailable = false;

			// DTR extended functionality.
			if(cfg.DtrControl == PinState.Disable)
				this.escape.DTR = false;
			else if(cfg.DtrControl == PinState.Enable)
				this.escape.DTR = true;
			else if(cfg.DtrControl == PinState.Toggle)
				this.escape.DTR = false;
			else if(cfg.DtrControl == PinState.Handshake)
				this.escape.DTRavailable = false;

			// Create TX overlap memory pointer.
			this.txOvr = new Win32Ovrlap(this.port.Handle, this.writeEvent.Handle);

			// Set the receiver mode.
			this.immediate = cfg.ReceiveMode;

			// Start the receiver thread.
			this.rxThread = new Thread(new ThreadStart(ReceiveThread));
			this.rxThread.Name = "COMReceiver";
			this.rxThread.Priority = ThreadPriority.AboveNormal;
			this.rxThread.Start();

			// Wait for receive thread to start.
			this.recvrEvent.WaitOne(500, false);

			// Port opened OK.
			return true;
		}
Beispiel #24
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);
        }