JustinIO的vb.NET版本!(串口操作类)

Imports System
Imports 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 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 '// 指定当前波特率 current baud rate
'// these are the c struct bit fields, bit twiddle flag to set
Public fBinary As Integer '// 指定是否允许二进制模式,在windows95中必须主TRUE binary mode, no EOF check
Public fParity As Integer '// 指定是否允许奇偶校验 enable parity checking
Public fOutxCtsFlow As Integer '// 指定CTS是否用于检测发送控制,当为TRUE是CTS为OFF,发送将被挂起。 CTS output flow control
Public fOutxDsrFlow As Integer '// 指定CTS是否用于检测发送控制 DSR output flow control
Public fDtrControl As Integer '// DTR_CONTROL_DISABLE值将DTR置为OFF, DTR_CONTROL_ENABLE值将DTR置为ON, DTR_CONTROL_HANDSHAKE允许DTR"握手" DTR flow control type
Public fDsrSensitivity As Integer '// 当该值为TRUE时DSR为OFF时接收的字节被忽略 DSR sensitivity
Public fTXContinueOnXoff As Integer '// 指定当接收缓冲区已满,并且驱动程序已经发送出XoffChar字符时发送是否停止。TRUE时,在接收缓冲区接收到缓冲区已满的字节XoffLim且驱动程序已经发送出XoffChar字符中止接收字节之后,发送继续进行。 FALSE时,在接收缓冲区接收到代表缓冲区已空的字节XonChar且驱动程序已经发送出恢复发送的XonChar之后,发送继续进行。XOFF continues Tx
Public fOutX As Integer '// TRUE时,接收到XoffChar之后便停止发送接收到XonChar之后将重新开始 XON/XOFF out flow control
Public fInX As Integer '// TRUE时,接收缓冲区接收到代表缓冲区满的XoffLim之后,XoffChar发送出去接收缓冲区接收到代表缓冲区空的XonLim之后,XonChar发送出去 XON/XOFF in flow control
Public fErrorChar As Integer '// 该值为TRUE且fParity为TRUE时,用ErrorChar 成员指定的字符代替奇偶校验错误的接收字符 enable error replacement
Public fNull As Integer '// eTRUE时,接收时去掉空(0值)字节 enable null stripping
Public fRtsControl As Integer '// RTS flow control
'/*RTS_CONTROL_DISABLE时,RTS置为OFF
' *   RTS_CONTROL_ENABLE时, RTS置为ON
' *    RTS_CONTROL_HANDSHAKE时,
' *    当接收缓冲区小于半满时RTS为ON
' *     当接收缓冲区超过四分之三满时RTS为OFF
' *    RTS_CONTROL_TOGGLE时,
' *    当接收缓冲区仍有剩余字节时RTS为ON ,否则缺省为OFF*/
Public fAbortOnError As Integer '// TRUE时,有错误发生时中止读和写操作 abort on error
Public fDummy2 As Integer '// 未使用 reserved
Public flags As Int64
Public wReserved As UInt16 '// 未使用,必须为0 not currently used
Public XonLim As UInt16 '// 指定在XON字符发送这前接收缓冲区中可允许的最小字节数 transmit XON threshold
Public XoffLim As UInt16 '// 指定在XOFF字符发送这前接收缓冲区中可允许的最小字节数 transmit XOFF threshold
Public ByteSize As Byte '// 指定端口当前使用的数据位 number of bits/byte, 4-8
Public Parity As Byte '// 指定端口当前使用的奇偶校验方法,可能为:EVENPARITY,MARKPARITY,NOPARITY,ODDPARITY 0-4=no,odd,even,mark,space
Public StopBits As Byte '// 指定端口当前使用的停止位数,可能为:ONESTOPBIT,ONE5STOPBITS,TWOSTOPBITS 0,1,2 = 1, 1.5, 2
Public XonChar As Char '// 指定用于发送和接收字符XON的值 Tx and Rx XON character
Public XoffChar As Char '// 指定用于发送和接收字符XOFF值 Tx and Rx XOFF character
Public ErrorChar As Char '// 本字符用来代替接收到的奇偶校验发生错误时的值 error replacement character
Public EofChar As Char '// 当没有使用二进制模式时,本字符可用来指示数据的结束 end of input character
Public EvtChar As Char '// 当接收到此字符时,会产生一个事件 received event character
Public wReserved1 As UInt16 '// 未使用 reserved; 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 dwShareMode As Integer, _
ByVal lpSecurityAttributes As Integer, _
ByVal dwCreationDisposition As Integer, _
ByVal dwFlagsAndAttributes As Integer, _
ByVal hTemplateFile As Integer) As Integer
End Function
'参数介绍:
'lpFileName 要打开的串口名称
'dwDesiredAccess 指定串口的访问方式,一般设置为可读可写方式
'dwShareMode 指定串口的共享模式,串口不能共享,所以设置为0
'lpSecurityAttributes 设置串口的安全属性,WIN9X下不支持,应设为NULL
'dwCreationDisposition 对于串口通信,创建方式只能为OPEN_EXISTING
'dwFlagsAndAttributes 指定串口属性与标志,设置为FILE_FLAG_OVERLAPPED(重叠I/O操作),指定串口以异步方式通信
'hTemplateFile 对于串口通信必须设置为NULL
<DllImport("kernel32.dll")> _
Private Shared Function GetCommState(ByVal hFile As Integer, ByRef lpDCB As DCB) As Boolean
End Function
'参数介绍
'hFile 通信设备句柄
'DCB lpDCB 设备控制块DCB

<DllImport("kernel32.dll")> _
Private Shared Function BuildCommDCB(ByVal lpDef As String, ByRef lpDCB As DCB) As Boolean
End Function
'参数介绍
'lpDef 设备控制字符串
'lpDCB 设备控制块DCB
<DllImport("kernel32.dll")> _
Private Shared Function SetCommState(ByVal hfile As Integer, ByRef lpDCB As DCB) As Boolean
End Function
'参数说明
'hFile 通信设备句柄
'lpDCB 设备控制块
<DllImport("kernel32.dll")> _
Private Shared Function GetCommTimeouts(ByVal hfile As Integer, ByRef lpCommTimeouts As COMMTIMEOUTS) As Boolean
End Function
'参数说明
'hFile 通信设备句柄 handle to comm device
'lpCommTimeouts 超时时间 time-out values
<DllImport("kernel32.dll")> _
Private Shared Function SetCommTimeouts(ByVal hfile As Integer, ByRef lpCommTimeouts As COMMTIMEOUTS) As Boolean
End Function
'参数说明
'hFile 通信设备句柄 handle to comm device
'lpCommTimeouts 超时时间 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
'参数说明
'hFile 通信设备句柄 handle to file
'lpBuffer 数据缓冲区 data buffer
'nNumberOfBytesToRead 多少字节等待读取 number of bytes to read
'lpNumberOfBytesRead 读取多少字节 number of bytes read
'lpOverlapped 溢出缓冲区 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
'参数介绍
'hFile 通信设备句柄 handle to file
'lpBuffer 数据缓冲区 data buffer
'nNumberOfBytesToWrite 多少字节等待写入 number of bytes to write
'lpNumberOfBytesWritten 已经写入多少字节 number of bytes written
'lpOverlapped 溢出缓冲区 overlapped buffer
<DllImport("kernel32.dll")> _
Private Shared Function CloseHandle(ByVal hObject As Integer) As Boolean
End Function
'参数hObject 要被关闭的句柄 handle to object
<DllImport("kernel32.dll")> _
Private Shared Function GetLastError() As UInt32
End Function
#End Region
Public Sub open()
Dim dcbCommPort As New DCB
Dim ctoCommPort 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 PORT CANNOT BE OPENED, BAIL OUT.
If hComm = INVALID_HANDLE_VALUE Then
Throw (New ApplicationException("非法操作,不能打开串口!"))
End If
'// 设置通信超时时间 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 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("非法操作,不能打开串口!"))
End If
'//unremark to see if setting took correctly
'//DCB dcbCommPort2 = new DCB();
'//GetCommState(hComm, ref dcbCommPort2);
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 ovlCommPort As New OVERLAPPED
Dim BytesRead As Integer = 0
ReadFile(hComm, BufBytes, NumBytes, BytesRead, ovlCommPort)
Array.Copy(BufBytes, OutBytes, BytesRead)
Else
Throw (New ApplicationException("串口未打开!"))
End If
Return OutBytes
End Function

Public 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 (New ApplicationException("串口未打开!"))
End If
End Sub
End Class
End Namespace

时间: 2024-09-19 09:41:15

JustinIO的vb.NET版本!(串口操作类)的相关文章

C#异步数据接收串口操作类

数据|异步 使用C#调用传统32位API实现串口操作,整个结构特别的简单.接收数据只需要定义数据接收事件即可. 上传源代码我不会,需要源代码的请与我(dyj057@gmail.com)联系.你也可以教我怎么上传源代码. using System;using System.Runtime.InteropServices; /// <summary>/// (C)2003-2005 C2217 Studio 保留所有权利/// /// 文件名称: IbmsSerialPort.cs/// 文件ID

C#封装的一个串口操作类(可用于Win CE)

封装 using System;using System.Runtime.InteropServices; namespace NativeDll{ /// <summary> /// SerialPort 的摘要说明. /// </summary> public class SerialPort { #region 申明要引用的和串口调用有关的API //win32 api constants private const uint GENERIC_READ = 0x8000000

C#串口通讯类

串口通讯类: using System;using System.Runtime.InteropServices;namespace JustinIO { class CommPort { public string PortNum; public int BaudRate; public byte ByteSize; public byte Parity; // 0-4=no,odd,even,mark,space public byte StopBits; // 0,1,2 = 1, 1.5

VC#串口操作实用类

做工业通信有很长时间了,特别是串口(232/485),有VB/VC/C各种版本的串口操作代码,这些代码也经过了多年的现场考验,应该说是比较健壮的代码,但是目前却没有C#相对成熟的串口操作代码,最近用Moxa的设备开发基于WinCE5.0的串口操作代码,所以就扩充完善了一下串口操作,特别是SendCommand函数,这是我比较常用的主从通信代码,不喜欢用事件或线程接数据,在规定的超时时间内直接循环判断要接收的数据. 下面是具体的代码: public class PortData { public

ASP通用数据库操作类源代码

<%'=========================================================================='文件名称:clsDbCtrl.asp'功 能:数据库操作类'作 者:coldstone (coldstone[在]qq.com)'程序版本:v1.0.5'完成时间:2005.09.23'修改时间:2007.10.30'版权声明:可以在任意作品中使用本程序代码,但请保留此版权信息.'          如果你修改了程序中的代码并得到更好的应用,

一个简单的asp数据库操作类

数据|数据库 <%'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%'数据库操作类'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%'名称:Class_DBOperate'版本:0.2'作者:qihangnet'更新:2005年6月14日'作用:简化数据库操作的流程'授权:免费使用'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Class Class_DBOperate '************************

MYSQL的操作类(修改后的新版本)

mysql           class MySQLDB  {    //MYSQL数据库操作类    //作者:熊毅    //版本:2.0(发行版)        //可以自由转载,修改请通知我scxy78@yeah.net    //转载请保留以上声明        //使用说明:    //该类完全按照ADO的习惯书写的,用过ASP的人都觉得ASP连接数据库比PHP好用(这是我的感觉),    //但PHP得一个一个API地写,挺累,该类做了完全的封装    //创建类的实例时可以指定

简单快速有趣的MySQL数据库操作类:SimpleDB

mysql|数据|数据库 自己写着玩的,代码没有测试,不过觉得思路不错,如果能够加上部分异常处理的功能,应该比较帅了,支持PHP4/PHP5,恩,虽然没有ADOdb或者PEAR::DB强,不错一般应用应该不错,恩. 喜欢的就自己拿去用吧,自己随便改,呵呵,也欢迎提意见.(注释遵循PHPDoc的标准,便于生成手册)  注意:代码未经测试,出现问题可要自己负责哇,呵呵.         <?//==========================================// 文件: Simp

C#串口操作(国外网站看来的,共享一下)

国外网站 前一阵,从国外网站看到一个用C#来操作串口的类.下载下来试了一下,觉得不错.共享一下./** Author: Marcus Lorentzon, 2001* d98malor@dtek.chalmers.se* * Freeware: Please do not remove this header* * File: SerialStream.cs* * Description: Implements a Stream for asynchronous* transfers and C