Private serialPort As SerialPort '定义
Public Function CreateSerialPort() As String
Dim strWeights As String = ""
Dim strData As String = ""
Dim bSetPointNum As Double = 0.0
If serialPort IsNot Nothing Then
If serialPort.IsOpen Then
Me.serialPort.Close()
End If
Me.serialPort.Dispose()
End If
Try
serialPort = New SerialPort("COM" + clXML.Read("Login", "bserialPortNames", ""), Integer.Parse(clXML.Read("Login", "bBaudRate", "")), CType([Enum].Parse(GetType(Parity), clXML.Read("Login", "bParity", "")), Parity), Integer.Parse(clXML.Read("Login", "bDataBits", "")), CType([Enum].Parse(GetType(StopBits), clXML.Read("Login", "bStopBits", "")), StopBits))
serialPort.WriteTimeout = 20000
serialPort.ReadTimeout = 20000
serialPort.ReadBufferSize = 20480
serialPort.WriteBufferSize = 20480
serialPort.Open()
Dim portName As String = "COM" + clXML.Read("Login", "bserialPortNames", "")
If serialPort.IsOpen Then
Dim readLength As Integer = 8
Dim offset As Integer = 0
Dim data As Byte() = New Byte(readLength - 1) {}
Do
Dim byteLenght As Integer = serialPort.Read(data, offset, readLength)
offset += byteLenght
readLength -= byteLenght
Loop While serialPort.BytesToRead > 0
strData = Encoding.[Default].GetString(data)
bSetPointNum = clXML.Read("Login", "bSetPoint", "")
SetPoint()
If IsNumeric(strData) = True Then
strWeights = IIf(strData / bSetPointNum < "0", bSetPoint, Val(strData / bSetPointNum))
Application.DoEvents()
Else
strWeights = bSetPoint
End If
If strWeights = "" Then
Return CreateSerialPort()
End If
End If
Catch ex As Exception
c.MsgInfro(c.GetResource("MyResource", "public_serialPortError"), "Notices", True)
End Try
Return strWeights
End Function