The vb. NET version of JustinIO! (Serial operation)

Source: Internet
Author: User

Imports System
Imports System. Runtime. InteropServices

Namespace JustinIO
Class commp ORT
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 as integer = 3
Private const invalid_handle_value as integer =-1

# Region "struct"

<Structlayout (layoutkind. Sequential)> _
Public structure DCB
'// Taken from C struct in Platform SDK
Public dcblength as integer '// sizeof (DCB)
Public baudrate as integer '// specifies the current baud rate of the current baud rate
'// These are the C struct bit fields, bit twiddle flag to set
Public fbinary as integer '// specifies whether the binary mode is allowed. in Windows95, the primary value must be true binary mode, no EOF check.
Public fparity as integer '// specifies whether the parity check enable parity checking is allowed
Public fOutxCtsFlow As Integer '// specifies whether the CTS is used to detect sending control. If the value TRUE indicates that the CTS is OFF, the sending will be suspended. CTS output flow control
Public fOutxDsrFlow As Integer '// specifies whether the CTS is used to detect the transmission control DSR output flow control
Public fDtrControl As Integer '// The DTR_CONTROL_DISABLE Value Sets DTR to OFF, and the DTR_CONTROL_ENABLE Value Sets DTR to ON. DTR_CONTROL_HANDSHAKE allows DTR "handshake" DTR flow control type
Public fdsrsensiti1_as Integer '// when the value is TRUE, the byte received when the DSR is OFF is ignored by the DSR sensiti1 _
Public fTXContinueOnXoff As Integer '// specifies whether to stop sending when the receiving buffer is full and the driver has sent XoffChar characters. TRUE: when the receiving buffer receives the byte XoffLim that is full in the buffer and the driver has sent the XoffChar character to abort the receiving byte, the sending continues. If this parameter is set to FALSE, the receiving buffer receives the byte XonChar that indicates that the buffer is empty and the driver sends the XonChar to resume sending. XOFF continues Tx
Public fOutX As Integer '// TRUE, after receiving XoffChar, stop sending and receiving XonChar, and re-start XON/XOFF out flow control
Public fInX As Integer '// TRUE: After the receiving buffer receives XoffLim, which indicates that the buffer is full, XoffChar sends the received buffer to the XonLim that indicates that the buffer is empty, xonChar sent out XON/XOFF in flow control
Public fErrorChar As Integer '// when this value is TRUE and fParity is TRUE, use the character specified by the ErrorChar member to replace the receiving character enable error replacement of the parity error.
Public fNull As Integer '// when eTRUE is received, remove the null (0 value) byte enable null stripping
Public fRtsControl As Integer '// RTS flow control
'/* RTS_CONTROL_DISABLE
'* When RTS_CONTROL_ENABLE is enabled
'* RTS_CONTROL_HANDSHAKE,
'* When the receiving buffer is less than half full, the RTS is ON
'* When the receiving buffer exceeds 3/4 full, the RTS is OFF.
'* RTS_CONTROL_TOGGLE,
'* When the receiving buffer still has the remaining bytes, the RTS is ON. Otherwise, the default value is OFF */
Public fAbortOnError As Integer '// TRUE
Public fDummy2 As Integer '// reserved is not used
Public flags As Int64
Public wReserved As uint16' // not used, must be 0 not currently used
Public XonLim As uint16' // specifies the minimum number of bytes allowed in the receiving buffer before the XON character is sent. transmit XON threshold
Public XoffLim As uint16' // specifies the minimum number of bytes allowed in the receiving buffer before XOFF is sent. transmit XOFF threshold
Public ByteSize As Byte // number of bits/byte, 4-8 currently used by the specified port
Public Parity As Byte '// The Parity method currently used by the specified port, which may be: EVENPARITY, MARKPARITY, NOPARITY, ODDPARITY 0-4 = no, odd, even, mark, space
Public StopBits As Byte // The number of currently used StopBits on the specified port, which may be ONESTOPBIT, ONE5STOPBITS, TWOSTOPBITS 0, 1, 2 = 1, 1.5, 2
Public XonChar As Char '// specifies the Tx and Rx XON character value used to send and receive the XON character
Public xoffchar as char '// specifies the xoff value for sending and receiving characters Tx and Rx xoff character
Public errorchar as char '// this character is used to replace the value of error replacement character when an error occurs in the received parity.
Public eofchar as char '// when the binary mode is not used, this character can be used to indicate the end of the Data end of input character
Public evtchar as char '// when this character is received, an event named Ed event character is generated.
Public wReserved1 As uint16' // reserved is not used; do not use
End Structure
<StructLayout (LayoutKind. Sequential)> _
Private Structure COMMTIMEOUTS
Public ReadIntervalTimeout As Integer
Public ReadTotalTimeoutMultiplier As Integer
Public ReadTotalTimeoutConstant As Integer
Public WriteTotalTimeoutMultiplier As Integer
Public writetotaltimeoutconstant as integer
End Structure
<Structlayout (layoutkind. Sequential)> _
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"
<DllImport ("kernel32.dll", CharSet: = CharSet. Auto)> _
Private Shared Function CreateFile (_
ByVal lpFileName As String ,_
ByVal dwDesiredAccess As UInt32 ,_
ByVal dw1_mode As Integer ,_
ByVal lpSecurityAttributes As Integer ,_
Byval dwcreationdisposition as integer ,_
Byval dwflagsandattributes as integer ,_
Byval htemplatefile as integer) as integer
End Function
'Parameter introduction:
'Lpfilename: name of the serial port to be opened
'Dwdesiredaccess specifies the serial port access mode, which is generally set to readable and writable.
'Dw1_mode specifies the serial port sharing mode. The serial port cannot be shared, so it is set to 0.
'Lpsecurityattributes: Set the Security Attribute of the serial port. This parameter is not supported in Win9x and should be set to null.
'Dwcreationdisposition: for serial communication, the creation method can only be OPEN_EXISTING
'Dwflagsandattributes: Specifies the serial port attribute and flag, and sets it to FILE_FLAG_OVERLAPPED (overlapping I/O operations). specifies the serial port to communicate asynchronously.
'Htemplatefile must be set to NULL for Serial Communication
<DllImport ("kernel32.dll")> _
Private Shared Function GetCommState (ByVal hFile As Integer, ByRef lpDCB As DCB) As Boolean
End Function
'Parameter Introduction
'Hfile communication device handle
'Dcb lpDCB Device Control Block DCB

<DllImport ("kernel32.dll")> _
Private Shared Function BuildCommDCB (ByVal lpDef As String, ByRef lpDCB As DCB) As Boolean
End Function
'Parameter Introduction
'Lpdef Device Control string
'Lpdcb Device Control Block DCB
<DllImport ("kernel32.dll")> _
Private Shared Function SetCommState (ByVal hfile As Integer, ByRef lpDCB As DCB) As Boolean
End Function
'Parameter description
'Hfile communication device handle
'Lpdcb Device Control Block
<DllImport ("kernel32.dll")> _
Private Shared Function GetCommTimeouts (ByVal hfile As Integer, ByRef lpCommTimeouts As COMMTIMEOUTS) As Boolean
End Function
'Parameter description
'Hfile communication device handle to comm device
'Lpcommtimeouts timeout time-out values
<DllImport ("kernel32.dll")> _
Private Shared Function SetCommTimeouts (ByVal hfile As Integer, ByRef lpCommTimeouts As COMMTIMEOUTS) As Boolean
End Function
'Parameter description
'Hfile communication device handle to comm device
'Lpcommtimeouts timeout time-out values
<Dllimport ("kernel32.dll")> _
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 description
'Hfile communication device handle to file
'Lpbuffer Data Buffer
How many bytes does 'nnumberofbytestoread wait to read number of bytes to read
'Maximum number of bytes read by lpNumberOfBytesRead
'Lpoverlapped overflow buffer overlapped buffer
<DllImport ("kernel32.dll")> _
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
'Parameter Introduction
'Hfile communication device handle to file
'Lpbuffer Data Buffer
'Nnumberofbytestowrite how many bytes are waiting to be written to number of bytes to write
'Maximum number of bytes written by lpnumberofbyteswritten
'Lpoverlapped overflow buffer overlapped Buffer
<Dllimport ("kernel32.dll")> _
Private shared function closehandle (byval hobject as integer) as Boolean
End Function
'The hobject handle to be closed handle to object
<Dllimport ("kernel32.dll")> _
Private Shared Function GetLastError () As UInt32
End Function
# End Region
Public Sub open ()
Dim dcbcommp ort As New DCB
Dim ctocommp ort As New COMMTIMEOUTS
'// Open the comm port.
HComm = CreateFile (PortNum, UInt32.Parse (GENERIC_READ Or GENERIC_WRITE), 0, 0, OPEN_EXISTING, 0, 0)
'// If the serial PORT is not enabled, open if the port cannot be opened, bail out.
If hComm = INVALID_HANDLE_VALUE Then
Throw (New ApplicationException ("illegal operation, cannot open the serial port! "))
End If
'// Set the communication timeout value set the comm timeouts.
GetCommTimeouts (hComm, ctocommp ORT) 'ref
Ctocommp ORT. ReadTotalTimeoutConstant = ReadTimeout
Ctocommp ORT. ReadTotalTimeoutMultiplier = 0
Ctocommp ORT. WriteTotalTimeoutMultiplier = 0
Ctocommp ORT. WriteTotalTimeoutConstant = 0
SetCommTimeouts (hComm, ctocommp ORT) 'ref
'// SET the serial port set baud rate, PARITY, word size, and stop bits.
GetCommState (hComm, dcbcommp ORT) 'ref
Dcbcomatrix. BaudRate = BaudRate
Dcbcommp ORT. flags = 0
'// Dcb. fBinary = 1;
Dcbcomatrix. flags = dcbcomatrix. flags Or (1)
If Parity> 0 Then
'// Dcb. fParity = 1
Dcbcomatrix. flags = dcbcomatrix. flags Or (2)
End If
Dcbcommp ORT. Parity = Parity
Dcbcommp ORT. ByteSize = ByteSize
Dcbcommp ORT. StopBits = StopBits
If SetCommState (hComm, dcbcommp ORT) = False Then
'// Uint ErrorNum = GetLastError ();
Throw (New ApplicationException ("illegal operation, cannot open the serial port! "))
End If
'// Unremark to see if setting took correctly
'// DCB dcbcomatrix ort2 = new DCB ();
'// GetCommState (hComm, ref dcbcommp ort2 );
Opened = True
End Sub
Public Sub Close ()
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 ovlcommp ort As New OVERLAPPED
Dim BytesRead As Integer = 0
ReadFile (hComm, BufBytes, NumBytes, BytesRead, ovlcommp ORT)
Array. Copy (BufBytes, OutBytes, BytesRead)
Else
Throw (New ApplicationException ("the serial port is not enabled! "))
End If
Return OutBytes
End Function

Public Sub Write (ByVal WriteBytes As Byte ())
If (hComm <> INVALID_HANDLE_VALUE) Then
Dim ovlcommp ort As New OVERLAPPED
Dim BytesWritten As Integer
WriteFile (hComm, WriteBytes, WriteBytes. Length, BytesWritten, ovlcommp ORT)
Else
Throw (New applicationexception ("the serial port is not enabled! "))
End if
End sub
End Class
End namespace

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.