Justinio's vb.net version! (Serial operation type)

Source: Internet
Author: User
Tags integer readfile reserved win32
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 '//Specify current baud rate baud rate
'//These are the "C struct bit fields, bit twiddle flag to set
Public fbinary as Integer '//Specifies whether to allow binary mode, in Windows95 must be the primary true binary mode, no EOF check
Public fparity as Integer '//Specifies whether parity enable parity checking
Public Foutxctsflow as Integer '//Specifies whether the CTS is used to detect send control, and when True is the CTS is off, the send is suspended. CTS Output Flow Control
Public Foutxdsrflow as Integer '//Specify whether CTS is used to detect send control DSR output flow controls
The public Fdtrcontrol as Integer '//dtr_control_disable value will be DTR to OFF, dtr_control_enable value will be DTR to ON, Dtr_control_ Handshake allows DTR "handshake" DTR flow control type
Public fdsrsensitivity as Integer '//Bytes received when the DSR is off when this value is true is ignored in DSR sensitivity
Public Ftxcontinueonxoff as Integer '//Specifies whether the send is stopped when the receive buffer is full and the driver has sent out XoffChar characters. True, the send continues after the receive buffer receives a buffer full byte Xofflim and the driver has sent a xoffchar character to abort the receive byte. False, the send continues after the receive buffer receives a byte XonChar that represents the empty buffer and the driver has sent the XonChar that sent the recovery. XOFF continues Tx
Public foutx as Integer '//True, after receiving XoffChar stop sending receive XonChar will restart Xon/xoff out flow control
Public Finx as Integer '//True, when the receive buffer receives the Xofflim that represents the buffer full, XoffChar sends out the receive buffer to receive the Xonlim that represents the buffer empty, XonChar sends out Xon/xoff in Flow control
Public Ferrorchar as Integer '//The value is True and Fparity is true, the character specified by the ErrorChar member is substituted for the receive character of the parity error to enable error replacement
When public fnull as Integer '//Etrue, the null (0 value) byte is removed to enable null when received stripping
Public Frtscontrol as Integer/RTS control
'/*rts_control_disable when the RTS is off
' * rts_control_enable, RTS is placed on
' * When Rts_control_handshake,
' * RTS is on when receive buffer is less than half full
' * When the receive buffer exceeds three-fourths full, RTS is off
' * When Rts_control_toggle,
' * The RTS is on when the receive buffer still has remaining bytes, otherwise the default is off*/
Public fabortonerror as Integer '//True, abort read and write while error occurs abort on Error
Public fDummy2 as Integer '//unused reserved
Public flags as Int64
Public wreserved as UInt16 '//unused, must be 0 not currently used
Public Xonlim as UInt16 '//Specify the minimum number of bytes allowed in the receive buffer before the XON character is sent transmit XON threshold
Public Xofflim as UInt16 '//Specify the minimum number of bytes allowed in the receive buffer before the XOFF character is sent transmit XOFF threshold
Public bytesize as Byte//Specifies the number of data bits currently in use for the port of Bits/byte, 4-8
Public Parity as Byte//Specifies the parity method currently used by the port, possibly: evenparity,markparity,noparity,oddparity 0-4=no,odd,even,mark,space
Public stopbits as Byte//Specifies the number of stop digits currently in use for the port, possibly: onestopbit,one5stopbits,twostopbits 0,1,2 = 1, 1.5, 2
Public XonChar as Char '//Specifies the value to send and receive character XON Tx and Rx 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 in lieu of the value of the received parity error replacement character
Public EofChar as Char '//when no binary mode is used, this character can be used to indicate the end of the data in the input character
Public Evtchar as Char '//When this character is received, an event is generated received events character
Public wReserved1 as UInt16 '//not used reserved; Don't 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 the 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
' Parameter introduction:
' lpFileName the serial name to be opened
' dwdesiredaccess specifies how the serial port is accessed, generally set to readable and writable
' dwShareMode specifies the serial port sharing mode, the serial port cannot be shared, so set to 0
' lpSecurityAttributes set the security properties of the serial port, Win9x not supported, should be set to NULL
' dwCreationDisposition for serial communication, the only way to create a open_existing
' dwflagsandattributes specifies serial port properties and flags, set to file_flag_overlapped (overlapped I/O operations), specify 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 handle to Comm device
' Lpcommtimeouts timeout time 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 handle to Comm device
' Lpcommtimeouts timeout time 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 handle to file
' Lpbuffer Data buffer
' nNumberOfBytesToRead how many bytes wait to read the number of bytes to read
' Lpnumberofbytesread reads how many bytes number of bytes read
' lpoverlapped overflow buffer overlapped buffers
<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 handle to file
' Lpbuffer Data buffer
' Nnumberofbytestowrite how many bytes wait to write number of bytes to write
' Lpnumberofbyteswritten has written how many bytes number of bytes written
' lpoverlapped overflow buffer overlapped buffers
<dllimport ("kernel32.dll") > _
Private Shared Function CloseHandle (ByVal hobject as Integer) as Boolean
End Function
' parameter hobject the handle to be closed 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 serial port opened 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 open, open if the port cannot is opened, bail out.
If Hcomm = Invalid_handle_value Then
Throw (New applicationexception ("Illegal operation, cannot open serial port!") "))
End If
'//Set the communication timeout time 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 serial port 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 ("Illegal operation, cannot open serial port!") "))
End If
'//unremark to ' 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 ("Serial Port not open!") "))
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 ("Serial Port not open!") "))
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.