
Imports System.Drawing.Printing
Imports System.Globalization
Imports System.IO.Ports
Imports System.IO
Imports System.Net
Imports System.Text
Imports System.Threading
Imports Newtonsoft.Json
Imports OpenCvSharp
Imports OpenCvSharp.Extensions

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.Command
Imports UTS_Core.UTSModule.Test.Command.ProcessCommand
Imports UTS_Core.UTSModule.Test.Controls
Imports UTS_Core.UTSModule.Test.StatusMonitor



Public Class ZQ_Mars_P1_FrmStationTest
    ' Implements IProcessfilechanged
    Implements IProcessStation
    Private _utsApp As UtsAppForm
    Private _stationPlan As StationPackagePlan
    Private PrintfNum As Integer = 0
    Private Printfcnt As Integer = 0
    Private _DummyVardic As Dictionary(Of String, Integer（））


    Dim g_TotolCnt As UInt64 = 0
    Dim g_ThisTimeCnt As UInt64 = 0
    Dim g_DUT_PortName As String = ""


    ' Private g_FileNameWsFullPatch As String = Application.StartupPath & "\Template\"
    'Private g_FileName As String
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

        CheckForIllegalCrossThreadCalls = False '禁用跨线程检查，简化跨线程操作’
        g_ThisTimeCnt = 0


        My.Settings.Reload()

        g_TotolCnt = CType(My.Settings.Total_Cnt， UInt64)
        g_DUT_PortName = My.Settings.DUT_PortName

        lab_Processed_Unit_Cnt.Text = g_TotolCnt.ToString
        tsl_DUT_PortSataus.Text = g_DUT_PortName

        tb_DUT_Msg.Text = ""
        tb_MAC_sent_to_ezCAD.Text = ""
        lab_Processed_Unit_Cnt_ThisCycle.Text = g_ThisTimeCnt.ToString


        ListBox1.Items.Clear()

        If String.IsNullOrEmpty(g_DUT_PortName) = False Then
            Open_Comport(Commport_DUT, g_DUT_PortName)
        End If
        UpdateDutPortStatus()

        TIM_DUT_TASK.Enabled = True
        TIM_Find_DUT_Port.Enabled = True
        TIM_CNT_CLEAR.Enabled = True
        TIM_PRINT_LABEL_TASK.Enabled = True
        TIM_DUT_TASK.Start()
        TIM_Find_DUT_Port.Stop()
        TIM_CNT_CLEAR.Start()
        TIM_PRINT_LABEL_TASK.Start()


        tips.SetToolTip(lab_Processed_Unit_Cnt, "本次生产累计打标数量，连续点击 5 次清零！")
        tips.SetToolTip(lab_Processed_Unit_Cnt_ThisCycle, "本次启动程序累计打标数量，连续点击 5 次清零！")


        ApplicationLog.WriteInfoLog($"测试页面加载中。")
        '创建资源文件夹
        If Not IO.Directory.Exists("C:\AUTS\Barcode\Mars\") Then
            IO.Directory.CreateDirectory("C:\AUTS\Barcode\Mars\")
        End If



        'If Not IO.Directory.Exists(g_FileNameWsFullPatch) Then
        '    IO.Directory.CreateDirectory(g_FileNameWsFullPatch)
        'End If
        '初始化UTS窗体信息,失败则关闭窗体
        If InitializeUtsApp() = False Then Return

        InitializeForm()

    End Sub
    Private Sub RichTextBox1_TextChanged(sender As Object, e As EventArgs) Handles RichTextBox1.TextChanged
        RichTextBox1.SelectionStart = RichTextBox1.TextLength
        RichTextBox1.ScrollToCaret()

    End Sub
    Delegate Sub IPSetRichTextBox1Text(TextBox1 As RichTextBox, text As String， txtcolor As Color)
    Private Sub SetRichTextBox1Text(TextBox1 As RichTextBox, text As String， txtcolor As Color)
        If InvokeRequired = True Then
            Dim dev As New IPSetRichTextBox1Text(AddressOf SetRichTextBox1Text)
            Me.Invoke(dev, New Object() {TextBox1, text, txtcolor})
        Else



            With TextBox1
                .SuspendLayout()

                .SelectionColor = txtcolor

                .AppendText(text & vbCrLf)
                .ResumeLayout(False)
            End With

        End If


    End Sub
    Public Function AccessApi（pwd As String， code As String, dbName As String, ProjectID As String） As String
        Dim jsonString As String = String.Empty
        Try
            jsonString = PostData("http://uts-data.com/CommonApi/AllocationBarcode", $"Pwd={pwd}&Barcode={code}&DBName={dbName}&ProjectID={ProjectID}")
        Catch ex As Exception
            MsgBox($"{ex.Message}！请联系管理员")
        End Try
        Console.WriteLine(jsonString)

        If jsonString = Nothing Then
            Return "False"
        End If
        Dim login As JsonAccessApi = JsonConvert.DeserializeObject(Of JsonAccessApi)(jsonString)
        Return login.Mars_ColorBox_BarCode

    End Function
    ''' <summary>
    ''' Post请求
    ''' </summary>
    ''' <param name="url"></param>
    ''' <param name="data"></param>
    ''' <returns></returns>
    Public Shared Function PostData(ByVal url As String, ByVal data As String) As String

        ServicePointManager.Expect100Continue = False
        Dim request As HttpWebRequest = CType(WebRequest.Create(url), HttpWebRequest)
        '//Post请求方式
        request.Method = "POST"

        '内容类型
        request.ContentType = "application/x-www-form-urlencoded"
        '将URL编码后的字符串转化为字节
        Dim encoding As New UTF8Encoding()
        Dim bys As Byte() = encoding.GetBytes(data)
        '设置请求的 ContentLength 
        request.ContentLength = bys.Length
        '获得请 求流
        Dim newStream As Stream = request.GetRequestStream()
        newStream.Write(bys, 0, bys.Length)
        newStream.Close()
        '获得响应流
        Dim sr As StreamReader = New StreamReader(request.GetResponse().GetResponseStream)
        Return sr.ReadToEnd
    End Function
    Private Sub InitializeForm()
        'Todo:初始化窗体代码

        InitBarcodeGrid()


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

        Show()
    End Sub

    ''' <summary>
    ''' 站位变化
    ''' </summary>
    Public Sub Station_Changed() Implements IProcessStation.StationChanged
        'Todo:站位变化代码
        ApplicationLog.WriteInfoLog($"测试页面站位变更中，PN：{_utsApp.ProcessStation.ParentProject.Name} - SN:{_utsApp.ProcessStation.Name} - TP:{_utsApp.ProcessStation.Packet.Name}!")

        _stationPlan = CType(_utsApp.ProcessStation.Packet.StationPlan, StationPackagePlan)
        ' lab_imger.Image = Nothing
        Dim revStationPlanPath As String = UtsPath.GetStationPacketResourceDirPath(_stationPlan.ParentPacket.Name)
        Select Case _utsApp.ProcessStation.ParentProject.Index
            Case 1
                'lab_imger.Image = Image.FromFile(revStationPlanPath & "\Mars.png")
                If File.Exists(revStationPlanPath & "\Mars.png") Then
                    'lab_imger.Image = Image.FromFile(revStationPlanPath & "\Mars.png")
                End If
            Case 2
                If File.Exists(revStationPlanPath & "\Phobos.png") Then
                    'lab_imger.Image = Image.FromFile(revStationPlanPath & "\Phobos.png")
                End If
        End Select



        '清除表格数据
        InitBarcodeGrid()

        ApplicationLog.WriteInfoLog($"测试页面站位变更完成!")
    End Sub
    Public DicBarTender As Dictionary(Of String, Integer())
    Private Sub InitBarcodeGrid()
        'GrdPriview = New FlexCell.Grid
        If IsNothing(_stationPlan) Then
            Return
        End If
        'Dim tmpPath As String = Application.StartupPath & "\Template\" & _stationPlan.TemplateFile
        Dim tmpPath As String = $"C:\AUTS\Barcode\Phobos\{_stationPlan.TemplateFile}"

        If IO.File.Exists(tmpPath) Then
            txt_template.Text = tmpPath


            'If GrdPriview.OpenFile(tmpPath) Then
            '    DicBarTender = ReplaceCelltext(GrdPriview)
            'Else
            '    MsgBox("文件打开失败")
            'End If
        End If

    End Sub

    Private Function InitializeUtsApp() As Boolean
        '_utsApp.ProcessStation.Packet.StationPlan
        _utsApp = UtsAppForm.CreateSingleton()
        _utsApp.AddStatisticsObserver(Me)

        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




    '获取模板伪变量
    Public Function ReplaceCelltext(ByRef gird As FlexCell.Grid) As Dictionary(Of String, Integer())
        Dim BarTender As New Dictionary(Of String, Integer())
        For rowid As Integer = 1 To gird.Rows - 1
            For colid As Integer = 1 To gird.Cols - 1
                If gird.Cell(rowid, colid).MergeCell Then
                    If String.IsNullOrEmpty(gird.Cell(rowid, colid).Text.Trim) Then Continue For
                    If BarTender.ContainsKey(gird.Cell(rowid, colid).Text.Trim) Then
                        MsgBox("警告：模板伪变量重复命名,设置将忽视靠后变量。")
                        Continue For
                    End If
                    BarTender.Add(gird.Cell(rowid, colid).Text.Trim.ToLower, {rowid, colid})
                End If
            Next
        Next


        Return BarTender
    End Function


    Public Sub SetBarTendertoGrid（ByRef gird As FlexCell.Grid, BarTender As Dictionary(Of String, Integer()））

        'Dim cellxy() As Integer
        'If BarTender.ContainsKey("{QRCode1}".ToLower ) Then

        '    cellxy = BarTender.Item("{QRCode1}".ToLower)
        '    gird.Cell(cellxy(0), cellxy(0)).Text = DevCode_txt.Text
        '     'gird.Selection.CellType = FlexCell.CellTypeEnum.QRCode 
        'End If
        'If BarTender.ContainsKey("{BarCode1}".ToLower) Then
        '    cellxy = BarTender.Item("{BarCode1}".ToLower)
        '    'cellxy = BarTender.Item("{BarCode1}".ToLower)
        '    gird.Cell(cellxy(0), cellxy(0)).Text = EnclosureCode_txt.Text
        '    'gird.Selection.CellType = FlexCell.CellTypeEnum.BarCode
        'End If

        'GrdPriview.Print 
    End Sub
    Public Function TestPrintf(filepath As String， dic As Dictionary(Of String， String), devname As String) As String


        'Try
        '    Dim btEngine As Engine = New Engine(True)
        '    btEngine.Start()
        '    Dim btFormat As LabelFormatDocument = btEngine.Documents.Open(filepath)

        '    '  btFormat.SubStrings("QRcode"）.Value = "98654613" '对模版相应字段进行赋值e
        '    For Each keyval As KeyValuePair（Of String， String） In dic
        '        Try
        '            btFormat.SubStrings(keyval.Key）.Value = keyval.Key  '对模版相应字段进行赋值e
        '        Catch ex As Exception
        '            MsgBox（$"False:未找到 {keyval.Key} 的打印索引位置，打印失败。请检查参数与打印模板标签是否一致。"）
        '            Return $"False:未找到 {keyval.Key} 的打印索引位置，打印失败。请检查参数与打印模板标签是否一致。"
        '        End Try
        '    Next


        '    btFormat.PrintSetup.PrinterName = devname      '  //寻找打印机
        '    Dim snames As PrinterSettings.StringCollection = PrinterSettings.InstalledPrinters

        '    Dim PrintIsExist As Boolean = False
        '    Dim logPringter As String = ""


        '    For Each Name As String In snames
        '        logPringter = logPringter & Name & ";"
        '        If Name.ToLower.Trim = devname.ToLower().Trim() Then
        '            PrintIsExist = True
        '            Exit For
        '        End If
        '    Next

        '    'Console.WriteLine("搜索的打印机有" + logPringter)
        '    If Not PrintIsExist Then
        '        MsgBox("False:未找到打印机打印失败！")
        '        Return "False:未找到打印机打印失败！"
        '    Else

        '        ' Console.WriteLine("开始打印")
        '        If btFormat.Print() <> 0 Then
        '            MsgBox("False:打印失败！")
        '            Return "False:打印失败！"
        '        End If
        '        ' Console.WriteLine("打印成功,开始关闭引擎")
        '        btEngine.Stop()
        '        'Console.WriteLine("开始关闭引擎")
        '    End If




        'Catch ex As Exception
        '    MsgBox("打印异常退出，" & ex.Message)
        '    Return "False:打印异常退出，" & ex.Message
        '    'Console.WriteLine("打印异常退出，" & ex.Message)
        'End Try


    End Function






    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        'GrdPriview.PrintPreview()
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles btn_Print.Click
        If _utsApp.ProcessStation Is Nothing Then
            MsgBox($"请选择项目与测试站后再尝试录入！")
            Return
        End If

        If String.IsNullOrEmpty(txt_template.Text) Then
            MsgBox($"未选择打印模板，请先选择打印模板在测试")
            Return
        End If
        If String.IsNullOrEmpty(DevCode_txt.Text) Then
            MsgBox($"无效的机身码[{DevCode_txt.Text}],请重新录入")
            Return
        End If





        ApplicationLog.WriteInfoLog($"打印条码完成,机身码:{DevCode_txt.Text }")
        '设置焦点
        DevCode_txt.Focus()
        DevCode_txt.SelectAll()


        Dim theE As New PreviewKeyDownEventArgs（Keys.Enter）
        DevCode_txt_PreviewKeyDown(Nothing, theE)


        'btn_Print.Enabled = True
        ''打印
        'If _stationPlan.AutoPrint Then
        '    GrdPriview.Print()
        'End If



    End Sub

    Private Sub Button3_Click(sender As Object, e As EventArgs)

        'Try


        '    Dim dlg As New OpenFileDialog

        '    dlg.InitialDirectory = Application.StartupPath
        '    dlg.Filter = "uts BarCode Template File (*.utsbct)|*.utsbct| All Files|*.*||"

        '    If System.IO.File.Exists(g_FileNameWsFullPatch) Then
        '        dlg.InitialDirectory = System.IO.Path.GetDirectoryName(g_FileNameWsFullPatch)
        '        dlg.FileName = g_FileNameWsFullPatch
        '    Else
        '        dlg.InitialDirectory = Application.StartupPath
        '    End If

        '    If dlg.ShowDialog() = Windows.Forms.DialogResult.OK Then
        '        'g_FileNameWsFullPatch = dlg.FileName '& ".utsbct"
        '        txt_template.Text = dlg.FileName
        '        Grid1.OpenFile(dlg.FileName)
        '        g_FileName = dlg.FileName
        '    End If

        'Catch ex As Exception
        '    MsgBox("打开文件失败！")
        'End Try
        '' updateWindowTitle()
        '_DummyVardic = ReplaceCelltext(Grid1)
    End Sub




    Private Sub DevCode_txt_PreviewKeyDown(sender As Object, e As PreviewKeyDownEventArgs) Handles DevCode_txt.PreviewKeyDown, TextBox1.PreviewKeyDown
        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 = $"{UtsPath.GetStationPacketResourceDirPath(_stationPlan.ParentPacket.Name)}\{_stationPlan.CompanyLogo}"
        Dim codelab As String = ""

        If e.KeyData = Keys.Enter Then

            ' buff = DevCode_txt.Text.Trim.Split(CType("/", Char))
            If DevCode_txt.Text.Length = 12 Then
                ColorBox = AccessApi("actop00803", DevCode_txt.Text.Trim, "uts_zongqing", _utsApp.ProcessStation.ParentProject.Index.ToString)
                EnclosureCode_txt.Text = ColorBox
                TextBox1.Text = DevCode_txt.Text.Trim
                'If GetTheColorBoxCode(DevCode_txt.Text， Dut_SN) Then
                If Not String.IsNullOrEmpty(_stationPlan.CompanyName) Then
                    codelab = codelab & $"{_stationPlan.CompanyName}={EnclosureCode_txt.Text },"
                End If
                If Not String.IsNullOrEmpty(_stationPlan.BoxMumEditKey) Then
                    codelab = codelab & $"{_stationPlan.BoxMumEditKey}={DevCode_txt.Text },"
                End If
                codelab = codelab.Substring(0, codelab.Length - 1)
                If String.IsNullOrEmpty(codelab) Then
                    node.RowListIndex = 1
                    node.Description = "模板标签未找到，请查看配置标签与模板标签是否一致！"
                    SetRichTextBox1Text(RichTextBox1, "模板标签未找到，请查看配置标签与模板标签是否一致！" & vbCrLf, Color.Red)
                    TheTestResults(Dut_SN, TestResult.TestResultEnum.Fail, datenow, node)
                    Return
                End If
                Dim exeArgs As String = $"0 {txt_template.Text} {codelab} 1 0 10000"

                If Not ColorBox.Equals("False") Then

                    'TestPrintf(,,)
                    SetRichTextBox1Text(RichTextBox1, "正在打印中" & vbCrLf, Color.ForestGreen)
                    SetRichTextBox1Text(RichTextBox1, codelab & vbCrLf, Color.ForestGreen)
                    If CallConsole（exepath， exeArgs， "20000"， "0", "Pass"） Then
                        Customfield.Clear()
                        Customfield.Add("MacCode", buff(1).Trim)
                        Customfield.Add("SnCode", buff(0).Trim)
                        Customfield.Add("ColorBoxCode", ColorBox)
                        Customfield.Add("label_string", DevCode_txt.Text.Trim)
                        PrintfNum = PrintfNum + 1
                        'lab_test_num.Text = PrintfNum.ToString & "个"
                        Printfcnt = My.Settings.P1_cnt + PrintfNum
                        'lab_Test_cnt.Text = Printfcnt.ToString & "个"
                        My.Settings.Save()
                        SetRichTextBox1Text(RichTextBox1, "调用打印机打印成功！" & vbCrLf, Color.Blue)
                        TheTestResults(buff(0).Trim, TestResult.TestResultEnum.Pass, datenow, Nothing, Customfield)
                    Else
                        node.RowListIndex = 1
                        node.Description = "打印失败！"
                        SetRichTextBox1Text(RichTextBox1, "打印失败" & vbCrLf, Color.Red)
                        TheTestResults(Dut_SN, TestResult.TestResultEnum.Fail, datenow, node)
                    End If


                Else
                    node.RowListIndex = 1
                    node.Description = "机身码绑定失败"
                    SetRichTextBox1Text(RichTextBox1, "机身码绑定失败" & vbCrLf, Color.Red)
                    TheTestResults(Dut_SN, TestResult.TestResultEnum.Fail, datenow, node)
                End If

            Else

                node.RowListIndex = 1
                node.Description = "机身码错误"
                SetRichTextBox1Text(RichTextBox1, "机身码错误" & vbCrLf, Color.Red)
                TheTestResults(Dut_SN, TestResult.TestResultEnum.Fail, datenow, node)
            End If
        End If
        If _stationPlan.AutoPrint Then
            DevCode_txt.Focus()
            DevCode_txt.SelectAll()
        End If

    End Sub

    Private Function GetTheColorBoxCode(devcode As String, ByRef DutSN As String) As String




    End Function


    Public Function CallConsole(exePath As String, exeArgs As String, timeout As String， stream As String， destSrc As String) As Boolean

        Dim Command As New TestCommand()
        Command.Parameter.Add(exePath）
        Command.Parameter.Add(exeArgs）
        Command.Parameter.Add(timeout)
        Command.Parameter.Add(stream)
        Command.Parameter.Add(destSrc)
        Dim executor As New ProcessExecuteExecutor(Command)

        Dim result As TestCommandReturn = executor.Execute()
        Return result.ExecuteResult

    End Function


    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 = Now
        _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 = 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



    Private Sub CheckBox1_CheckedChanged(sender As Object, e As EventArgs)
        'If CheckBox1.Checked Then
        '    btn_Print.Enabled = False
        'Else
        '    btn_Print.Enabled = True
        'End If
    End Sub




#Region "串口基础操作"
    Private Sub UpdateDutPortStatus()
        tsl_DUT_PortSataus.Text = Commport_DUT.PortName
        If Commport_DUT.IsOpen Then
            tsl_DUT_PortSataus.ForeColor = Color.Green
        Else
            tsl_DUT_PortSataus.ForeColor = Color.Red
        End If
    End Sub

    ''' <summary>
    ''' 关闭串口
    ''' </summary>
    Private Sub Close_Comport(objComPort As SerialPort)
        Try
            If objComPort.IsOpen Then
                objComPort.Close() '关闭commport
                objComPort.DiscardInBuffer()
            End If
        Catch ex As Exception
            objComPort.Close()
        End Try

    End Sub

    ''' <summary>
    ''' 打开串口,如果端口当前状态是打开状态，则先关闭串口，然后重新打开串口
    ''' </summary>
    ''' <param name="objComPort">打开目标串口的串口对象</param>
    ''' <returns>返回串口状态</returns>
    Private Function Open_Comport(objComPort As SerialPort, strPortName As String) As Boolean
        Try
            If objComPort.IsOpen Then
                objComPort.Close() '关闭commport
            End If

            objComPort.PortName = strPortName '串口编号赋值’
            objComPort.BaudRate = 115200
            objComPort.Open() '打开串口’

            Return objComPort.IsOpen '返回打开状态，true=打开成功’

        Catch ex As Exception
            objComPort.Close()
            Return False
        End Try

    End Function

    ''' <summary>
    ''' 获取可用串口列表
    ''' </summary>
    ''' <returns></returns>
    Private Function Get_Comport_list() As List(Of String）
        Dim lstComportName As List(Of String) = New List(Of String)
        lstComportName.Clear()

        Dim portNames() As String = SerialPort.GetPortNames()
        Array.Sort(portNames)
        lstComportName.AddRange(portNames)

        Return lstComportName
    End Function
#End Region


#Region "DUT 任务操作"
    Dim g_DutData As Dut_Data_Struct
    Dim g_tmpStrRcvd As String = "" '临时保持接收到的串口数据
    Dim g_RcvdData_Fm_DUT As String = "" '串口接收完成后，将临时数据复制一份出来，确保不耽误下一包接收
    Dim g_Str_tobe_Sent_To_ezCAD As String = ""
    Dim g_Find_Dut_Status As enum_Find_Dut_Status = enum_Find_Dut_Status.enum_DUT_ComPort_Status_UnKnow
    Dim g_Find_Dut_Status_Last As enum_Find_Dut_Status = enum_Find_Dut_Status.enum_DUT_ComPort_Status_UnKnow

    Structure Dut_Data_Struct
        Dim dev_Mac_Str As String
        Dim Dev_Mac As String
        Dim Dev_Version As String
        Dim Dev_Voltage As UInt16
        Dim Dev_Humiture As Double
        Dim Dev_Temprature_F As Double
        Dim Dev_Temprature_C As Double
        Dim Dev_PIR As Boolean
        Dim Dev_KeyLeft As Boolean
        Dim Dev_KeyRight As Boolean
        Dim Dev_Info_Count As ULong
        Dim Dev_DataReady As Boolean
        Dim Dev_IsPrinted As Boolean
        Dim Dev_LastUpate As DateTime

        Dim Dev_Info_Count_Last As ULong
        Dim Dev_Info_NoUpdate_Cnt As ULong
        Dim Dev_PortReady As Boolean

        Dim KeyVal_Left_Last As Boolean
        Dim KeyVal_Right_Last As Boolean
        Dim PirVal_Last As Boolean

        Dim KeyPressCnt_Left As Integer
        Dim KeyPressCnt_Right As Integer
        Dim PirTrigCnt As Integer
    End Structure

    ''' <summary>
    ''' DUT串口任务状态机标记位
    ''' </summary>
    Public Enum enum_Find_Dut_Status
        enum_DUT_ComPort_Status_UnKnow
        enum_DUT_ComPort_Status_GetPortList
        enum_DUT_ComPort_Status_ChangePort
        enum_DUT_ComPort_Status_Connected
        enum_DUT_ComPort_Status_WaitData
    End Enum


    ''' <summary>
    ''' 双击DUT串口标签启动串口自动匹配
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    Private Sub tsl_DUT_PortSataus_DoubleClick(sender As Object, e As EventArgs) Handles tsl_DUT_PortSataus.DoubleClick
        'TIM_DUT_TASK.Stop()
    End Sub

    ''' <summary>
    ''' DUT 串口接收事件
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    Private Sub Commport_DUT_DataReceived(sender As Object, e As SerialDataReceivedEventArgs) Handles Commport_DUT.DataReceived

    End Sub
    Private Function paser_RcvData(strRcvData As String) As Boolean
        '**************************** START ********************************
        '[MAC] -> [PHOD03E7DA4ADE8]
        '[Version] -> [0.2.17]
        '[Voltate] -> [2023] mV
        '[Humiture] -> Temperature: [80.11]F, Humidity:[56.1]%H
        '[PIR] -> [0]
        '[KeyLeft] -> [1]
        '[KeyRight] -> [0]
        '**************************** END ********************************
        Dim tmpPossition As Integer = 0
        Clear_Dut_Data()
        If InStr(strRcvData, "START") > 0 AndAlso InStr(strRcvData, "END") > 0 Then
            '>>>>>>> MAC
            tmpPossition = InStr(strRcvData, "MAC")
            If tmpPossition > 0 Then
                g_DutData.dev_Mac_Str = Microsoft.VisualBasic.Mid(strRcvData, tmpPossition + 9, 15)
                g_DutData.Dev_Mac = Microsoft.VisualBasic.Mid(strRcvData, tmpPossition + 12, 12)
                If InStr(g_DutData.Dev_Mac, ":") <= 0 Then
                    g_Str_tobe_Sent_To_ezCAD = g_DutData.Dev_Mac
                    tb_MAC_sent_to_ezCAD.Text = g_Str_tobe_Sent_To_ezCAD
                    g_DutData.Dev_Info_Count = CULng(g_DutData.Dev_Info_Count + 1)
                    g_DutData.Dev_DataReady = True
                    'g_DutData.Dev_PortReady = True
                    'g_DutData.Dev_LastUpate = Date.Now
                    tsl_dut_msg_cnt.Text = g_DutData.Dev_Info_Count.ToString

                    tb_DUT_Msg.Text = strRcvData
                End If
                'MsgBox(g_DutData.dev_Mac_Str & "," & g_DutData.Dev_Mac)
            End If

            '    '>>>>>>> Version
            '    tmpPossition = InStr(strRcvData, "Version")
            'If tmpPossition > 0 Then
            '    g_DutData.Dev_Version = Microsoft.VisualBasic.Mid(strRcvData, tmpPossition + 13, 6)
            '    'MsgBox(g_DutData.Dev_Version)
            'End If

            ''>>>>>>> Voltage
            'tmpPossition = InStr(strRcvData, "Voltage")
            'If tmpPossition > 0 Then
            '    g_DutData.Dev_Voltage = CType（Microsoft.VisualBasic.Mid(strRcvData, tmpPossition + 13, 4)， UInt16)
            '    'MsgBox(g_DutData.Dev_Voltage)
            'End If

            ''>>>>>>> Humiture
            'tmpPossition = InStr(strRcvData, "Humidity:")
            'If tmpPossition > 0 Then
            '    g_DutData.Dev_Humiture = CDbl(Microsoft.VisualBasic.Mid(strRcvData, tmpPossition + 10, 4))
            '    'MsgBox(g_DutData.Dev_Humiture)
            'End If

            ''>>>>>>> Temperature
            'tmpPossition = InStr(strRcvData, "Temperature:")
            'If tmpPossition > 0 Then
            '    g_DutData.Dev_Temprature_F = CDbl(Microsoft.VisualBasic.Mid(strRcvData, tmpPossition + 13, 5))
            '    g_DutData.Dev_Temprature_C = (g_DutData.Dev_Temprature_F - 32) / 1.8
            '    'MsgBox(g_DutData.Dev_Temprature_F & " , " & g_DutData.Dev_Temprature_C)
            'End If

            ''>>>>>>> PIR
            'tmpPossition = InStr(strRcvData, "PIR")
            'If tmpPossition > 0 Then
            '    g_DutData.Dev_PIR = CType(Microsoft.VisualBasic.Mid(strRcvData, tmpPossition + 9, 1), Boolean)
            '    'MsgBox(g_DutData.Dev_PIR)
            '    If g_DutData.Dev_PIR <> g_DutData.PirVal_Last Then
            '        If g_DutData.Dev_PIR = True Then
            '            g_DutData.PirTrigCnt += 1
            '        End If
            '        g_DutData.PirVal_Last = g_DutData.Dev_PIR
            '    End If
            'End If

            ''>>>>>>> KeyLeft
            'tmpPossition = InStr(strRcvData, "KeyLeft")
            'If tmpPossition > 0 Then
            '    g_DutData.Dev_KeyLeft = CType(Microsoft.VisualBasic.Mid(strRcvData, tmpPossition + 13, 1), Boolean)
            '    'lab_KeyLeft.Visible = g_DutData.Dev_KeyLeft
            '    'MsgBox(g_DutData.Dev_KeyLeft)
            '    If g_DutData.Dev_KeyLeft <> g_DutData.KeyVal_Left_Last Then
            '        If g_DutData.Dev_KeyLeft = True Then
            '            g_DutData.KeyPressCnt_Left += 1
            '        End If
            '        g_DutData.KeyVal_Left_Last = g_DutData.Dev_KeyLeft
            '    End If
            'End If

            ''>>>>>>> KeyRight
            'tmpPossition = InStr(strRcvData, "KeyRight")
            'If tmpPossition > 0 Then
            '    g_DutData.Dev_KeyRight = CType(Microsoft.VisualBasic.Mid(strRcvData, tmpPossition + 14, 1), Boolean)
            '    'MsgBox(g_DutData.Dev_KeyRight)
            '    If g_DutData.Dev_KeyRight <> g_DutData.KeyVal_Right_Last Then
            '        If g_DutData.Dev_KeyRight = True Then
            '            g_DutData.KeyPressCnt_Right += 1
            '        End If
            '        g_DutData.KeyVal_Right_Last = g_DutData.Dev_KeyRight
            '    End If
            'End If

            'g_DutData.Dev_Info_Count = CULng(g_DutData.Dev_Info_Count + 1)
            'g_DutData.Dev_DataReady = True
            ''g_DutData.Dev_PortReady = True
            ''g_DutData.Dev_LastUpate = Date.Now
            'tsl_dut_msg_cnt.Text = g_DutData.Dev_Info_Count

            'tb_DUT_Msg.Text = strRcvData
        Else
            Return False
        End If

        Return True
    End Function

    ''' <summary>
    ''' 清空DUT数据，通常在发生新数据时调用
    ''' </summary>
    Private Sub Clear_Dut_Data(Optional ByVal isClearAll As Boolean = False)
        g_DutData.dev_Mac_Str = ""
        g_DutData.Dev_Mac = ""
        g_DutData.Dev_Version = ""
        g_DutData.Dev_Voltage = 0
        g_DutData.Dev_Humiture = 0
        g_DutData.Dev_Temprature_F = 0
        g_DutData.Dev_Temprature_C = 0
        g_DutData.Dev_PIR = False
        g_DutData.Dev_KeyLeft = False
        g_DutData.Dev_KeyRight = False

        'g_Auts_RunData.Ble_Mac = ""
        'g_Auts_RunData.Ble_Rssi = -127

        If isClearAll Then
            g_DutData.KeyVal_Left_Last = False
            g_DutData.KeyVal_Right_Last = False
            g_DutData.PirVal_Last = False

            g_DutData.KeyPressCnt_Left = 0
            g_DutData.KeyPressCnt_Right = 0
            g_DutData.PirTrigCnt = 0

            g_DutData.Dev_DataReady = False
        End If
    End Sub

    Dim g_dut_find_portList As List(Of String) = New List(Of String) '保存搜索到的串口列表
    Dim g_dut_find_portidx As Integer = 0 '当前列表指针
    Dim g_dut_find_port_WaitCnt_100mS As Integer = 0 '串口打开后，等待一段时间看有没有数据上来
    Dim g_dut_task_data_nochange_cnt_100mS As Integer = 0 '串口任务中对数据未更新进行计时，超过2.5秒钟无更新则清楚数据
    ''' <summary>
    ''' 自动匹配串口
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    Private Sub TIM_Find_DUT_Port_Tick(sender As Object, e As EventArgs) Handles TIM_Find_DUT_Port.Tick

    End Sub

    Private Sub btn_FindDutPort_Click(sender As Object, e As EventArgs) Handles btn_FindDutPort.Click
        TIM_Find_DUT_Port.Start()
    End Sub

    Private Sub TIM_DUT_TASK_Tick(sender As Object, e As EventArgs) Handles TIM_DUT_TASK.Tick

    End Sub
#End Region

#Region "计数值管理"
    Dim g_totalcnt_Press_Cnt As Integer = 0
    Dim g_thistimecnt_Press_Cnt As Integer = 0
    Dim g_lastTimePoint As DateTime

    Private Sub TIM_CNT_CLEAR_Tick(sender As Object, e As EventArgs) Handles TIM_CNT_CLEAR.Tick

    End Sub

    Private Sub lab_Processed_Unit_Cnt_MouseDown(sender As Object, e As MouseEventArgs) Handles lab_Processed_Unit_Cnt.MouseDown

    End Sub

    Private Sub lab_Processed_Unit_Cnt_ThisCycle_MouseDown(sender As Object, e As MouseEventArgs) Handles lab_Processed_Unit_Cnt_ThisCycle.MouseDown

    End Sub

    Dim g_isLabelPrinted As Boolean = False
    Private Sub TIM_PRINT_LABEL_TASK_Tick(sender As Object, e As EventArgs) Handles TIM_PRINT_LABEL_TASK.Tick

    End Sub


#End Region

End Class


Public Class JsonAccessApi
    ''' <summary>
    ''' 初始化
    ''' </summary>
    Sub New()

    End Sub

    Public Mars_ColorBox_BarCode As String
    Public Message As String
    Public Barcodeas As String
End Class

