⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 crs232.vb

📁 vb.net 开发的WinCE下的串口通讯类
💻 VB
📖 第 1 页 / 共 4 页
字号:
#Region "导入命名空间"


Imports System.Runtime.InteropServices
Imports System.Text
Imports System.Threading
Imports System.ComponentModel
Imports System.IO
#End Region

#Region "RS232 类"
'===================================================
'
'		描述:		WinCE.net 串口通信 
'		创建:		2005-8-13 12:17
'
'		版本:      V1.0.0.1
'		类名:		Rs232
'						
'       作者 :     韩俊峰
'       公司:      重庆联康科技有限公司		:
'===================================================
Public Class Rs232 : Implements IDisposable

#Region "类Private 成员变量声明"


    '// Class Members		
    Private m_hcom As IntPtr = New IntPtr(0)      '// 打开串口句柄									
    Private miPort As Integer = 1024              '// 默认串口为  COM1	
    Private miTimeout As Int32 = 70               '// 默认超时为  70 ms   (1秒=1000ms)
    Private miBaudRate As Int32 = 57600           '// 默认 波特率 为 57600 HZ
    Private meParity As DataParity = 0            '// 默认数据校验 为0 即:没有数据校验
    Private meStopBit As DataStopBit = 0          '// 默认数据停止位 为 DataStopBit.StopBit_1  即:数据停止位 为1
    Private miDataBit As Int32 = 8                '// 默认数据位 为:8
    Private miBufferSize As Int32 = 512           '// 默认串口 输出缓冲区(writefile()) 输入缓冲区(readfile())  512 bytes  ,SetupComm(m_hcom, miBufferSize, miBufferSize)
    Private mabtRxBuf As Byte()                   '// 接收的或读取的 二进制数据数组 	Receive buffer,
    Private meMode As Mode                        '// 工作方式:不重叠操作(同步操作),重叠操作(异步操作)  Class working mode	 WinCE 中 ,CreateFile(,,,,0,0) 取 值 为 0,  其他 不能为 0,取 Nothing
    Private moThreadTx As Thread                  '// TX线程
    Private moThreadRx As Thread                  '// RX线程
    Private moEvents As Thread                    '// 读、写 事件线程
    Private miTmpBytes2Read As Int32
    Private meMask As EventMasks                  '// Com 信号状态标志 
    Private mbDisposed As Boolean                 '// 关闭或释放由实现此接口的类的实例保持的文件、流和句柄等非托管资源  的 状态标志
    Private mbUseXonXoff As Boolean               '// XON/XOFF 流控制 打开与关闭的标志
    Private mbEnableEvents As Boolean             '// 开辟 事件处理进程的标志
    Private miBufThreshold As Int32 = 1
    Private muOvlE As OVERLAPPED                  '// 读、写 串口 事务 操作方式:不重叠操作(同步操作),重叠操作(异步操作) WinCE 中取 Nothing 不能为 0
    Private muOvlW As OVERLAPPED                  '// 写  操作方式:不重叠操作(同步操作),重叠操作(异步操作) WinCE 中取 Nothing 不能为 0
    Private muOvlR As OVERLAPPED                  '// 读  操作方式:不重叠操作(同步操作),重叠操作(异步操作) WinCE 中取 Nothing 不能为 0
    Private mHE As GCHandle                       '// 读、写 串口 事务 句柄
    Private mHR As GCHandle                       '// 读请求事件句柄
    Private mHW As GCHandle                       '// 写请求事件句柄
    Private INVALID_HANDLE_VALUE As System.Int32 = -1 '//打不开com口的错误标志

    '----------------------------------------------------------------------------------------
#End Region

#Region "Const 常量定义"
    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          '//可读     m_hcom = CreateFile("COM" & miPort.ToString + ":", GENERIC_READ Or GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0)
    Private Const GENERIC_WRITE As Integer = &H40000000         '//可写     m_hcom = CreateFile("COM" & miPort.ToString + ":", GENERIC_READ Or GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0)
    Private Const OPEN_EXISTING As Integer = 3                  '//假定 串口存在,m_hcom = CreateFile("COM" & miPort.ToString + ":", GENERIC_READ Or GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0)
    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("coredll.dll", SetlastError:=True)> Private Shared Function SetCommState(ByVal hCommDev As IntPtr, ByRef lpDCB As DCB) As Int32
    End Function
    <DllImport("coredll.dll", SetlastError:=True)> Private Shared Function GetCommState(ByVal hCommDev As IntPtr, ByRef lpDCB As DCB) As Int32
    End Function
    <DllImport("coredll.dll", SetlastError:=True, CharSet:=CharSet.Auto)> Private Shared Function BuildCommDCB(ByVal lpDef As String, ByRef lpDCB As DCB) As Int32
    End Function
    <DllImport("coredll.dll", SetlastError:=True)> Private Shared Function SetupComm(ByVal hFile As IntPtr, ByVal dwInQueue As Int32, ByVal dwOutQueue As Int32) As Int32
    End Function
    <DllImport("coredll.dll", SetlastError:=True)> Private Shared Function SetCommTimeouts(ByVal hFile As IntPtr, ByRef lpCommTimeouts As COMMTIMEOUTS) As Int32
    End Function
    <DllImport("coredll.dll", SetlastError:=True)> Private Shared Function GetCommTimeouts(ByVal hFile As IntPtr, ByRef lpCommTimeouts As COMMTIMEOUTS) As Int32
    End Function
    <DllImport("coredll.dll", SetlastError:=True)> Private Shared Function ClearCommError(ByVal hFile As IntPtr, ByRef lpErrors As Int32, ByRef lpComStat As COMSTAT) As Int32
    End Function
    <DllImport("coredll.dll", SetlastError:=True)> Private Shared Function PurgeComm(ByVal hFile As IntPtr, ByVal dwFlags As Int32) As Int32
    End Function
    <DllImport("coredll.dll", SetlastError:=True)> Private Shared Function EscapeCommFunction(ByVal hFile As IntPtr, ByVal ifunc As Int32) As Boolean
    End Function
    <DllImport("coredll.dll", SetlastError:=True)> Private Shared Function WaitCommEvent(ByVal hFile As IntPtr, ByRef Mask As EventMasks, ByRef lpOverlap As OVERLAPPED) As Int32
    End Function
    <DllImport("coredll.dll", SetlastError:=True)> Private Shared Function WriteFile(ByVal hFile As IntPtr, ByVal Buffer As Byte(), ByVal nNumberOfBytesToWrite As Integer, ByRef lpNumberOfBytesWritten As Integer, ByRef lpOverlapped As OVERLAPPED) As Integer
    End Function
    <DllImport("coredll.dll", SetlastError:=True)> Private Shared Function ReadFile(ByVal hFile As IntPtr, <Out()> ByVal Buffer As Byte(), ByVal nNumberOfBytesToRead As Integer, ByRef lpNumberOfBytesRead As Integer, ByRef lpOverlapped As OVERLAPPED) As Integer
    End Function
    <DllImport("coredll.dll", SetlastError:=True, CharSet:=CharSet.Auto)> Private Shared Function CreateFile(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 IntPtr
    End Function
    <DllImport("coredll.dll", SetlastError:=True)> Private Shared Function CloseHandle(ByVal hObject As IntPtr) As Boolean
    End Function
    <DllImport("coredll.dll", SetlastError:=True)> Public Shared Function GetCommModemStatus(ByVal hFile As IntPtr, ByRef lpModemStatus As Int32) As Boolean
    End Function
    <DllImport("coredll.dll", SetlastError:=True)> Private Shared Function SetEvent(ByVal hEvent As IntPtr) As Boolean
    End Function
    <DllImport("coredll.dll", SetlastError:=True, CharSet:=CharSet.Auto)> Private Shared Function CreateEvent(ByVal lpEventAttributes As IntPtr, ByVal bManualReset As Int32, ByVal bInitialState As Int32, ByVal lpName As String) As IntPtr
    End Function
    <DllImport("coredll.dll", SetlastError:=True)> Private Shared Function WaitForSingleObject(ByVal hHandle As IntPtr, ByVal dwMilliseconds As Int32) As Int32
    End Function
    <DllImport("coredll.dll", SetlastError:=True)> Private Shared Function GetOverlappedResult(ByVal hFile As IntPtr, ByRef lpOverlapped As OVERLAPPED, ByRef lpNumberOfBytesTransferred As Int32, ByVal bWait As Int32) As Int32
    End Function
    <DllImport("coredll.dll", SetlastError:=True)> Private Shared Function SetCommMask(ByVal hFile As IntPtr, ByVal lpEvtMask As Int32) As Int32
    End Function
    <DllImport("coredll.dll", SetlastError:=True, CharSet:=CharSet.Auto)> Private Shared Function GetDefaultCommConfig(ByVal lpszName As String, ByRef lpCC As COMMCONFIG, ByRef lpdwSize As Integer) As Boolean
    End Function
    <DllImport("coredll.dll", SetlastError:=True)> Private Shared Function SetCommBreak(ByVal hFile As IntPtr) As Boolean
    End Function
    <DllImport("coredll.dll", SetlastError:=True)> Private Shared Function ClearCommBreak(ByVal hFile As IntPtr) As Boolean
    End Function


#End Region

#Region "Enums 枚举型结构定义"
    '// Parity Data
    Public Enum DataParity
        Parity_None = 0
        Parity_Odd
        Parity_Even
        Parity_Mark
    End Enum
    '// StopBit Data
    Public Enum DataStopBit
        StopBit_1 = 1
        StopBit_2
    End Enum
    <Flags()> Public 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               '//接收一个字符放入输入缓冲区,EV_RXCHAR        0X0001
        RXFlag = &H2                '//接收到事件字符(DCB 结构的 EVTChar 成员),并放入输入缓冲区   EV_RXFLAG  0X0002
        TxBufferEmpty = &H4         '//输入缓冲区中的最后一个字符发送出去    EV_TXEMPTY    0X0004
        ClearToSend = &H8           '//CTS(清除发送)信号改变状态, EV_CTS   0X0008
        DataSetReady = &H10         '//DSR(数据设置就绪) 信号改变状态  EV_DSR    0X0010
        CarrierDetect = &H20        '//RLSD(接受线路信号检测) 信号改变状态 EV_RLSD 0X0020 
        Break = &H40                '//监测到输入的终止,EV_BREAK   0X0040
        StatusError = &H80          '//发生了线路状态错误,线路状态错误时 CE_FRAME(帧错误   ) 0X0080
        Ring = &H100               '//监测到振铃  EV_RING  0X0100
    End Enum

#End Region

#Region "Structures 数据结构体定义"
    <StructLayout(LayoutKind.Sequential)> Private Structure DCB
        Public DCBlength As Int32
        Public BaudRate As Int32
        Public Bits1 As Int32
        Public wReserved As Int16
        Public XonLim As Int16
        Public XoffLim As Int16
        Public ByteSize As Byte
        Public Parity As Byte
        Public StopBits As Byte
        Public XonChar As Char
        Public XoffChar As Char
        Public ErrorChar As Char
        Public EofChar As Char
        Public EvtChar As Char
        Public wReserved2 As Int16
    End Structure
    <StructLayout(LayoutKind.Sequential)> 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)> Private Structure COMMCONFIG
        Public dwSize As Int32
        Public wVersion As Int16
        Public wReserved As Int16
        Public dcbx As DCB
        Public dwProviderSubType As Int32
        Public dwProviderOffset As Int32
        Public dwProviderSize As Int32
        Public wcProviderData As Int16
    End Structure
    <StructLayout(LayoutKind.Sequential)> Public Structure OVERLAPPED
        Public Internal As Int32
        Public InternalHigh As Int32
        Public Offset As Int32
        Public OffsetHigh As Int32
        Public hEvent As IntPtr
    End Structure
    <StructLayout(LayoutKind.Sequential)> Private Structure COMSTAT
        Dim fBitFields As Int32
        Dim cbInQue As Int32
        Dim cbOutQue As Int32
    End Structure

#End Region

#Region "类 属性 接口声明 和实现"


    Public Property Port() As Integer
        '===================================================
        '
        '		Description	:		Comunication Port
        '		Created			:		21/09/2001 - 11:25:49
        '
        '												*Parameters Info*
        '
        '		Notes				:
        '===================================================
        Get
            Return miPort
        End Get
        Set(ByVal Value As Integer)
            miPort = Value
        End Set
    End Property
    Public Sub PurgeBuffer(ByVal Mode As PurgeBuffers)
        '===================================================
        '												?003 ALSTOM FIR S.p.A All rights reserved
        '
        '	Description	:	Purge Communication Buffer
        '	Created			:	01/09/03 - 10:37:39
        '	Author			:	Corrado Cavalli
        '
        '						*Parameters Info*
        '
        '	Notes				:	This method will clear any character into buffer, use TxAbort/RxAbort
        '								to terminate any pending overlapped Tx/Rx operation.
        '===================================================
        If (m_hcom.ToInt32 <> 0 And m_hcom.ToInt32 <> INVALID_HANDLE_VALUE) Then PurgeComm(m_hcom, Mode)
    End Sub
    Public Overridable Property Timeout() As Integer
        '===================================================
        '
        '		Description:		Comunication timeout in seconds
        '		Created			:		21/09/2001 - 11:26:50
        '
        '												*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
        '===================================================
        '

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -