/// <summary>
 /// Constructor for a DCB, using the DCB provided by another object.
 /// </summary>
 /// <param name="handle">Valid handle to a serial port object.</param>
 /// <param name="state">A CommState object for which the DCB settings should be
 /// taken. Note, the handle managed by the state object is ignored. If this
 /// parameter is null, then a default DCB is created.</param>
 internal CommState(SafeFileHandle handle, CommState state)
 {
     m_ComPortHandle = handle;
     if (state == null)
     {
         m_Dcb.DCBLength = Marshal.SizeOf(m_Dcb);
         GetCommState();
     }
     else
     {
         m_Dcb = state.m_Dcb;
     }
 }
Esempio n. 2
0
        void UpdateSettings()
        {
            lock (_lock)
            {
                // This assumes the handle is acquired.
                if (!_settingsChanged)
                {
                    return;
                }
                _settingsChanged = false;

                var dcb = new NativeMethods.DCB();
                dcb.DCBlength = Marshal.SizeOf(typeof(NativeMethods.DCB));
                if (!NativeMethods.GetCommState(_handle, ref dcb))
                {
                    int hr = Marshal.GetHRForLastWin32Error();
                    throw DeviceException.CreateIOException(Device, "Failed to get serial state.", hr);
                }

                int baudRate = _ser.BaudRate;
                int dataBits = _ser.DataBits;
                var parity   = _ser.Parity;
                int stopBits = _ser.StopBits;

                SetDcbDefaults(ref dcb);
                dcb.BaudRate = checked ((uint)baudRate);
                dcb.ByteSize = checked ((byte)_ser.DataBits);
                dcb.Parity   = parity == SerialParity.Even ? NativeMethods.EVENPARITY : parity == SerialParity.Odd ? NativeMethods.ODDPARITY : NativeMethods.NOPARITY;
                dcb.StopBits = stopBits == 2 ? NativeMethods.TWOSTOPBITS : NativeMethods.ONESTOPBIT;
                if (!NativeMethods.SetCommState(_handle, ref dcb))
                {
                    int hr = Marshal.GetHRForLastWin32Error();
                    throw DeviceException.CreateIOException(Device, "Failed to set serial state.", hr);
                }

                var purgeFlags = NativeMethods.PURGE_RXABORT | NativeMethods.PURGE_RXCLEAR | NativeMethods.PURGE_TXABORT | NativeMethods.PURGE_TXCLEAR;
                if (!NativeMethods.PurgeComm(_handle, purgeFlags))
                {
                    int hr = Marshal.GetHRForLastWin32Error();
                    throw DeviceException.CreateIOException(Device, "Failed to purge serial port.", hr);
                }
            }
        }
Esempio n. 3
0
 static void SetDcbDefaults(ref NativeMethods.DCB dcb)
 {
     dcb.fFlags  = 0;
     dcb.fBinary = true;
 }