📄 crs232.vb
字号:
Imports System.Runtime.InteropServices
Imports System.Text
Imports System.Threading
#Region "RS232"
Public Class Rs232
'===================================================
' ?002 Corrado Cavalli All rights reserved
'
' Module : Rs232
' Description : Class for handling RS232 comunication with VB.Net
' Created : 10/08/2001 - 8:45:25
' Author : Corrado Cavalli
'
' Notes :
'-----------------------------------------------------------------------------------------------
' Revisions
' Rev.1 (28.02.2002)
' 1. Added ResetDev, SetBreak and ClearBreak to the EscapeCommFunction constants
' 2. Added the overloaded Open routine.
' 3. Added the modem status routines, properties and enum.
' 4. If a read times out, it now returns a EndOfStreamException (instead of a simple Exception).
'
' Above modification suggested by:
' Richard J. Kucia
' Kucia Associates
' rjkucia@worldnet.att.net
' Rev.2 (01.02.2002)
' Added Async support
'===================================================
'// Class Members
Private mhRS As Int32 = -1 '// Handle to Com Port
Private miPort As Integer = 1 '// Default is COM1
Private miTimeout As Int32 = 70 '// Timeout in ms
Private miBaudRate As Int32 = 9600
Private meParity As DataParity = 0
Private meStopBit As DataStopBit = 0
Private miDataBit As Int32 = 8
Private miBufferSize As Int32 = 512 '// Buffers size default to 512 bytes
Private mabtRxBuf As Byte() '// Receive buffer
Private meMode As Mode '// Class working mode
Private mbWaitOnRead As Boolean
Private mbWaitOnWrite As Boolean
Private mbWriteErr As Boolean
Private muOverlapped As OVERLAPPED
Private muOverlappedW As OVERLAPPED
Private muOverlappedE As OVERLAPPED
Private mabtTmpTxBuf As Byte() '// Temporary buffer used by Async Tx
Private moThreadTx As Thread
Private moThreadRx As Thread
Private miTmpBytes2Read As Int32
Private meMask As EventMasks
'----------------------------------------------------------------------------------------
#Region "Enums"
'// Parity Data
Public Enum DataParity
Parity_None = 0
Pariti_Odd
Parity_Even
Parity_Mark
End Enum
'// StopBit Data
Public Enum DataStopBit
StopBit_1 = 1
StopBit_2
End Enum
Private Enum PurgeBuffers
RXAbort = &H2
RXClear = &H8
TxAbort = &H1
TxClear = &H4
End Enum
Private Enum Lines
SetRts = 3
ClearRts = 4
SetDtr = 5
ClearDtr = 6
ResetDev = 7 ' // Reset device if possible
SetBreak = 8 ' // Set the device break line.
ClearBreak = 9 ' // Clear the device break line.
End Enum
'// Modem Status
<Flags()> Public Enum ModemStatusBits
ClearToSendOn = &H10
DataSetReadyOn = &H20
RingIndicatorOn = &H40
CarrierDetect = &H80
End Enum
'// Working mode
Public Enum Mode
NonOverlapped
Overlapped
End Enum
'// Comm Masks
<Flags()> Public Enum EventMasks
RxChar = &H1
RXFlag = &H2
TxBufferEmpty = &H4
ClearToSend = &H8
DataSetReady = &H10
ReceiveLine = &H20
Break = &H40
StatusError = &H80
Ring = &H100
End Enum
#End Region
#Region "Structures"
<StructLayout(LayoutKind.Sequential, Pack:=1)> Private Structure DCB
Private DCBlength As Int32
Private BaudRate As Int32
Private Bits1 As Int32
Private wReserved As Int16
Private XonLim As Int16
Private XoffLim As Int16
Private ByteSize As Byte
Private Parity As Byte
Private StopBits As Byte
Private XonChar As Byte
Private XoffChar As Byte
Private ErrorChar As Byte
Private EofChar As Byte
Private EvtChar As Byte
Private wReserved2 As Int16
End Structure
<StructLayout(LayoutKind.Sequential, Pack:=1)> Private Structure COMMTIMEOUTS
Public ReadIntervalTimeout As Int32
Public ReadTotalTimeoutMultiplier As Int32
Public ReadTotalTimeoutConstant As Int32
Public WriteTotalTimeoutMultiplier As Int32
Public WriteTotalTimeoutConstant As Int32
End Structure
<StructLayout(LayoutKind.Sequential, Pack:=1)> Private Structure COMMCONFIG
Private dwSize As Int32
Private wVersion As Int16
Private wReserved As Int16
Private dcbx As DCB
Private dwProviderSubType As Int32
Private dwProviderOffset As Int32
Private dwProviderSize As Int32
Private wcProviderData As Byte
End Structure
<StructLayout(LayoutKind.Sequential, Pack:=1)> Public Structure OVERLAPPED
Public Internal As Int32
Public InternalHigh As Int32
Public Offset As Int32
Public OffsetHigh As Int32
Public hEvent As Int32
End Structure
#End Region
#Region "Constants"
Private Const PURGE_RXABORT As Integer = &H2
Private Const PURGE_RXCLEAR As Integer = &H8
Private Const PURGE_TXABORT As Integer = &H1
Private Const PURGE_TXCLEAR As Integer = &H4
Private Const GENERIC_READ As Integer = &H80000000
Private Const GENERIC_WRITE As Integer = &H40000000
Private Const OPEN_EXISTING As Integer = 3
Private Const INVALID_HANDLE_VALUE As Integer = -1
Private Const IO_BUFFER_SIZE As Integer = 1024
Private Const FILE_FLAG_OVERLAPPED As Int32 = &H40000000
Private Const ERROR_IO_PENDING As Int32 = 997
Private Const WAIT_OBJECT_0 As Int32 = 0
Private Const ERROR_IO_INCOMPLETE As Int32 = 996
Private Const WAIT_TIMEOUT As Int32 = &H102&
Private Const INFINITE As Int32 = &HFFFFFFFF
#End Region
#Region "Win32API"
'// Win32 API
<DllImport("kernel32.dll")> Private Shared Function SetCommState(ByVal hCommDev As Int32, ByRef lpDCB As DCB) As Int32
End Function
<DllImport("kernel32.dll")> Private Shared Function GetCommState(ByVal hCommDev As Int32, ByRef lpDCB As DCB) As Int32
End Function
<DllImport("kernel32.dll", CharSet:=CharSet.Auto)> Private Shared Function BuildCommDCB(<MarshalAs(UnmanagedType.LPStr)> ByVal lpDef As String, ByRef lpDCB As DCB) As Int32
End Function
<DllImport("kernel32.dll")> Private Shared Function SetupComm(ByVal hFile As Int32, ByVal dwInQueue As Int32, ByVal dwOutQueue As Int32) As Int32
End Function
<DllImport("kernel32.dll")> Private Shared Function SetCommTimeouts(ByVal hFile As Int32, ByRef lpCommTimeouts As COMMTIMEOUTS) As Int32
End Function
<DllImport("kernel32.dll")> Private Shared Function GetCommTimeouts(ByVal hFile As Int32, ByRef lpCommTimeouts As COMMTIMEOUTS) As Int32
End Function
<DllImport("kernel32.dll")> Private Shared Function ClearCommError(ByVal hFile As Int32, ByVal lpErrors As Int32, ByVal l As Int32) As Int32
End Function
<DllImport("kernel32.dll")> Private Shared Function PurgeComm(ByVal hFile As Int32, ByVal dwFlags As Int32) As Int32
End Function
<DllImport("kernel32.dll")> Private Shared Function EscapeCommFunction(ByVal hFile As Integer, ByVal ifunc As Long) As Boolean
End Function
<DllImport("kernel32.dll")> Private Shared Function WaitCommEvent(ByVal hFile As Integer, ByRef Mask As EventMasks, ByRef lpOverlap As OVERLAPPED) As Int32
End Function
<DllImport("kernel32.dll")> Private Shared Function WriteFile(ByVal hFile As Integer, ByVal Buffer As Byte(), ByVal nNumberOfBytesToWrite As Integer, ByRef lpNumberOfBytesWritten As Integer, ByRef lpOverlapped As OVERLAPPED) As Integer
End Function
<DllImport("kernel32.dll")> Private Shared Function ReadFile(ByVal hFile As Integer, ByVal Buffer As Byte(), ByVal nNumberOfBytesToRead As Integer, ByRef lpNumberOfBytesRead As Integer, ByRef lpOverlapped As OVERLAPPED) As Integer
End Function
<DllImport("kernel32.dll")> Private Shared Function CreateFile(<MarshalAs(UnmanagedType.LPStr)> ByVal lpFileName As String, ByVal dwDesiredAccess As Integer, ByVal dwShareMode As Integer, ByVal lpSecurityAttributes As Integer, ByVal dwCreationDisposition As Integer, ByVal dwFlagsAndAttributes As Integer, ByVal hTemplateFile As Integer) As Integer
End Function
<DllImport("kernel32.dll")> Private Shared Function CloseHandle(ByVal hObject As Integer) As Integer
End Function
<DllImport("kernel32.dll")> Private Shared Function FormatMessage(ByVal dwFlags As Integer, ByVal lpSource As Integer, ByVal dwMessageId As Integer, ByVal dwLanguageId As Integer, <MarshalAs(UnmanagedType.LPStr)> ByVal lpBuffer As String, ByVal nSize As Integer, ByVal Arguments As Integer) As Integer
End Function
<DllImport("kernel32.dll")> Public Shared Function GetCommModemStatus(ByVal hFile As Int32, ByRef lpModemStatus As Int32) As Boolean
End Function
<DllImport("kernel32.dll")> Private Shared Function CreateEvent(ByVal lpEventAttributes As Int32, ByVal bManualReset As Int32, ByVal bInitialState As Int32, <MarshalAs(UnmanagedType.LPStr)> ByVal lpName As String) As Int32
End Function
<DllImport("kernel32.dll")> Private Shared Function GetLastError() As Int32
End Function
<DllImport("kernel32.dll")> Private Shared Function WaitForSingleObject(ByVal hHandle As Int32, ByVal dwMilliseconds As Int32) As Int32
End Function
<DllImport("kernel32.dll")> Private Shared Function GetOverlappedResult(ByVal hFile As Int32, ByRef lpOverlapped As OVERLAPPED, ByRef lpNumberOfBytesTransferred As Int32, ByVal bWait As Int32) As Int32
End Function
<DllImport("kernel32.dll")> Private Shared Function SetCommMask(ByVal hFile As Int32, ByVal lpEvtMask As Int32) As Int32
End Function
Private Declare Function FormatMessage Lib "kernel32" Alias _
"FormatMessageA" (ByVal dwFlags As Int32, ByVal lpSource As Int32, _
ByVal dwMessageId As Int32, ByVal dwLanguageId As Int32, _
ByVal lpBuffer As StringBuilder, ByVal nSize As Int32, ByVal Arguments As Int32) _
As Int32
#End Region
#Region "Events"
Public Event DataReceived(ByVal Source As Rs232, ByVal DataBuffer() As Byte)
Public Event TxCompleted(ByVal Source As Rs232)
Public Event CommEvent(ByVal Source As Rs232, ByVal Mask As EventMasks)
#End Region
Public Property Port() As Integer
'===================================================
' ?001 Corrado Cavalli All rights reserved
'
' Description: Comunication Port
' Created : 21/09/2001 - 11:25:49
' Author : Corrado Cavalli
'
' *Parameters Info*
'
' Notes :
'===================================================
Get
Return miPort
End Get
Set(ByVal Value As Integer)
miPort = Value
End Set
End Property
Public Overridable Property Timeout() As Integer
'===================================================
' ?001 Corrado Cavalli All rights reserved
'
' Description: Comunication timeout in seconds
' Created : 21/09/2001 - 11:26:50
' Author : Corrado Cavalli
'
' *Parameters Info*
'
' Notes :
'===================================================
Get
Return miTimeout
End Get
Set(ByVal Value As Integer)
miTimeout = CInt(IIf(Value = 0, 500, Value))
'// If Port is open updates it on the fly
pSetTimeout()
End Set
End Property
Public Property Parity() As DataParity
'===================================================
' ?001 Corrado Cavalli All rights reserved
'
' Description: Comunication parity
' Created : 21/09/2001 - 11:27:15
' Author : Corrado Cavalli
'
' *Parameters Info*
'
' Notes :
'===================================================
Get
Return meParity
End Get
Set(ByVal Value As DataParity)
meParity = Value
End Set
End Property
Public Property StopBit() As DataStopBit
'===================================================
' ?001 Corrado Cavalli All rights reserved
'
' Description: Comunication StopBit
' Created : 21/09/2001 - 11:27:37
' Author : Corrado Cavalli
'
' *Parameters Info*
'
' Notes :
'===================================================
Get
Return meStopBit
End Get
Set(ByVal Value As DataStopBit)
meStopBit = Value
End Set
End Property
Public Property BaudRate() As Integer
'===================================================
' ?001 Corrado Cavalli All rights reserved
'
' Description: Comunication BaudRate
' Created : 21/09/2001 - 11:28:00
' Author : Corrado Cavalli
'
' *Parameters Info*
'
' Notes :
'===================================================
Get
Return miBaudRate
End Get
Set(ByVal Value As Integer)
miBaudRate = Value
End Set
End Property
Public Property DataBit() As Integer
'===================================================
' ?001 Corrado Cavalli All rights reserved
'
' Description: Comunication DataBit
' Created : 21/09/2001 - 11:28:20
' Author : Corrado Cavalli
'
' *Parameters Info*
'
' Notes :
'===================================================
Get
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -