예제 #1
0
        private SerialPortFixer(string portName)
        {
            if (portName == null || !portName.StartsWith("COM", StringComparison.OrdinalIgnoreCase))
            {
                throw new ArgumentException("Invalid Serial Port", nameof(portName));
            }

            SafeFileHandle file = SerialPortFixer.CreateFile("\\\\.\\" + portName, -1073741824, 0, IntPtr.Zero, 3, 1073741824, IntPtr.Zero);

            if (file.IsInvalid)
            {
                SerialPortFixer.WinIoError();
            }

            try
            {
                switch (SerialPortFixer.GetFileType(file))
                {
                case 0:
                case 2:
                    m_Handle = file;
                    InitializeDcb();
                    break;

                default:
                    throw new ArgumentException("Invalid Serial Port", nameof(portName));
                }
            }
            catch
            {
                file.Close();
                m_Handle = null;
                throw;
            }
        }
예제 #2
0
        private static string GetMessage(int errorCode)
        {
            var lpBuffer = new StringBuilder(512);

            if (SerialPortFixer.FormatMessage(12800, new HandleRef(null, IntPtr.Zero), errorCode, 0, lpBuffer, lpBuffer.Capacity, IntPtr.Zero) != 0)
            {
                return(lpBuffer.ToString());
            }

            return("Unknown Error");
        }
예제 #3
0
        private void SetCommStateNative(ref SerialPortFixer.Dcb lpDcb)
        {
            var lpErrors = 0;
            var lpStat   = new SerialPortFixer.Comstat();

            for (var index = 0; index < 10; ++index)
            {
                if (!SerialPortFixer.ClearCommError(m_Handle, ref lpErrors, ref lpStat))
                {
                    SerialPortFixer.WinIoError();
                }

                if (SerialPortFixer.SetCommState(m_Handle, ref lpDcb))
                {
                    break;
                }

                if (index == 9)
                {
                    SerialPortFixer.WinIoError();
                }
            }
        }
예제 #4
0
        private static void WinIoError()
        {
            var lastWin32Error = Marshal.GetLastWin32Error();

            throw new IOException(SerialPortFixer.GetMessage(lastWin32Error), SerialPortFixer.MakeHrFromErrorCode(lastWin32Error));
        }