16,556
社区成员
发帖
与我相关
我的任务
分享
Public Sub SimControllSending(stateInfo As Object)
Dim autoEvent As AutoResetEvent = DirectCast(stateInfo, AutoResetEvent)
Dim bDataOut() As Byte
Dim Buf As String
Dim iSentCount As Integer
Dim Encode1 As Encoding = Encoding.ASCII '声明编码对象,使用ASCII
Dim bOutHexTemp() As String
Dim temp As String()
Dim strIncoming As String
Dim bytes() As Byte
Dim str1(), str2() As String
Dim ReceivePer As Integer
ReceivePer = 0
Dim ReceivedString As String
Try
'如果是ASCII发送
If Not send_HEX_Checked = True Then
temp = Split(Interval(SimControllerSendCount), "|")
Buf = temp(1).ToString().Trim()
bDataOut = Encode1.GetBytes(Buf)
'将字符串转换为字节数组
End If
'如果是HEX发送
If send_HEX_Checked = True Then
temp = Split(Interval(SimControllerSendCount), "|")
Buf = temp(1).ToString().Trim()
bOutHexTemp = Split(Buf, " ")
ReDim bDataOut(bOutHexTemp.Count - 1)
For i = 0 To bOutHexTemp.Count - 1
bDataOut(i) = Val("&H" & bOutHexTemp(i))
Next
End If
iSentCount = bDataOut.GetLength(0) '发送总字节数
RS232.Write(bDataOut, 0, iSentCount)
Catch ex As Exception
'MessageBox.Show("输入数值错误:" + ex.ToString, "错误通知", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
End Try
Console.WriteLine(DateTime.Now.ToString("h:mm:ss.fff") & ", i am sending ...now ... " & Buf)
autoEvent.Set()
SimControllerSendCount += 1
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'下面代码是用RS232_2接收通道1发来的数据并记录到DataGridView2上
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Try
'txtReceive.Text = Str(Val(txtReceive.Text) + RS232_2.BytesToRead)
'If RS232_2.BytesToRead > 0 Then
ReceivePer = RS232_2.BytesToRead
''ThreadItem1. '添加的延时
'HEX方式接收
If receive_HEX_Checked Then
If RS232_2.BytesToRead > 0 Then
ReDim bytes(RS232_2.BytesToRead)
'strIncoming = Convert.ToByte(SerialPort1.ReadByte())
'If receivecheck.Checked = True Then
strIncoming = RS232_2.ReadByte()
bytes(0) = strIncoming
For i = 1 To RS232_2.BytesToRead
strIncoming = RS232_2.ReadByte() '读取缓冲区中的数据
bytes(i) = strIncoming
Next
' SerialPort1.Write(sendbox.Text)'发送数据
RS232_2.DiscardInBuffer()
str1 = Split(BitConverter.ToString(bytes), "-")
ReDim str2(str1.Length - 1) '去除str1中最后的字符
For i = 0 To str1.Length - 2
str2(i) = str1(i)
Next
'txtReceive.Text &
ReceivedString = Join(str2, " ")
'BitConverter.ToString(bytes)
'Else
' receivebox.Text = receivebox.Text & SerialPort1.ReadExisting()
'End If
End If
Else 'ASCII方式接收
If RS232_2.BytesToRead > 0 Then
strIncoming = RS232_2.ReadExisting '读取缓冲区中的数据
RS232_2.DiscardInBuffer()
ReceivedString = strIncoming
End If
End If
'将收到的报文保存到DataGridView中
Dim dr As DataRow = dt_temp.NewRow()
dr(0) = mPortName2
dr(1) = Now() & "." & Microsoft.VisualBasic.Right("0" & Now().Millisecond.ToString(), 3) & "s"
dr(2) = ReceivedString
dt_temp.Rows.Add(dr)
iReceiveCount = iReceiveCount + ReceivePer
'countReceived.Text = iReceiveCount
' End If
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'上面代码是用RS232_2接收通道1发来的数据并记录到DataGridView2上
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
End Sub
'触发接收事件
Public Sub Sp_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles RS232.DataReceived
Me.Invoke(New EventHandler(AddressOf Sp_Receiving)) '调用接收数据函数
End Sub
'触发接收事件
'Public Sub Sp_DataReceived_2(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles RS232_2.DataReceived
' Me.Invoke(New EventHandler(AddressOf Sp_Receiving_2)) '调用接收数据函数
'End Sub
'接收数据
Private Sub Sp_Receiving(ByVal sender As Object, ByVal e As EventArgs)
Dim strIncoming As String
Dim Encode1 As Encoding = Encoding.Unicode
Dim bytes() As Byte
Dim str1(), str2() As String
Dim ReceivePer As Integer
ReceivePer = 0
Try
'txtReceive.Text = Str(Val(txtReceive.Text) + RS232_2.BytesToRead)
' If RS232.BytesToRead > 0 Then
'Threading.Thread.Sleep(100) '添加的延时
'HEX方式接收
If ChboxHex2.Checked Then
If RS232.BytesToRead > 0 Then
ReDim bytes(RS232.BytesToRead)
ReceivePer = RS232.BytesToRead()
'strIncoming = Convert.ToByte(SerialPort1.ReadByte())
'If receivecheck.Checked = True Then
strIncoming = RS232.ReadByte()
bytes(0) = strIncoming
For i = 1 To RS232.BytesToRead
strIncoming = RS232.ReadByte() '读取缓冲区中的数据
bytes(i) = strIncoming
Next
' SerialPort1.Write(sendbox.Text)'发送数据
RS232.DiscardInBuffer()
str1 = Split(BitConverter.ToString(bytes), "-")
ReDim str2(str1.Length - 1) '去除str1中最后的字符
For i = 0 To str1.Length - 2
str2(i) = str1(i)
Next
'txtReceive.Text &
txtReceive.Text = Join(str2, " ")
'BitConverter.ToString(bytes)
'Else
' receivebox.Text = receivebox.Text & SerialPort1.ReadExisting()
'End If
End If
Else 'ASCII方式接收
If RS232.BytesToRead > 0 Then
ReceivePer = RS232.BytesToRead
strIncoming = RS232.ReadExisting '读取缓冲区中的数据
RS232.DiscardInBuffer()
txtReceive.Text = strIncoming
End If
End If
'将收到的报文保存到DataGridView中
Dim dr As DataRow = dt.NewRow()
dr(0) = mPortName
dr(1) = Now() & "." & Microsoft.VisualBasic.Right("0" & Now().Millisecond.ToString(), 3) & "s"
dr(2) = txtReceive.Text
dt.Rows.Add(dr)
Me.DataGridView2.DataSource = dt
For i = 0 To DataGridView2.Columns.Count - 1
DataGridView2.AutoResizeColumn(i, DataGridViewAutoSizeColumnMode.AllCells)
Next
iReceiveCount = iReceiveCount + ReceivePer
countReceived.Text = iReceiveCount
'End If
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
'接收数据
Public Sub Sp_Receiving_2(ByVal sender As Object, ByVal e As EventArgs)
Dim strIncoming As String
Dim Encode1 As Encoding = Encoding.Unicode
Dim bytes() As Byte
Dim str1(), str2() As String
Dim ReceivePer As Integer
ReceivePer = 0
Try
'txtReceive.Text = Str(Val(txtReceive.Text) + RS232_2.BytesToRead)
'If RS232_2.BytesToRead > 0 Then
ReceivePer = RS232_2.BytesToRead
''ThreadItem1. '添加的延时
'HEX方式接收
If ChboxHex2.Checked Then
If RS232_2.BytesToRead > 0 Then
ReDim bytes(RS232_2.BytesToRead)
'strIncoming = Convert.ToByte(SerialPort1.ReadByte())
'If receivecheck.Checked = True Then
strIncoming = RS232_2.ReadByte()
bytes(0) = strIncoming
For i = 1 To RS232_2.BytesToRead
strIncoming = RS232_2.ReadByte() '读取缓冲区中的数据
bytes(i) = strIncoming
Next
' SerialPort1.Write(sendbox.Text)'发送数据
RS232_2.DiscardInBuffer()
str1 = Split(BitConverter.ToString(bytes), "-")
ReDim str2(str1.Length - 1) '去除str1中最后的字符
For i = 0 To str1.Length - 2
str2(i) = str1(i)
Next
'txtReceive.Text &
txtReceive.Text = Join(str2, " ")
'BitConverter.ToString(bytes)
'Else
' receivebox.Text = receivebox.Text & SerialPort1.ReadExisting()
'End If
End If
Else 'ASCII方式接收
If RS232_2.BytesToRead > 0 Then
strIncoming = RS232_2.ReadExisting '读取缓冲区中的数据
RS232_2.DiscardInBuffer()
txtReceive.Text = strIncoming
End If
End If
'将收到的报文保存到DataGridView中
Dim dr As DataRow = dt.NewRow()
dr(0) = mPortName2
dr(1) = Now() & "." & Microsoft.VisualBasic.Right("0" & Now().Millisecond.ToString(), 3) & "s"
dr(2) = txtReceive.Text
dt.Rows.Add(dr)
Me.DataGridView2.DataSource = dt
For i = 0 To DataGridView2.Columns.Count - 1
DataGridView2.AutoResizeColumn(i, DataGridViewAutoSizeColumnMode.AllCells)
Next
iReceiveCount = iReceiveCount + ReceivePer
countReceived.Text = iReceiveCount
' End If
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Public Sub btnRun_Click(sender As Object, e As EventArgs) Handles btnRun.Click
Dim autoEvent As New AutoResetEvent(False)
Dim SendingPacket1 As New SendingPacket(10)
Dim i As Long
i = 0
Dim temp As String()
Dim dueTime As Integer
loadInterval()
ThreadItem1 = New System.Threading.Timer(New TimerCallback(AddressOf SimControllSending), autoEvent, 0, 0)
While i <= zzz
autoEvent.WaitOne(999999999, False)
temp = Split(Interval(i), "|")
dueTime = temp(0).Trim()
ThreadItem1.Change(dueTime, 0)
Console.WriteLine("i=" & i & ", " & Interval(i) & "ms")
Console.WriteLine(vbCrLf & "Changing period." & vbCrLf)
i += 1
End While
ThreadItem1.Dispose()
Interval = Nothing
Console.WriteLine(vbCrLf & "Destroying timer.")
SimControllerSendCount = 0
isRotate = False '循环运行为false
Me.DataGridView2.DataSource = dt_temp
For i = 0 To DataGridView2.Columns.Count - 1
DataGridView2.AutoResizeColumn(i, DataGridViewAutoSizeColumnMode.AllCells)
Next
btnStart.Enabled = False '打开和关闭端口失效变灰
btnRun.Enabled = False 'csv启动运行按钮失效变灰
btnFileOpen.Enabled = False '打开文件按钮失效变灰
End Sub
Public Class SendingPacket
Dim invokeCount, maxCount As Integer
Sub New(count As Integer)
invokeCount = 0
maxCount = count
End Sub
' This method is called by the timer delegate.
Sub Sending(stateInfo As Object)
Dim autoEvent As AutoResetEvent = DirectCast(stateInfo, AutoResetEvent)
Console.WriteLine(DateTime.Now.ToString("h:mm:ss.fff") & ", i am sending ...now " & invokeCount.ToString())
autoEvent.Set()
End Sub
End Class
Public Class TimeChecker
Public Event EndCheckTime(dt As DateTime) '定义完成事件
Public Sub GetTimeAsync()
Dim th As Thread = New Thread(Sub(obj)
Thread.Sleep(3000)
Dim dt As DateTime = DateTime.Now
RaiseEvent EndCheckTime(dt) '触发完成事件
End Sub)
'设为后台线程,这样当主线程结束时会自动结束。
'不然这里运行到一半时,关闭主窗体,程序并不会马上退出。
'这也是直接用thread不方便的地方
th.IsBackground = True
th.Start()
End Sub
End Class
窗体调用:
Private WithEvents checker As TimeChecker = New TimeChecker()
'定义事件处理函数
Private Sub checker_EndCheck(dt As DateTime) Handles checker.EndCheckTime
'在这里通过窗体的Invoke方法回到UI线程
Me.Invoke(New MethodInvoker(Sub()
MsgBox(String.Format("当前时间:{0}。", dt))
End Sub))
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
checker.GetTimeAsync() ‘调用异步方法。
End Sub
Delegate Function GetDataSource() As DataTable
Delegate Sub SetDataSource(dt As DataTable)
Private Sub Form_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim h As GetDataSource = New GetDataSource(AddressOf gsb)
h.BeginInvoke(New AsyncCallback(AddressOf gsbCallback), h)
End Sub
Private Function gsb() As DataTable
......
End Function
Private Sub gsbCallback(ar As IAsyncResult)
Dim h As GetDataSource = CType(ar.AsyncState, GetDataSource)
Dim dt As DataTable = h.EndInvoke(ar)
dgv.Invoke(New SetDataSource(AddressOf SetDgvDataSource), dt)
End Sub
Private Sub SetDgvDataSource(dt As DataTable)
dgv.DataSource = dt
End Sub