Imports System.Threading
Imports UTS_Core.DebugLog

Public Class Uart_1089

    Public DataKey As String
    Public Rowid As Integer = 0
    '发送次数
    Public SendNumber As Integer = 0
    '发送时间
    Public SendDate As Date
    '发送间隔(ms)
    Public SendIinterval As Integer = 8000
    Public WaitIinterval As Integer = 100
    '发送数据
    Public SendData As String
    '发送帧号
    Public SendFrame As Integer = 0
    '发送命令
    Public SendCmd As Integer
    ''' <summary>
    ''' 发送状态,
    ''' </summary>
    Public CmdStat As Boolean = False
    ''' <summary>
    ''' 接收状态,
    ''' </summary>
    Public CmdReadStat As Boolean = False
    ''' <summary>
    ''' 接收结果,
    ''' </summary>
    Public CmdReadResult As Boolean = False

    Public Cycleflag As Boolean = False
    Public Resendnum As Integer = 3
    '''' <summary>
    '''' 预期回复是多条还是一条【默认一条】
    '''' </summary>
    'Public ManyState As Boolean = 0

    '''' <summary>
    '''' 回复数据
    '''' </summary>
    'Public ReadDataList As New List(Of Object)






End Class

Public Class Uart_1089_Client
    Private _Uart As IO.Ports.SerialPort
    Private _RichTextBox1 As RichTextBox

    Private _IsCycleflag As Boolean = False

    Public SendDataList As New List(Of Uart_1089)
    Private _tooplabel As Label
    Public IsSendThresdflag As Boolean = True
    Private _Task As Thread
    Private _grid As FlexCell.Grid
    Private _ThreadBuff() As Thread

    '''<summary>测试结束事件</summary>
    Public Event TestEnd(ispass As Boolean)
    Sub New（SerialPort1 As IO.Ports.SerialPort, RichTextBox1 As RichTextBox, grd As FlexCell.Grid, tooplabel As Label, ParamArray ThreadBuff() As Thread）
        _Uart = SerialPort1
        _RichTextBox1 = RichTextBox1
        _Task = New Thread(New ThreadStart(AddressOf SnedUartThread))
        _grid = grd
        _tooplabel = tooplabel
        _ThreadBuff = ThreadBuff
        _Task.Start()
    End Sub
    Public Sub TaskClose(isflag As Boolean)
        If isflag Then
            _Task.Abort()
            For threadid As Integer = 0 To _ThreadBuff.Length - 1
                _ThreadBuff(threadid).Abort()
            Next
        Else
            If _Task.IsAlive Then
            Else
                _Task = New Thread(New ThreadStart(AddressOf SnedUartThread))
                _Task.Start()
            End If
        End If


    End Sub

    Public Sub Colose_Uart()
        If IsNothing(_Uart) Then Return
        If _Uart.IsOpen Then
            _Uart.Close()
        End If
    End Sub
    Public Function Get_Uart() As Boolean
        If IsNothing(_Uart) Then Return False
        Return _Uart.IsOpen
    End Function


    Private Sub SnedUartThread()
        'ApplicationLog.WriteInfoLog($"测试页面生产线变更中。")
        Dim theClient As Uart_1089
        While IsSendThresdflag
            If SendDataList.Count < 1 Then Continue While
            theClient = SendDataList.Item(0)
            If theClient.SendNumber = 1 And theClient.Cycleflag Then
                For threadid As Integer = 0 To _ThreadBuff.Length - 1
                    _ThreadBuff(threadid).Start()
                Next
            End If

            If GetThreadStart() Then
                '_IsCycleflag = False
                theClient.Cycleflag = False
            End If
            If theClient.CmdStat Then
                If theClient.CmdReadStat Then
                    If theClient.CmdReadResult AndAlso Not theClient.Cycleflag Then
                        'SyncLock SendDataList
                        DetermineResults(_grid, theClient.Rowid, "PASS")

                        SendDataList.RemoveAt(0)
                        If theClient.SendData.Equals("SET_PPS_OUTP:OFF") Then
                            RaiseEvent TestEnd(True)
                        End If
                        'End SyncLock
                    Else
                        If theClient.SendNumber < theClient.Resendnum OrElse theClient.Cycleflag Then

                            Thread.Sleep(theClient.WaitIinterval)
                            _Uart.Write(theClient.SendData）
                            Console.WriteLine(theClient.SendData)
                            theClient.CmdStat = True
                            theClient.CmdReadStat = False
                            theClient.SendNumber += 2
                            theClient.SendDate = Now
                            If theClient.SendNumber = 100 Then theClient.SendNumber = 1
                            SetCommunicationData_txt("", Color.Black, $"重发({theClient.SendNumber})：" & theClient.SendData, Color.Blue)

                        Else

                            'SyncLock SendDataList
                            DetermineResults(_grid, theClient.Rowid, "FALSE")

                            SendDataList.RemoveAt(0)
                            'End SyncLock
                            If theClient.SendData.Equals("SET_PPS_OUTP:OFF") Then
                                RaiseEvent TestEnd(False)
                            End If
                        End If
                    End If
                Else
                    Dim Span As Double = theClient.SendIinterval * 10000
                    If (Now.Ticks - theClient.SendDate.Ticks) < Span Then
                        Continue While
                    Else

                        If theClient.SendNumber < theClient.Resendnum OrElse theClient.Cycleflag Then

                            Thread.Sleep(theClient.WaitIinterval)
                            _Uart.Write(theClient.SendData）
                            theClient.CmdStat = True
                            theClient.CmdReadStat = False
                            theClient.SendNumber += 1
                            theClient.SendDate = Now
                            Console.WriteLine(theClient.SendData)
                            If theClient.SendNumber = 100 Then theClient.SendNumber = 2
                            SetCommunicationData_txt("", Color.Black, $"重发({theClient.SendNumber})：" & theClient.SendData, Color.Blue)
                        Else
                            'SyncLock SendDataList
                            DetermineResults(_grid, theClient.Rowid, "FALSE")
                            SendDataList.RemoveAt(0)
                            If theClient.SendData.Equals("SET_PPS_OUTP:OFF") Then
                                RaiseEvent TestEnd(False)
                            End If
                            'End SyncLock
                        End If
                    End If
                End If

            Else
                _Uart.Write(theClient.SendData）
                theClient.CmdStat = True
                theClient.SendNumber += 1
                theClient.SendDate = Now
                SetCommunicationData_txt("", Color.Black, $"发送({theClient.SendNumber})：" & theClient.SendData, Color.Blue)
                Console.WriteLine(theClient.SendData)

            End If


        End While

    End Sub

    Private Function GetThreadStart() As Boolean
        Dim ruslt As Boolean = True
        For threadid As Integer = 0 To _ThreadBuff.Length - 1
            If _ThreadBuff(threadid).IsAlive Then
                ruslt = False
                Exit For
            End If
        Next
        Return ruslt
    End Function

    Delegate Sub delegate_SearchSetMAC_Change(Cmd As String, cmdcolor As Color, txt As String, txtcolor As Color)

    Public Sub SetCommunicationData_txt(Cmd As String, cmdcolor As Color, txt As String, txtcolor As Color)
        If _RichTextBox1.InvokeRequired Then
            Dim dev As New delegate_SearchSetMAC_Change(AddressOf SetCommunicationData_txt)
            _RichTextBox1.Invoke(dev, New Object() {Cmd, cmdcolor, txt, txtcolor})
        Else
            If String.IsNullOrEmpty(Cmd) Then

            End If
            With _RichTextBox1
                .SuspendLayout()
                .SelectionColor = Color.Black
                .AppendText($"{Date.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")} :")
                .SelectionColor = cmdcolor
                .AppendText($"{Cmd} ")
                .SelectionColor = txtcolor
                .AppendText(txt)
                .ResumeLayout(False)
            End With
        End If
    End Sub
    Public Sub UArtSendData(uartdata As Uart_1089)
        If _Uart.IsOpen Then
            ' _Uart.Write(uartdata.SendData)

            ' SyncLock SendDataList
            SendDataList.Add(uartdata)
            'End SyncLock
        Else
            ' MsgBox("串口未打开")
        End If

    End Sub


    Private Sub DetermineResults(tablegrid As FlexCell.Grid, trowel As Integer, result As String)
        'If trowel = 0 OrElse Not trowel < tablegrid.Rows Then Return False
        'If tablegrid.Cell(trowel, MainTest.ColNames.DataSource).Text.Trim.Equals("*IDN?") Then
        '    If result.ToUpper.Equals("PASS") Then
        '        'MTSetUILabeltext(_tooplabel,"测试板未连接！",Color .Black )
        '    End If
        'End If
        If tablegrid.Cell(trowel, MainTest.ColNames.RetryCount).Text.Trim.Equals("max") Then
            SettheGridt(tablegrid, MainTest.ColNames.TestResult, trowel, "PASS")
        Else
            SettheGridt(tablegrid, MainTest.ColNames.TestResult, trowel, result)
        End If
    End Sub


    Delegate Sub IPSetUILabeltext(tablegrid As FlexCell.Grid, tcol As Integer, trowel As Integer, txt As String)
    Private Sub SettheGridt(tablegrid As FlexCell.Grid, tcol As Integer, trowel As Integer, txt As String)
        If tablegrid.InvokeRequired Then
            tablegrid.Invoke(New IPSetUILabeltext(AddressOf SettheGridt), New Object() {tablegrid, tcol, trowel, txt})
        Else
            tablegrid.Cell(trowel, tcol).Text = txt
        End If
    End Sub


    '数据转换
    Public Function StringTobyte(sendstr As String) As Byte()
        Return System.Text.Encoding.ASCII.GetBytes(sendstr)
    End Function

    Public Sub SetCycleflagStop()
        _IsCycleflag = True
    End Sub
    Delegate Sub IPMTSetUILabeltext(ByRef ctl As ToolStripStatusLabel, txt As String, txtcolor As Color)
    Public Sub MTSetUILabeltext(ByRef ctl As ToolStripStatusLabel, txt As String, txtcolor As Color)
        If FrmMain.InvokeRequired Then
            FrmMain.Invoke(New IPMTSetUILabeltext(AddressOf MTSetUILabeltext), New Object() {ctl, txt, txtcolor})
        Else
            ctl.Text = txt
            ctl.ForeColor = txtcolor
        End If
    End Sub

End Class


