Beispiel #1
0
        private void ApplyAdvancedSettings(int baudRate, System.IO.Ports.Handshake flowControl)
        {
            DCB dcb = new DCB {
                DCBLength = (uint)Marshal.SizeOf(typeof(DCB))
            };

            if (!GetCommState(_Handle, ref dcb))
            {
                throw new Win32Exception(Marshal.GetLastWin32Error(), "Cannot query comm state for serial port");
            }

            dcb.BaudRate = (uint)baudRate;
            dcb.ByteSize = 8;
            dcb.Parity   = Parity.None;
            dcb.StopBits = StopBits.One;

            switch (flowControl)
            {
            case System.IO.Ports.Handshake.None:
                dcb.TxContinueOnXoff = false;
                dcb.OutX             = false;
                dcb.RtsControl       = RtsControl.Enable;
                dcb.DtrControl       = DtrControl.Enable;
                dcb.OutxCtsFlow      = false;
                dcb.OutxDsrFlow      = false;
                break;

            case System.IO.Ports.Handshake.XOnXOff:
                dcb.TxContinueOnXoff = true;
                dcb.OutX             = true;
                dcb.RtsControl       = RtsControl.Enable;
                dcb.DtrControl       = DtrControl.Enable;
                dcb.OutxCtsFlow      = false;
                dcb.OutxDsrFlow      = false;
                break;

            case System.IO.Ports.Handshake.RequestToSend:
                dcb.TxContinueOnXoff = false;
                dcb.OutX             = false;
                dcb.RtsControl       = RtsControl.Handshake;
                dcb.DtrControl       = DtrControl.Enable;
                dcb.OutxCtsFlow      = true;
                dcb.OutxDsrFlow      = false;
                break;

            case System.IO.Ports.Handshake.RequestToSendXOnXOff:
                dcb.TxContinueOnXoff = true;
                dcb.OutX             = true;
                dcb.RtsControl       = RtsControl.Handshake;
                dcb.DtrControl       = DtrControl.Enable;
                dcb.OutxCtsFlow      = true;
                dcb.OutxDsrFlow      = false;
                break;
            }

            if (!SetCommState(_Handle, ref dcb))
            {
                throw new Win32Exception(Marshal.GetLastWin32Error(), "Cannot set comm state for serial port");
            }
        }
Beispiel #2
0
 /// <summary>
 /// 关闭
 /// </summary>
 public void Close()
 {
     isopen = false;
     OnClosing(EventArgs.Empty);
     unsolicitedThread.Join();
     System.IO.Ports.Handshake handshake = SerialPort.Handshake;
     try
     {
         SerialPort.Handshake = System.IO.Ports.Handshake.None;
         SerialPort.Close();
     }
     finally
     {
         SerialPort.Handshake = handshake;
     }
     Log("Modem is closed");
 }
Beispiel #3
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);
            }
        }
 internal SerialStream(string portName, int baudRate, System.IO.Ports.Parity parity, int dataBits, System.IO.Ports.StopBits stopBits, int readTimeout, int writeTimeout, System.IO.Ports.Handshake handshake, bool dtrEnable, bool rtsEnable, bool discardNull, byte parityReplace)
 {
     int dwFlagsAndAttributes = 0x40000000;
     if (Environment.OSVersion.Platform == PlatformID.Win32Windows)
     {
         dwFlagsAndAttributes = 0x80;
         this.isAsync = false;
     }
     if ((portName == null) || !portName.StartsWith("COM", StringComparison.OrdinalIgnoreCase))
     {
         throw new ArgumentException(SR.GetString("Arg_InvalidSerialPort"), "portName");
     }
     SafeFileHandle hFile = Microsoft.Win32.UnsafeNativeMethods.CreateFile(@"\\.\" + portName, -1073741824, 0, IntPtr.Zero, 3, dwFlagsAndAttributes, IntPtr.Zero);
     if (hFile.IsInvalid)
     {
         InternalResources.WinIOError(portName);
     }
     try
     {
         int fileType = Microsoft.Win32.UnsafeNativeMethods.GetFileType(hFile);
         if ((fileType != 2) && (fileType != 0))
         {
             throw new ArgumentException(SR.GetString("Arg_InvalidSerialPort"), "portName");
         }
         this._handle = hFile;
         this.portName = portName;
         this.handshake = handshake;
         this.parityReplace = parityReplace;
         this.tempBuf = new byte[1];
         this.commProp = new Microsoft.Win32.UnsafeNativeMethods.COMMPROP();
         int lpModemStat = 0;
         if (!Microsoft.Win32.UnsafeNativeMethods.GetCommProperties(this._handle, ref this.commProp) || !Microsoft.Win32.UnsafeNativeMethods.GetCommModemStatus(this._handle, ref lpModemStat))
         {
             int errorCode = Marshal.GetLastWin32Error();
             switch (errorCode)
             {
                 case 0x57:
                 case 6:
                     throw new ArgumentException(SR.GetString("Arg_InvalidSerialPortExtended"), "portName");
             }
             InternalResources.WinIOError(errorCode, string.Empty);
         }
         if ((this.commProp.dwMaxBaud != 0) && (baudRate > this.commProp.dwMaxBaud))
         {
             throw new ArgumentOutOfRangeException("baudRate", SR.GetString("Max_Baud", new object[] { this.commProp.dwMaxBaud }));
         }
         this.comStat = new Microsoft.Win32.UnsafeNativeMethods.COMSTAT();
         this.dcb = new Microsoft.Win32.UnsafeNativeMethods.DCB();
         this.InitializeDCB(baudRate, parity, dataBits, stopBits, discardNull);
         this.DtrEnable = dtrEnable;
         this.rtsEnable = this.GetDcbFlag(12) == 1;
         if ((handshake != System.IO.Ports.Handshake.RequestToSend) && (handshake != System.IO.Ports.Handshake.RequestToSendXOnXOff))
         {
             this.RtsEnable = rtsEnable;
         }
         if (readTimeout == 0)
         {
             this.commTimeouts.ReadTotalTimeoutConstant = 0;
             this.commTimeouts.ReadTotalTimeoutMultiplier = 0;
             this.commTimeouts.ReadIntervalTimeout = -1;
         }
         else if (readTimeout == -1)
         {
             this.commTimeouts.ReadTotalTimeoutConstant = -2;
             this.commTimeouts.ReadTotalTimeoutMultiplier = -1;
             this.commTimeouts.ReadIntervalTimeout = -1;
         }
         else
         {
             this.commTimeouts.ReadTotalTimeoutConstant = readTimeout;
             this.commTimeouts.ReadTotalTimeoutMultiplier = -1;
             this.commTimeouts.ReadIntervalTimeout = -1;
         }
         this.commTimeouts.WriteTotalTimeoutMultiplier = 0;
         this.commTimeouts.WriteTotalTimeoutConstant = (writeTimeout == -1) ? 0 : writeTimeout;
         if (!Microsoft.Win32.UnsafeNativeMethods.SetCommTimeouts(this._handle, ref this.commTimeouts))
         {
             InternalResources.WinIOError();
         }
         if (this.isAsync && !ThreadPool.BindHandle(this._handle))
         {
             throw new IOException(SR.GetString("IO_BindHandleFailed"));
         }
         Microsoft.Win32.UnsafeNativeMethods.SetCommMask(this._handle, 0x1fb);
         this.eventRunner = new EventLoopRunner(this);
         new Thread(new ThreadStart(this.eventRunner.WaitForCommEvent)) { IsBackground = true }.Start();
     }
     catch
     {
         hFile.Close();
         this._handle = null;
         throw;
     }
 }
 public void Open(string portName, int baudRate, System.IO.Ports.Parity portParity, int portDataBits, System.IO.Ports.StopBits portStopBits, System.IO.Ports.Handshake portHandshake, int timeOut, Encoding dataEncoding)
 {
     Open(portName, baudRate);
 }