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