Justinio's VB.NET version! (Serial operation)

xiaoxiao2021-03-06  17

Imports Systemimports System.Runtime.InteropServices

Namespace JustinIO Class CommPort Public PortNum As String Public BaudRate As Integer Public ByteSize As Byte Public Parity As Byte '// 0-4 = no, odd, even, mark, space Public StopBits As Byte' // 0,1,2 = 1 , 1.5, 2 Public ReadTimeout As Integer '// comm port win32 file handle Private hComm As Integer = -1 Public Opened As Boolean = False' // win32 api constants Private Const GENERIC_READ As Int64 = & H80000000 Private Const GENERIC_WRITE As Int64 = & H40000000 Private Const open_existing asset = 3 private const invalid_handle_value as integer = -1

#Region "Struct"

_ Public Structure DCB '// taken from c struct in platform sdk Public DCBlength As Integer' // sizeof (DCB) Public BaudRate As Integer '// current baud rate specified current baud rate' / / The are the c struct bit fields, bit twis integer '// Specifies whether binary mode is allowed, in Windows 95 must be the primary true binary mode, no EOF check public fparity as integer' // Specify whether to allow parity Check Enable Parity Checking Public FoutxctSflow AS Integer '// Specify whether the CTS is used to detect transmission control, and the transmission will be suspended when TRUE is CTS. CTS output flow control Public fOutxDsrFlow As Integer '// Specify CTS for detecting whether the transmission control DSR output flow control Public fDtrControl As Integer' // DTR_CONTROL_DISABLE DTR is set to the value OFF, DTR_CONTROL_ENABLE DTR value set ON, DTR_CONTROL_HANDSHAKE allow DTR " Handshake "DTR Flow Control Type Public FDSRSITIIVITY AS INTEGER '// When this value is True, the byte received when the DSR is OFF is ignored DSR Sensitivity Public ftxContinueonxoff as integer' // specifies that the receiving buffer is full, and the driver has Whether the transmission is sent when sending an Xoffchar character. When True, the transmitted buffer receives the byte Xofflim that is full of the buffer, and the driver has sent the XoffChar character aborted byte, the transmission continues. When FALSE, the transmitted buffer receives the byte xonchar that represents the buffer has empty and the driver has sent the Xonchar that has been resumed.

When Xoff Continues TX Public Foutx As INTEGER '// True, the received buffer receives the representative buffer when the XON / XOFF OUT FLOW Control public finx as integer' // true is stopped after receiving XOONCHAR. After the Xofflim of the zone, XOFCCHAR sends out the reception buffer to receive Xonlim that represents the empty space, XONCHAR sends out the XON / XOFF IN FLOW Control public ferrorchar as integer '// This value is TRUE and fparity is True, using ErrorChar Members Specify the Character Enable Error Replacement Public Fnull As INTEGER '// ETRUE in the parity error error, receive the empty (0 value) byte Enable Null Stripping Public Flow Control AS INTEGER' // RTS Flow Control '/ * RTS_CONTROL_DISABLE, RTS is set to OFF '* RTS_CONTROL_ENABLE, when RTS is set to ON' * RTS_CONTROL_HANDSHAKE, '* When the receiving buffer is less than half full, RTS is ON' * When the receive buffer exceeds more than four-quarters of RTS When Off '* RTS_CONTROL_TOGGLE,' * When the remaining byte remains in the receiving buffer, RTS is ON, otherwise, when the default is OFF * / PUBLIC FABORTONERROR AS INTEGER '// True, there is an error to inter-read and write Operation ABORT ON ERROR PUBLIC FDUMMY2 AS INTEGER '// Not Used Reserved Public Flags AS INT64 PUBLIC WRESERVED AS UINT16' // Not Used, must be 0 NOT CURRENTLY USED PUBLIC XONLIM AS uint16 '// Specify the front reception buffer in XON characters The minimum byte of the area in the area Transmit Xon Threshold Public Xofflim as uint16 '// Specifies that the minimum byte number of allowable minimum bytes in this pre-receiving buffer transmit Xoff threshold public Bytesize as byte' // Specify port current Data Bit Number Of Bits / Byte, 4-8 Public Parity As Byte '// Specifies the parity method for the currently used in the port, which may be: EVENPARITY, MarkParity, Noparity, Oddparity 0-4 =

NO, ODD, EVEN, MARK, SPACE PUBLIC STOPBITS AS BYTE '/ / Specifies the number of stop bits currently used by ports, may be: onestopbit, one5stopbits, twostopbits 0, 1, 2 = 1, 1.5, 2 public xonchar as char' / / Specifies the value of the value TX and RX XON Character public Xoffchar as char 'to send and receive characters xon specified to send and receive character xoff values ​​Tx and rx xoff character public errorchar as char' // this character is used instead of reception When the parity error occurred, the value of Error Replacement Character Public Error AS Char '// This character can be used to indicate the end of the data end of the data to indicate the end of infut character public evtchar as char' //. when the character, generates an event received event character Public wReserved1 As UInt16 '// unused reserved; do not use End Structure _ Private Structure COMMTIMEOUTS Public ReadIntervalTimeout As Integer Public ReadTotalTimeoutMultiplier As Integer Public ReadTotalTimeoutConstant As Integer Public WriteTotal TimeoutMultiplier As Integer Public WriteTotalTimeoutConstant As Integer End Structure _ Private Structure OVERLAPPED Public Internal As Integer Public InternalHigh As Integer Public Offset As Integer Public OffsetHigh As Integer Public hEvent As Integer End Structure # End Region

#Region "Windows API" _ Private Shared Function CreateFile (_ ByVal lpFileName As String, _ ByVal dwDesiredAccess As UInt32, _ ByVal dwShareMode As Integer, _ ByVal lpSecurityAttributes as Integer, _ ByVal dwCreationDisposition as Integer, _ ByVal dwFlagsAndAttributes as Integer, _ ByVal hTemplateFile as Integer) as Integer End Function 'parameters introduced:' lpFileName to open port name 'dwDesiredAccess serial access mode is specified, generally set to be readable Write the way 'dwsharemode specifies the shared mode of the serial port, the serial port cannot be shared, so set to 0' LPSecurityAttributes Set the security attributes of the serial port, Win9X is not supported, should be set to NULL 'DWCREATIONDisPosition For serial communication, the creation can only specify Open_EXISTING' DWFLAGSANDATTRIBUTES Serial port attribute and flag, set to file_flag_overlapped, specifying the serial port to communicate in asynchronous mode to Null _ private shared function getcommstate (Byval Hfile AS) Integer, byref lpdc B AS DCB) AS Boolean End Function 'Parameter Description' HFILE Communication Equipment Handle 'DCB LPDCB Device Control Block DCB

_ Private Shared Function BuildCommDCB (ByVal lpDef As String, ByRef lpDCB As DCB) As Boolean End Function 'parameters introduced' lpDef device control character string 'lpDCB device control block DCB _ private shared function setcommstate (ByVal Hfile As INTEGER, BYREF LPDCB AS DCB) AS Boolean End Function 'Parameter Description' HFile Communication Equipment Handle 'LPDCB Device Control Block _ Private Shared Function GetCommTimeouts (ByVal hfile As Integer, ByRef lpCommTimeouts As COMMTIMEOUTS) As Boolean End Function 'parameter' hFile communication device handles handle to comm device 'lpCommTimeouts timeout time-out values ​​ _ Private Shared Function SetCommTimeouts (ByVal hfile As Integer, ByRef lpCommTimeouts As COMMTIMEOUTS) As Boolean End Function 'parameter' hFile communication device handles handle to comm device 'lpCommTimeouts timeout time-out values ​​ _ Private Shared Function ReadFile (ByVal hFile As Integer, ByVal lpBuffer () As Byte, _ ByVal nNumberOfBytesToRead As Integer, ByRef lpNumberOfBytesRead As Integer, _ ByRef lpOverlapped As OVERLAPPED) As Boolean End Function 'Parameter' hFile communication device handle handle to file 'lpBuffer data buffer data buffer' waiting to read how many bytes nNumberOfBytesToRead number of bytes to read 'how many bytes read number lpNumberOfBytesRead of bytes read' lpOverlapped buffer overflow overlapped buffer

_ Private Shared Function WriteFile (ByVal hFile As Integer, ByVal lpBuffer () As Byte, _ ByVal nNumberOfBytesToRead As Integer, ByRef lpNumberOfBytesWritten As Integer, _ ByRef lpOverlapped As OVERLAPPED) As Boolean End Function 'parameters introduced' hFile communication device handles handle to file how many bytes 'lpBuffer data buffer data buffer' nNumberOfBytesToWrite waiting write number of bytes to write 'lpNumberOfBytesWritten number of bytes already written number of bytes written' lpOverlapped buffer overflow overlapped buffer _ Private Shared Function CloseHandle (ByVal hObject As Integer) As Boolean End Function 'hObject parameters to be closed handle handle to object _ Private Shared Function GetLastError () As UInt32 End Function # End Region Public Sub open () DCBCOMMPORT AS New DCB DIM CTOCOMMPORT AS New Commtimeouts' // Open Serial Open The Comm Port. Hcomm = cretefile (POR tNum, UInt32.Parse (GENERIC_READ Or GENERIC_WRITE), 0, 0, OPEN_EXISTING, 0, 0) '// If the serial port is not open, open IF THE PORT CAN NOT BE OPENED, BAIL OUT. If hComm = INVALID_HANDLE_VALUE Then Throw (New ApplicationException ("Illegal operation, can not open the serial port! ")) End If '// set the communication timeout SET THE COMM TIMEOUTS. GetCommTimeouts (hComm, ctoCommPort)' ref ctoCommPort.ReadTotalTimeoutConstant = ReadTimeout ctoCommPort.ReadTotalTimeoutMultiplier = 0 ctoCommPort.WriteTotalTimeoutMultiplier = 0 ctoCommPort.WriteTotalTimeoutConstant =

0 SetCommTimeouts (hComm, ctoCommPort) 'ref' // set the serial SET BAUD RATE, PARITY, WORD SIZE, AND STOP BITS. GetCommState (hComm, dcbCommPort) 'ref dcbCommPort.BaudRate = BaudRate dcbCommPort.flags = 0' // dcb. fBinary = 1; dcbCommPort.flags = dcbCommPort.flags Or (1) If Parity> 0 Then '//dcb.fParity=1 dcbCommPort.flags = dcbCommPort.flags Or (2) End If dcbCommPort.Parity = Parity dcbCommPort.ByteSize = ByteSize dcbCommPort.StopBits = StopBits If SetCommState (hComm, dcbCommPort) = False Then '// uint ErrorNum = GetLastError (); Throw (New ApplicationException ( "! illegal operation, can not open the serial port")) End If' // unremark to see IF setting took correctly '// DCB DCBCOMMPORT2 = New DCB ();' // getcommstate (hcomm, ref dcbcommport2); Opened = true end sub public SUB C lose () If hComm <> INVALID_HANDLE_VALUE Then CloseHandle (hComm) End If End Sub Public Function Read (ByVal NumBytes As Integer) As Byte () Dim BufBytes (NumBytes) As Byte Dim OutBytes (0) As Byte If (hComm <> INVALID_HANDLE_VALUE ) Then Dim ovlCommPort As New OVERLAPPED Dim BytesRead As Integer = 0 ReadFile (hComm, BufBytes, NumBytes, BytesRead, ovlCommPort) Array.Copy (BufBytes, OutBytes, BytesRead) Else Throw (New ApplicationException ( "

The serial port is not open! ")) End If Return OutBytes End FunctionPublic Sub Write (ByVal WriteBytes As Byte ()) If (hComm <> INVALID_HANDLE_VALUE) Then Dim ovlCommPort As New OVERLAPPED Dim BytesWritten As Integer WriteFile (hComm, WriteBytes, WriteBytes.Length, BytesWritten, ovlCommPort) Else Throw ("Serial Port Unmopted!")) End if End Sub End Classend Namespace

转载请注明原文地址:https://www.9cbs.com/read-41745.html

New Post(0)