/// <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"); } } }
/// <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); } }
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); } }
private static void sendByte(byte b) { uint written = 0; Win32Com.WriteFile(HPort, new[] { b }, 1, out written, IntPtr.Zero); }
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); }