Imports System.Text
Imports System.Threading
Imports UTS_Core.DebugLog
Imports UTS_Core.UTSModule
Imports UTS_Core.UTSModule.DbConnect
Imports UTS_Core.UTSModule.DbTableModel.Customer
Imports UTS_Core.UTSModule.Station
Imports UTS_Core.UTSModule.Test
Imports UTS_Core.UTSModule.Test.Controls
Imports UTS_Core.UTSModule.Test.StatusMonitor

Public Class ZQ_Phobos_T1_FrmStationTest
#Region "框架部分 要放在最前段"
    Implements IProcessStation

    Private _utsApp As UtsAppForm
    Private _stationPlan As StationPackagePlan
    Public Sub Station_Changed() Implements IProcessStation.StationChanged
        ApplicationLog.WriteInfoLog($"编辑页面站位变更中，PN：{_utsApp.ProcessStation.ParentProject.Name} - SN:{_utsApp.ProcessStation.Name} - TP:{_utsApp.ProcessStation.Packet.Name}!")

        Try
            _stationPlan = CType(_utsApp.ProcessStation.Packet.StationPlan, StationPackagePlan)
        Catch ex As Exception
            MsgBox($"加载项目流程失败,{ex.Message}")
        End Try

        ' InitGrid(_stationPlan)

        ApplicationLog.WriteInfoLog($"编辑页面站位变更完成。")


    End Sub
    Public Sub ShowForm(parentControl As Control)
        FormBorderStyle = FormBorderStyle.None
        TopLevel = False
        Dock = DockStyle.Fill
        Parent = parentControl

        Show()
    End Sub
    Private Sub TheTestResults(dutSn As String, ispass As TestResult.TestResultEnum, datenow As Date, Optional FailMsg As RowNode = Nothing, Optional Customfield As Dictionary(Of String， String) = Nothing)

        '重置信息
        _utsApp.TestResult.ResetTestResult()
        '产线索引
        _utsApp.TestResult.ProductionLineID = -1
        '测试开始时间
        _utsApp.TestResult.StartTime = datenow
        _utsApp.TestResult.DUT_SN = dutSn
        _utsApp.TestResult.TestResult = ispass
        _utsApp.TestResult.UsedTime = Now - datenow
        If Not IsNothing(FailMsg) Then
            _utsApp.TestResult.FailSteps.Add(FailMsg)
        End If


        If Not IsNothing(Customfield) Then
            For indexptr As Integer = 0 To Customfield.Count - 1
                _utsApp.TestResult.AddCustomRecord($"{Customfield.Keys(indexptr)}", $"{Customfield.Values(indexptr)}")
            Next
        End If


        Try
            '提交测试记录,缺省参数默认为False，True则测试记录唯一,覆盖相同条码记录
            _utsApp.CommitTestResult(True)

            If ispass = TestResult.TestResultEnum.Pass Then
                TestStatusMonitor.TestStatus = StatusMonitor.TestStatusMonitor.TestStatusEnum.TestPass
            Else
                TestStatusMonitor.TestStatus = TestStatusMonitor.TestStatusEnum.TestFail
            End If
            TestStatusMonitor.TestStatus = TestStatusMonitor.TestStatusEnum.TestPass
        Catch ex As Exception
            ApplicationLog.WriteErrorLog($"写入称量数据失败：{ex.Message}")
            MsgBox($"写入称量数据失败：{ex.Message}")
            'LblResult.Text = "FAIL"
            'LblResult.ForeColor = Color.Red
            TestStatusMonitor.TestStatus = TestStatusMonitor.TestStatusEnum.TestFail
            Return
        End Try


    End Sub
    ''' <summary>
    ''' 初始化App
    ''' </summary>
    ''' <returns></returns>
    Private Function InitializeUtsApp() As Boolean
        _utsApp = UtsAppForm.CreateSingleton()
        _utsApp.AddStatisticsObserver(CType(Me, IProcessStation))

        Try
            If _utsApp.IsInitialized = False Then
                _utsApp.Initialize(ProcessStation.StationTypeEnum.Package) 'Todo:可根据需要限定可选站位
            End If
        Catch ex As Exception
            ApplicationLog.WriteErrorLog($"初始化窗体失败,原因：{ex.Message}!")

            MsgBox($"初始化窗体失败,原因：{ex.Message}")
            Close()
            Return False
        End Try
        Return True
    End Function

#End Region


#Region "界面控件初始化"

    ''' <summary>
    ''' 副测试类
    ''' </summary>
    Private _recordGrid1 As AttributeTest
    Private _recordGrid2 As AttributeTest
    Private _recordGrid3 As AttributeTest
    Private _recordGrid4 As AttributeTest
    ''' <summary>
    ''' 主测试类
    ''' </summary>
    Private _recordGrid5 As MainTest
    Private Sub ZQ_Phobos_T1_FrmStationTest_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        ApplicationLog.WriteInfoLog($"测试页面加载中。")
        If InitializeUtsApp() = False Then Return


        InitTest4Tack（）
        InitTestTable()
        InitUart5Tack()

    End Sub


    Public Sub InitTestTable()


        _UartClient = New Uart_1089_Client（SerialPort1, RichTextBox5, Grid5, Label17, _Test1Tack, _Test2Tack, _Test3Tack, _Test4Tack）
        ' AddHandler _UartClient.TestEnd, AddressOf UartClientTestEnd
        _recordGrid5 = New MainTest（Grid5）
        _recordGrid5.Userkeyval_Rictext = RichTextBox5
        _recordGrid5.Userkeyval_ComboBox = UartPort_cob
        _recordGrid5.Serial = SerialPort1
        _recordGrid5.Label2 = Label17
        OpenUart_btn.Tag = _recordGrid5



        _recordGrid4 = New AttributeTest(Grid4)
        _recordGrid4.cmdcolor = Color.MediumPurple
        _recordGrid4.txtcolor = Color.Purple
        _recordGrid4.Userkeyval_ComboBox = ComboBox1
        _recordGrid4.Userkeyval_Key = SerialPort2
        _recordGrid4.Userkeyval_ProgressBar = ProgressBar3
        _recordGrid4.Userkeyval_Rictext = RichTextBox3
        _recordGrid4.Userkeyval_Station = Label12
        _recordGrid4.Userkeyval_PASS = Label11
        _recordGrid4.Userkeyval_StepTip = Label10
        _recordGrid4.Userkeyval_Tip = Label9
        _recordGrid4.Userkeyval_check = CheckBox4
        Button2.Tag = _recordGrid4


        _recordGrid1 = New AttributeTest(Grid1)
        _recordGrid1.cmdcolor = Color.OrangeRed
        _recordGrid1.txtcolor = Color.Orange
        _recordGrid1.Userkeyval_ComboBox = ComboBox1
        _recordGrid1.Userkeyval_Key = SerialPort5
        _recordGrid1.Userkeyval_ProgressBar = ProgressBar4
        _recordGrid1.Userkeyval_Rictext = RichTextBox2
        _recordGrid1.Userkeyval_Station = Label16
        _recordGrid1.Userkeyval_PASS = Label15
        _recordGrid1.Userkeyval_StepTip = Label14
        _recordGrid1.Userkeyval_Tip = Label3
        _recordGrid1.Userkeyval_check = CheckBox3
        Button5.Tag = _recordGrid1

        _recordGrid2 = New AttributeTest(Grid2)
        _recordGrid2.cmdcolor = Color.YellowGreen
        _recordGrid2.txtcolor = Color.Green
        _recordGrid2.Userkeyval_ComboBox = ComboBox2
        _recordGrid2.Userkeyval_Key = SerialPort4
        _recordGrid2.Userkeyval_ProgressBar = ProgressBar1
        _recordGrid2.Userkeyval_Rictext = RichTextBox1
        _recordGrid2.Userkeyval_Station = Label4
        _recordGrid2.Userkeyval_PASS = Label3
        _recordGrid2.Userkeyval_StepTip = Label2
        _recordGrid2.Userkeyval_Tip = Label1
        _recordGrid2.Userkeyval_check = CheckBox1
        Button4.Tag = _recordGrid2


        _recordGrid3 = New AttributeTest(Grid3)
        _recordGrid3.cmdcolor = Color.CadetBlue
        _recordGrid3.txtcolor = Color.Blue
        _recordGrid3.Userkeyval_ComboBox = ComboBox3
        _recordGrid3.Userkeyval_Key = SerialPort3
        _recordGrid3.Userkeyval_ProgressBar = ProgressBar2
        _recordGrid3.Userkeyval_Rictext = RichTextBox4
        _recordGrid3.Userkeyval_Station = Label8
        _recordGrid3.Userkeyval_PASS = Label7
        _recordGrid3.Userkeyval_StepTip = Label6
        _recordGrid3.Userkeyval_Tip = Label5
        _recordGrid3.Userkeyval_check = CheckBox2
        Button3.Tag = _recordGrid3

        Button7.Tag = RichTextBox1
        Button9.Tag = RichTextBox2
        Button8.Tag = RichTextBox3
        Button6.Tag = RichTextBox4


        UartPort_cob.Tag = OpenUart_btn


        'ToolStripButton3.PerformClick()
    End Sub


    '#Region "统计图表显示"
    '    Public Sub UartClientTestEnd(ispass As Boolean)
    '        Dim Result As New TestResult
    '        Result.StartTime = Now
    '        Result.TestResult = TestResult.TestResultEnum.Pass
    '        If ispass Then
    '            If _recordGrid1.Userkeyval_check.Checked Then
    '                If Result.TestResult = TestResult.TestResultEnum.Pass AndAlso _recordGrid1.Userkeyval_TestTable.TestResult = TestResult.TestResultEnum.Pass Then
    '                    Result.TestResult = TestResult.TestResultEnum.Pass
    '                Else
    '                    Result.TestResult = TestResult.TestResultEnum.Fail
    '                End If
    '            End If
    '            If _recordGrid2.Userkeyval_check.Checked Then
    '                If Result.TestResult = TestResult.TestResultEnum.Pass AndAlso _recordGrid2.Userkeyval_TestTable.TestResult = TestResult.TestResultEnum.Pass Then
    '                    Result.TestResult = TestResult.TestResultEnum.Pass
    '                Else
    '                    Result.TestResult = TestResult.TestResultEnum.Fail
    '                End If

    '            End If
    '            If _recordGrid3.Userkeyval_check.Checked Then
    '                If Result.TestResult = TestResult.TestResultEnum.Pass AndAlso _recordGrid3.Userkeyval_TestTable.TestResult = TestResult.TestResultEnum.Pass Then
    '                    Result.TestResult = TestResult.TestResultEnum.Pass
    '                Else
    '                    Result.TestResult = TestResult.TestResultEnum.Fail
    '                End If
    '            End If
    '            If _recordGrid4.Userkeyval_check.Checked Then
    '                If Result.TestResult = TestResult.TestResultEnum.Pass AndAlso _recordGrid4.Userkeyval_TestTable.TestResult = TestResult.TestResultEnum.Pass Then
    '                    Result.TestResult = TestResult.TestResultEnum.Pass
    '                Else
    '                    Result.TestResult = TestResult.TestResultEnum.Fail
    '                End If
    '            End If
    '        Else
    '            Result.TestResult = TestResult.TestResultEnum.Fail
    '        End If

    '        AddBarChart(Result) '当前时测试总数绘制至图表
    '        AddPointChart(Result) '测试结果绘制至点阵图
    '        AddPieChart(Result) '测试结果绘制至饼状图
    '    End Sub
    '    ''' <summary>
    '    ''' 柱状图
    '    ''' </summary>
    '    ''' <param name="result"></param>
    '    Private Sub AddBarChart(result As TestResult)
    '        '填充内存
    '        Dim addBar As Boolean
    '        Dim tmp As BarChartResult
    '        If _barResults.Count > 0 Then
    '            If _barResults(_barResults.Count - 1).TimeEqual(result.StartTime) Then
    '                tmp = _barResults(_barResults.Count - 1)
    '            Else
    '                If result.StartTime.Hour = 0 Then
    '                    _barResults.Clear() '过零点则清空
    '                    TcBarPass.Clear()
    '                    TChart2.Clear()
    '                End If

    '                tmp = New BarChartResult(result.StartTime)
    '                _barResults.Add(tmp)

    '                If _barResults.Count > 8 Then '超过八个小时,移除前一小时数据
    '                    _barResults.RemoveAt(0)
    '                    addBar = False
    '                Else
    '                    addBar = True
    '                End If
    '            End If
    '        Else
    '            tmp = New BarChartResult(result.StartTime)
    '            _barResults.Add(tmp)
    '            addBar = True
    '        End If
    '        tmp.AddResult(result.TestResult = TestResult.TestResultEnum.Pass)

    '        '填充图表
    '        If addBar Then
    '            TcBarPass.Add(tmp.RecordTime, tmp.PassCount)
    '            TcBarFail.Add(tmp.RecordTime, tmp.FailCount)
    '        Else
    '            RedrawBarChart()
    '        End If

    '    End Sub
    '    ''' <summary>
    '    ''' 添加绘制测试结果
    '    ''' </summary>
    '    ''' <param name="result"></param>
    '    Private Sub AddPointChart(result As TestResult)
    '        Dim a As New PointChartResult With {.BarCode = result.DUT_SN}
    '        If result.TestResult = TestResult.TestResultEnum.Pass Then
    '            a.Result = True
    '            a.Color = _errCodeManager("9002").Color
    '        Else
    '            a.Result = False
    '            If _errCodeManager.IndexOf(result.ErrCode) <> -1 Then
    '                a.Color = _errCodeManager(result.ErrCode).Color
    '            Else
    '                a.Color = _errCodeManager("9001").Color
    '            End If
    '        End If
    '        _pointResults.Add(a)

    '        DrawPointChart(_pointResults.Count - 1) '从0开始
    '    End Sub
    '    Private Sub AddPieChart(result As TestResult)
    '        Dim code As String
    '        Dim msg As String
    '        Dim color As Color

    '        If result.TestResult = TestResult.TestResultEnum.Pass Then
    '            code = "PASS"
    '            msg = "测试通过"
    '            color = _errCodeManager("9002").Color
    '        Else
    '            If _errCodeManager.IndexOf(result.ErrCode) <> -1 Then
    '                code = result.ErrCode
    '                msg = _errCodeManager(result.ErrCode).Msg
    '                color = _errCodeManager(result.ErrCode).Color
    '            Else
    '                code = "9001"
    '                msg = _errCodeManager(code).Msg
    '                color = _errCodeManager(code).Color
    '            End If
    '        End If


    '        Dim addPie As Boolean = True
    '        For i As Integer = 0 To _pieResults.Count - 1
    '            If _pieResults(i).CodeEqual(code) Then
    '                _pieResults(i).AddResult()
    '                addPie = False
    '                Exit For
    '            End If
    '        Next

    '        If addPie Then
    '            Dim pieResult As New PieChartResult(code, msg, color)
    '            pieResult.AddResult()
    '            _pieResults.Add(pieResult)
    '        End If

    '        ReDrawPie()
    '    End Sub
    '#End Region



#Region "副测试线程初始化"

    Private _Test1Tack As Thread
    Private _Test2Tack As Thread
    Private _Test3Tack As Thread
    Private _Test4Tack As Thread
    Public Sub InitTest4Tack()

        _Test1Tack = New Thread(AddressOf RuningTest1)
        _Test2Tack = New Thread(AddressOf RuningTest2)
        _Test3Tack = New Thread(AddressOf RuningTest3)
        _Test4Tack = New Thread(AddressOf RuningTest4)
        _Test1Tack.IsBackground = False
        _Test2Tack.IsBackground = False
        _Test3Tack.IsBackground = False
        _Test4Tack.IsBackground = False

        '_Test1Tack.Start()
        '_Test2Tack.Start()
        '_Test3Tack.Start()
        '_Test4Tack.Start()

    End Sub

    Public Sub RuningTest1()
        Dim uartkeyval As AttributeTest = _recordGrid1
        Dim gridTable As FlexCell.Grid = uartkeyval.Userkeyval_grid
        ApplicationLog.WriteInfoLog($"开始执行测试流程:1。")

        ExecuteTheProcess(uartkeyval, gridTable)
        ApplicationLog.WriteInfoLog($"开始执行测试流程:1,测试结束")

    End Sub

    Public Sub RuningTest2()
        Dim uartkeyval As AttributeTest = _recordGrid2
        Dim gridTable As FlexCell.Grid = uartkeyval.Userkeyval_grid
        ApplicationLog.WriteInfoLog($"开始执行测试流程:2。")
        ExecuteTheProcess(uartkeyval, gridTable)
        ApplicationLog.WriteInfoLog($"开始执行测试流程:2,测试结束")
    End Sub

    Public Sub RuningTest3()
        Dim uartkeyval As AttributeTest = _recordGrid3
        Dim gridTable As FlexCell.Grid = uartkeyval.Userkeyval_grid
        ApplicationLog.WriteInfoLog($"开始执行测试流程:3。")
        ExecuteTheProcess(uartkeyval, gridTable)
        ApplicationLog.WriteInfoLog($"开始执行测试流程:3,测试结束")
    End Sub
    Public Sub RuningTest4()
        Dim uartkeyval As AttributeTest = _recordGrid4
        Dim gridTable As FlexCell.Grid = uartkeyval.Userkeyval_grid
        ApplicationLog.WriteInfoLog($"开始执行测试流程:4。")
        ExecuteTheProcess(uartkeyval, gridTable)
        ApplicationLog.WriteInfoLog($"开始执行测试流程:4,测试结束")
    End Sub

    Public Sub ExecuteTheProcess(uartkeyval As AttributeTest, gridTable As FlexCell.Grid)


        Dim buff() As String
        Dim Customfield As New Dictionary(Of String， String)
        Dim ColorBox As String = ""
        Dim node As New RowNode
        Dim Dut_SN As String = ""
        Dim datenow As Date = Now
        Dim exepath As String = "C:\Debug\AUTS_Ext_BarTenderConsole.exe"

        SetTestInformation(uartkeyval)

        If Not uartkeyval.Userkeyval_Key.IsOpen Then
            ApplicationLog.WriteInfoLog($"执行测试流程串口未打开,串口名：{uartkeyval.Userkeyval_Key.PortName}。测试结束")
            uartkeyval.SetAttriGridt(gridTable, 1, AttributeTest.ColNames.TestResult, "FALSE")


            Return
        End If

        SetTestTableAttri(uartkeyval.Userkeyval_TestTable)
        While uartkeyval.Userkeyval_check.Checked
            For rowid As Integer = 1 To gridTable.Rows
                Dim isrecord As String = gridTable.Cell(rowid, AttributeTest.ColNames.IsRecord).Text.Trim
                Dim celltxt As String = gridTable.Cell(rowid, AttributeTest.ColNames.DataSource).Text.Trim
                Dim attri As String = gridTable.Cell(rowid, AttributeTest.ColNames.OperatingMode).Text.Trim
                If isrecord.Equals("Y") Then
                    AddCustomRecordkeyval(uartkeyval, rowid, gridTable)
                End If
                If celltxt.Equals("设备") Then
                    Dim isnum As Integer = 0
                    While isnum < 5
                        If uartkeyval.GetDeviceData(rowid, attri) Then
                            uartkeyval.SetAttriGridt(gridTable, rowid, AttributeTest.ColNames.TestResult, "PASS")
                            uartkeyval.Userkeyval_TestTable.TestResult = TestResult.TestResultEnum.Pass
                            Continue For
                        Else
                            isnum += 1
                            Thread.Sleep(100)
                            Continue While
                        End If
                    End While
                    uartkeyval.SetAttriGridt(gridTable, rowid, AttributeTest.ColNames.TestResult, "FALSE")
                    uartkeyval.Userkeyval_TestTable.FailSteps.Add(GetFailSteps(rowid, gridTable))
                    uartkeyval.Userkeyval_TestTable.TestResult = TestResult.TestResultEnum.Fail
                    Continue While
                ElseIf celltxt.Equals("uts") Then
                    Dim result As String = _recordGrid5.GetUtsData(attri)
                    uartkeyval.SetAttriGridt(gridTable, rowid, AttributeTest.ColNames.TestVal, result)
                    If String.IsNullOrEmpty(result) Then
                        uartkeyval.SetAttriGridt(gridTable, rowid, AttributeTest.ColNames.TestResult, "FALSE")
                        uartkeyval.Userkeyval_TestTable.TestResult = TestResult.TestResultEnum.Fail
                        uartkeyval.Userkeyval_TestTable.FailSteps.Add(GetFailSteps(rowid, gridTable))
                        Continue While
                    Else
                        uartkeyval.SetAttriGridt(gridTable, rowid, AttributeTest.ColNames.TestResult, "PASS")
                        uartkeyval.Userkeyval_TestTable.TestResult = TestResult.TestResultEnum.Pass
                    End If
                ElseIf celltxt.Equals("设备-uts") Then
                    Dim devrow As String = gridTable.Cell(rowid, AttributeTest.ColNames.SendData).Text.Trim
                    Dim utsrow As String = gridTable.Cell(rowid, AttributeTest.ColNames.PassResult).Text.Trim
                    Dim devint As Integer = 0
                    Dim utsint As Integer = 0
                    Dim devDou As Double = 0
                    Dim utsDou As Double = 0
                    If Integer.TryParse(devrow, devint) AndAlso Integer.TryParse(devrow, devint) Then
                        If devint = 0 OrElse utsint = 0 Then
                            uartkeyval.SetAttriGridt(uartkeyval.Userkeyval_grid, rowid, AttributeTest.ColNames.TestVal, "数据获取失败")
                            uartkeyval.SetAttriGridt(uartkeyval.Userkeyval_grid, rowid, AttributeTest.ColNames.TestResult, "FALSE")
                            uartkeyval.Userkeyval_TestTable.TestResult = TestResult.TestResultEnum.Fail
                            uartkeyval.Userkeyval_TestTable.FailSteps.Add(GetFailSteps(rowid, gridTable))
                            Continue While
                        Else
                            devrow = gridTable.Cell(devint, AttributeTest.ColNames.TestVal).Text.Trim
                            utsrow = gridTable.Cell(utsint, AttributeTest.ColNames.TestVal).Text.Trim
                            If Double.TryParse(devrow, devDou) AndAlso Double.TryParse(utsrow, utsDou) Then
                                devDou = devDou - utsDou
                                utsrow = CType(devDou, String)
                                uartkeyval.SetAttriGridt(gridTable, rowid, AttributeTest.ColNames.TestVal, utsrow)
                                uartkeyval.SetAttriGridt(gridTable, rowid, AttributeTest.ColNames.TestResult, "PASS")
                                uartkeyval.Userkeyval_TestTable.TestResult = TestResult.TestResultEnum.Pass

                            Else
                                uartkeyval.SetAttriGridt(gridTable, rowid, AttributeTest.ColNames.TestVal, "数据获取失败")
                                uartkeyval.SetAttriGridt(gridTable, rowid, AttributeTest.ColNames.TestResult, "FALSE")
                                uartkeyval.Userkeyval_TestTable.TestResult = TestResult.TestResultEnum.Fail
                                uartkeyval.Userkeyval_TestTable.FailSteps.Add(GetFailSteps(rowid, gridTable))
                                Continue While
                            End If

                        End If
                    Else
                        uartkeyval.SetAttriGridt(gridTable, rowid, AttributeTest.ColNames.TestVal, "数据获取失败")
                        uartkeyval.SetAttriGridt(gridTable, rowid, AttributeTest.ColNames.TestResult, "FALSE")
                        uartkeyval.Userkeyval_TestTable.TestResult = TestResult.TestResultEnum.Fail
                        uartkeyval.Userkeyval_TestTable.FailSteps.Add(GetFailSteps(rowid, gridTable))
                        Continue While
                    End If
                End If
            Next
        End While

        uartkeyval.Userkeyval_TestTable.UsedTime = uartkeyval.Userkeyval_TestTable.StartTime - Now
        SaveTestLogToDatabase(uartkeyval.Userkeyval_TestTable)
        '

        ApplicationLog.WriteInfoLog($"测试页面测试结束。")
    End Sub
    ''' <summary>
    ''' 初始化副流程界面显示
    ''' </summary>
    ''' <param name="uartkeyval"></param>
    Public Sub SetTestInformation(uartkeyval As AttributeTest)
        uartkeyval.Userkeyval_ProgressBar.Maximum = uartkeyval.Userkeyval_grid.Rows - 1
        uartkeyval.Userkeyval_ProgressBar.Value = 0
        uartkeyval.Userkeyval_Station.Text = _utsApp.ProcessStation.Name
        uartkeyval.Userkeyval_PASS.Text = "------"
        uartkeyval.Userkeyval_PASS.BackColor = Color.Gray
        uartkeyval.Userkeyval_StepTip.Text = "------"
        uartkeyval.Userkeyval_Tip.Text = "------"
        uartkeyval.clearGridResult(uartkeyval.Userkeyval_grid)
    End Sub
    ''' <summary>
    ''' 初始化测试结果
    ''' </summary>
    ''' <param name="TestTable"></param>
    Public Sub SetTestTableAttri(ByRef TestTable As TestResult)
        TestTable.ResetTestResult()
        'TestTable.DUT_SN =""   '条码
        TestTable.AppName = Application.ProductName & Application.ProductVersion
        'TestTable.ErrCode =""      
        'TestTable.OrderID =""
        'TestTable.ProductionLineID =""

        TestTable.ServiceID = CInt(UtsRegistry.DataServiceIndex)
        TestTable.StartTime = Now
        TestTable.UserID = _utsApp.Account.UserId

    End Sub
    ''' <summary>
    ''' 添加自定义测试记录数据到入库集合
    ''' </summary>
    ''' <param name="uartkeyval"></param>
    ''' <param name="rowid"></param>
    ''' <param name="gridTable"></param>
    Public Sub AddCustomRecordkeyval(ByRef uartkeyval As AttributeTest, rowid As Integer, gridTable As FlexCell.Grid)
        Dim name As String = gridTable.Cell(rowid, AttributeTest.ColNames.RecordName).Text.Trim
        Dim val As String = gridTable.Cell(rowid, AttributeTest.ColNames.TestVal).Text.Trim
        uartkeyval.Userkeyval_TestTable.CustomRecord.Add(name, val)

    End Sub

    ''' <summary>
    ''' 获取失败信息
    ''' </summary>
    ''' <param name="rowid"></param>
    ''' <param name="gridTable"></param>
    ''' <returns></returns>
    Public Function GetFailSteps(rowid As Integer, gridTable As FlexCell.Grid) As RowNode
        Dim node As New RowNode
        node.RowListIndex = rowid
        node.Description = gridTable.Cell(rowid, AttributeTest.ColNames.Content).Text.Trim & ":" &
                          gridTable.Cell(rowid, AttributeTest.ColNames.TestVal).Text.Trim & "," &
                          gridTable.Cell(rowid, AttributeTest.ColNames.Lower).Text.Trim & "," &
                          gridTable.Cell(rowid, AttributeTest.ColNames.Upper).Text.Trim
        Return node
    End Function
    ''' <summary>
    '''  存储单笔测试记录至数据库
    ''' </summary>
    Private Sub SaveTestLogToDatabase(result As TestResult)
        If String.IsNullOrWhiteSpace(result.DUT_SN) Then Return '无SN不处理
        Try
            Dim tbName As String = TestLogTable.TableName(_utsApp.ProcessStation.ParentProject.Index, _utsApp.ProcessStation.StationID)
            DbConnector.SaveTestLog(tbName, _utsApp.ProcessStation, result)
        Catch ex As Exception
            ApplicationLog.WriteErrorLog($"保存测试结果至数据库失败：{ex.Message}")
            UtsMsgBox.ShowDialog($"保存测试结果至数据库失败:{ex.Message}")
        End Try
    End Sub
#End Region



#Region "串口线程初始化"
    ''' <summary>
    ''' 串口
    ''' </summary>
    Public _UartClient As Uart_1089_Client
    ''' <summary>
    ''' 线程
    ''' </summary>
    Private _Uart1Tack As Thread
    Private _Uart2Tack As Thread
    Private _Uart3Tack As Thread
    Private _Uart4Tack As Thread
    Private _Uart5Tack As Thread

    Public Sub InitUart5Tack()

        _Uart1Tack = New Thread(AddressOf ReadUart1DataThread)
        _Uart2Tack = New Thread(AddressOf ReadUart2DataThread)
        _Uart3Tack = New Thread(AddressOf ReadUart3DataThread)
        _Uart4Tack = New Thread(AddressOf ReadUart4DataThread)
        _Uart5Tack = New Thread(AddressOf ReadUart5DataThread)
        _Uart1Tack.IsBackground = False
        _Uart2Tack.IsBackground = False
        _Uart3Tack.IsBackground = False
        _Uart4Tack.IsBackground = False
        _Uart5Tack.IsBackground = False


        _Uart1Tack.Start()
        _Uart2Tack.Start()
        _Uart3Tack.Start()
        _Uart4Tack.Start()
        _Uart5Tack.Start()


    End Sub


    Public Function UartStateSelection1(rowid As Integer, readStr As String, uartkeyval As MainTest) As Boolean
        Dim cmdcolor As Color = Color.Gray
        Dim txtcolor As Color = Color.Red
        Dim cmd As String = ""
        Dim txt As String = readStr
        SetCommunicationData_txt(uartkeyval.Userkeyval_Rictext, cmd, cmdcolor, txt, txtcolor)
        Return uartkeyval.ParsingRowRead(rowid， readStr.Trim)

    End Function
    Public Sub ReadUart1DataThread()


        Dim uartkeyval As MainTest = _recordGrid5

        Dim readStr As String
        Dim bufflen As Integer
        Dim readUartStr As String = ""
        Dim uartport As IO.Ports.SerialPort = uartkeyval.Serial

        While True
            Try
                If Not uartport.IsOpen Then Continue While
                bufflen = uartport.BytesToRead
                If uartport.BytesToRead > 0 Then
                    Dim therecvBuffer(bufflen) As Byte
                    uartport.Read(therecvBuffer, 0, bufflen)
                    readStr = Encoding.GetEncoding("GBK").GetString(therecvBuffer)

                    If readStr.Equals(vbNullChar) Then Continue While
                    readUartStr = readUartStr & readStr
                    readUartStr = readUartStr.Replace（vbNullChar, ""）

                    If readUartStr.Substring(readUartStr.Length - 2).Equals(vbCrLf) Then
                        Dim Uartdata As Uart_1089 = _UartClient.SendDataList.Item(0)

                        Dim Span As Double = Uartdata.SendIinterval * 10000
                        If (Now.Ticks - Uartdata.SendDate.Ticks) < Span Then
                            If UartStateSelection1（Uartdata.Rowid， readUartStr, uartkeyval） Then
                                Uartdata.CmdReadStat = True
                                Uartdata.CmdReadResult = True
                            Else
                                Uartdata.CmdReadStat = True
                                Uartdata.CmdReadResult = False
                            End If
                            readUartStr = ""
                        Else
                            readUartStr = ""
                            Continue While
                        End If

                    End If
                Else
                    Continue While
                End If

            Catch ex As Exception
                SetopenUartshow(OpenUart_btn)
            End Try
        End While

    End Sub

    Delegate Sub theSetopenUartshow(btn As Button)
    Public Sub SetopenUartshow(btn As Button)
        If btn.InvokeRequired Then
            Dim dev As New theSetopenUartshow(AddressOf SetopenUartshow)
            btn.Invoke(dev, New Object() {btn})
        Else
            btn.Text = "打开串口"
            btn.BackColor = Color.LightGray
        End If
    End Sub

    Public Sub ReadUart2DataThread()

        'If Not _ThreadUserkeyval_Dic.ContainsKey(Thread.ManagedThreadId) Then Return
        Dim uartkeyval As AttributeTest = _recordGrid1
        'If IsNothing(uartkeyval) Then Return
        Dim readStr As String
        Dim bufflen As Integer
        Dim readUartStr As String = ""
        Dim uartport As IO.Ports.SerialPort = uartkeyval.Userkeyval_Key

        While True
            Try
                If Not uartport.IsOpen Then Continue While
                bufflen = uartport.BytesToRead
                If uartport.BytesToRead > 0 Then
                    Dim therecvBuffer(bufflen) As Byte
                    uartport.Read(therecvBuffer, 0, bufflen)
                    readStr = Encoding.GetEncoding("GBK").GetString(therecvBuffer)

                    If readStr.Equals(vbNullChar) Then Continue While
                    readUartStr = readUartStr & readStr
                    readUartStr = readUartStr.Replace（vbNullChar, ""）

                    If readUartStr.Substring(readUartStr.Length - 2).Equals(vbCrLf) Then

                        UartStateSelection（readUartStr, uartkeyval）

                        readUartStr = ""

                    End If
                Else
                    Continue While
                End If

            Catch ex As Exception
                SetopenUartshow(Button5)
            End Try
        End While

    End Sub
    Public Sub ReadUart3DataThread()

        'If Not _ThreadUserkeyval_Dic.ContainsKey(Thread.ManagedThreadId) Then Return
        Dim uartkeyval As AttributeTest = _recordGrid2
        'If IsNothing(uartkeyval) Then Return
        Dim readStr As String
        Dim bufflen As Integer
        Dim readUartStr As String = ""
        Dim uartport As IO.Ports.SerialPort = uartkeyval.Userkeyval_Key

        While True
            Try
                If Not uartport.IsOpen Then Continue While
                bufflen = uartport.BytesToRead
                If uartport.BytesToRead > 0 Then
                    Dim therecvBuffer(bufflen) As Byte
                    uartport.Read(therecvBuffer, 0, bufflen)
                    readStr = Encoding.GetEncoding("GBK").GetString(therecvBuffer)

                    If readStr.Equals(vbNullChar) Then Continue While
                    readUartStr = readUartStr & readStr
                    readUartStr = readUartStr.Replace（vbNullChar, ""）

                    If readUartStr.Substring(readUartStr.Length - 2).Equals(vbCrLf) Then

                        UartStateSelection（readUartStr, uartkeyval）

                        readUartStr = ""

                    End If
                Else
                    Continue While
                End If

            Catch ex As Exception
                SetopenUartshow(Button4)
            End Try
        End While

    End Sub
    Public Sub ReadUart4DataThread()

        'If Not _ThreadUserkeyval_Dic.ContainsKey(Thread.ManagedThreadId) Then Return
        Dim uartkeyval As AttributeTest = _recordGrid3
        'If IsNothing(uartkeyval) Then Return
        Dim readStr As String
        Dim bufflen As Integer
        Dim readUartStr As String = ""
        Dim uartport As IO.Ports.SerialPort = uartkeyval.Userkeyval_Key

        While True
            Try
                If Not uartport.IsOpen Then Continue While
                bufflen = uartport.BytesToRead
                If uartport.BytesToRead > 0 Then
                    Dim therecvBuffer(bufflen) As Byte
                    uartport.Read(therecvBuffer, 0, bufflen)
                    readStr = Encoding.GetEncoding("GBK").GetString(therecvBuffer)

                    If readStr.Equals(vbNullChar) Then Continue While
                    readUartStr = readUartStr & readStr
                    readUartStr = readUartStr.Replace（vbNullChar, ""）

                    If readUartStr.Substring(readUartStr.Length - 2).Equals(vbCrLf) Then

                        UartStateSelection（readUartStr, uartkeyval）

                        readUartStr = ""

                    End If
                Else
                    Continue While
                End If

            Catch ex As Exception
                SetopenUartshow(Button3)
            End Try
        End While

    End Sub
    Public Sub ReadUart5DataThread()

        ' If Not _ThreadUserkeyval_Dic.ContainsKey(Thread.ManagedThreadId) Then Return
        Dim uartkeyval As AttributeTest = _recordGrid4
        'If IsNothing(uartkeyval) Then Return
        Dim readStr As String
        Dim bufflen As Integer
        Dim readUartStr As String = ""
        Dim uartport As IO.Ports.SerialPort = uartkeyval.Userkeyval_Key
        Dim isflag As Boolean = True
        While True
            Try
                If Not uartport.IsOpen Then Continue While
                'Thread .Sleep (1000)
                'If isflag Then
                'uartport.Write("[KeyLeft] -> [0]" & vbCrLf)
                'SetCommunicationData_txt(uartkeyval.Userkeyval_Rictext, "KeyLeft", Color .Red , "0", Color .Yellow )
                'isflag=False 
                'End If

                bufflen = uartport.BytesToRead
                If uartport.BytesToRead > 0 Then
                    Dim therecvBuffer(bufflen) As Byte
                    uartport.Read(therecvBuffer, 0, bufflen)
                    readStr = Encoding.GetEncoding("GBK").GetString(therecvBuffer)

                    If readStr.Equals(vbNullChar) Then Continue While
                    readUartStr = readUartStr & readStr
                    readUartStr = readUartStr.Replace（vbNullChar, ""）

                    If readUartStr.Substring(readUartStr.Length - 2).Equals(vbCrLf) Then
                        'isflag=True 
                        UartStateSelection（readUartStr, uartkeyval）

                        readUartStr = ""

                    End If
                Else
                    Continue While
                End If

            Catch ex As Exception
                SetopenUartshow(Button2)
            End Try
        End While

    End Sub

    Public Sub UartStateSelection(readStr As String, uartkeyval As AttributeTest)
        Dim cmdcolor As Color = Color.Gray
        Dim txtcolor As Color = Color.Red
        Dim cmd As String = ""
        Dim txt As String = readStr
        Dim reaDcmdbuff() As String

        reaDcmdbuff = readStr.Trim.Replace(vbCrLf, "").Replace("->", vbCrLf).Split(CType(vbCrLf, Char))
        If reaDcmdbuff.Length = 2 Then
            cmd = GetAttributeValue(reaDcmdbuff(0))
            If cmd.ToLower.Equals("mac") Then
                uartkeyval.Val_mac = GetAttributeValue(reaDcmdbuff(1))
            ElseIf cmd.ToLower.Equals("version") Then
                uartkeyval.Val_version = GetAttributeValue(reaDcmdbuff(1))
            ElseIf cmd.ToLower.Equals("voltage") Then
                uartkeyval.Val_voltage = GetAttributeValue(reaDcmdbuff(1))
            ElseIf cmd.ToLower.Equals("humiture") Then
                Dim temp() As String = reaDcmdbuff(1).Trim.Split(CType(",", Char))
                For ptrstr As Integer = 0 To temp.Length - 1
                    If temp(ptrstr).Trim.Contains("temperature") Then
                        uartkeyval.Val_tempre = GetAttributeValue(temp(ptrstr))
                    ElseIf temp(ptrstr).Trim.Contains("humidity") Then
                        uartkeyval.Val_humiture = GetAttributeValue(temp(ptrstr))
                    End If
                Next

            ElseIf cmd.ToLower.Equals("keyleft") Then
                uartkeyval.Val_keyleft = GetAttributeValue(reaDcmdbuff(1))
            ElseIf cmd.ToLower.Equals("keyright") Then
                uartkeyval.Val_keyright = GetAttributeValue(reaDcmdbuff(1))
            ElseIf cmd.ToLower.Equals("pir") Then
                uartkeyval.Val_pir = GetAttributeValue(reaDcmdbuff(1))
            Else
                txt = reaDcmdbuff(1)
                SetCommunicationData_txt(uartkeyval.Userkeyval_Rictext, cmd, cmdcolor, txt, txtcolor)
                Return
            End If

            cmdcolor = uartkeyval.cmdcolor
            txtcolor = uartkeyval.txtcolor
            txt = UartCmdStateMachine(reaDcmdbuff(1))

        End If
        SetCommunicationData_txt(uartkeyval.Userkeyval_Rictext, cmd, cmdcolor, txt, txtcolor)
    End Sub

    Public Function UartCmdStateMachine(ptr As String) As String
        Dim ptrbuff（） As String = ptr.Trim.Split(CType(",", Char))
        Dim result As String = ""

        For Each ptrindex As String In ptrbuff
            result = result & GetAttributeValue(ptrindex) & ","
        Next
        Return result.Substring(0, result.Length - 1)

    End Function

    Public Function GetAttributeValue(ptr As String) As String
        Dim ptrleft As Integer = ptr.IndexOf("[")
        Dim ptrright As Integer = ptr.IndexOf("]")
        Dim strlen As Integer = ptrright - ptrleft
        If strlen = 0 Then Return ""
        Dim result As String = ptr.Substring(ptrleft + 1, strlen - 1)
        Return result

    End Function
    Delegate Sub delegate_SearchSetMAC_Change(rictext As RichTextBox, Cmd As String, cmdcolor As Color, txt As String, txtcolor As Color)

    Public Sub SetCommunicationData_txt(rictext As RichTextBox, 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)
            rictext.Invoke(dev, New Object() {rictext, Cmd, cmdcolor, txt, txtcolor})
        Else
            If String.IsNullOrEmpty(Cmd) Then

            End If
            With rictext
                .SuspendLayout()
                .SelectionColor = Color.Black
                .AppendText($"接收 {Date.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")} :")
                .SelectionColor = cmdcolor
                .AppendText($"{Cmd} ")
                .SelectionColor = txtcolor
                .AppendText(txt & vbCrLf)
                .ResumeLayout(False)

            End With
        End If
    End Sub

    Private Sub UartPort_cob_DropDown(sender As Object, e As EventArgs) Handles UartPort_cob.DropDown, ComboBox4.DropDown, ComboBox3.DropDown, ComboBox2.DropDown, ComboBox1.DropDown
        Dim portNames As String() = System.IO.Ports.SerialPort.GetPortNames       '获得可用串口
        Array.Sort(portNames)
        UartPort_cob.Items.Clear()
        UartPort_cob.Items.AddRange(portNames)
        If Not SerialPort1.IsOpen Then
            UartPort_cob.SelectedIndex = 0
        End If

        ComboBox1.Items.Clear()
        ComboBox1.Items.AddRange(portNames)
        If Not SerialPort5.IsOpen Then
            ComboBox1.SelectedIndex = 0
        End If

        ComboBox2.Items.Clear()
        ComboBox2.Items.AddRange(portNames)
        If Not SerialPort4.IsOpen Then
            ComboBox2.SelectedIndex = 0
        End If
        ComboBox3.Items.Clear()
        ComboBox3.Items.AddRange(portNames)
        If Not SerialPort3.IsOpen Then
            ComboBox3.SelectedIndex = 0
        End If
        ComboBox1.Items.Clear()
        ComboBox1.Items.AddRange(portNames)
        If Not SerialPort2.IsOpen Then
            ComboBox1.SelectedIndex = 0
        End If
    End Sub

    Private Sub Button6_Click(sender As Object, e As EventArgs) Handles Button9.Click, Button8.Click, Button7.Click, Button6.Click
        Dim btn As Button = CType(sender, Button)
        Dim ric As RichTextBox = CType(btn.Tag, RichTextBox)
        ric.Clear()
    End Sub

#End Region

#Region "控件事件"


#End Region




#End Region
End Class



