Imports System.IO
Imports System.IO.Ports
Imports System.Net
Imports System.Text
Imports Newtonsoft.Json
Imports UTS_Core.DebugLog
Imports UTS_Core.UTSModule
Imports UTS_Core.UTSModule.Station
Imports UTS_Core.UTSModule.Test
Imports UTS_Core.UTSModule.Test.Command
Imports UTS_Core.UTSModule.Test.StatusMonitor

Public Class ZQ_Mars_T2_FrmStationTest
    Implements IProcessStation

    Private _utsApp As UtsAppForm
    Private _stationPlan As StationPackagePlan

    Private PrintfNum As Integer = 0
    Private Printfcnt As Integer = 0

#Region "UTS Produce"

    ''' <summary>
    ''' 窗口加载事件
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    Private Sub ZQ_Mars_P2_FrmStationTest_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        ' lp_label.BackColor = Color.Transparent
        ApplicationLog.WriteInfoLog($"测试页面加载中。")
        If InitializeUtsApp() = False Then Return

        'InitializeForm()

        'timer_AutoFindCommPort.Enabled = True
        'timer_AutoFindCommPort.Start()
    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

    ''' <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)
        '清除表格数据
        'InitBarcodeGrid()
        txt_LooadNum.Text = "100" ' _stationPlan.CompanyName
        txt_UpNum.Text = "65535" '_stationPlan.BoxMumEditKey
        ApplicationLog.WriteInfoLog($"测试页面站位变更完成!")
    End Sub

    ''' <summary>
    ''' 加载窗体
    ''' </summary>
    ''' <param name="parentControl"></param>
    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 = 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 = 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

#End Region



#Region "SerialPort"

    ''' <summary>
    ''' 电子秤数据结构体
    ''' </summary>
    Private Structure ScaleData_Strut
        Dim isStable As ScaleIsStable_Enum  '是否稳定
        Dim weight_g As Double              '重量，以 g 为单位
        Dim weight_unit As ScaleUnit_Enum   '重量单位
        Dim isDataReady As Boolean          '数据是否可用
        Dim updateCnt As ULong              '更新计数
    End Structure

    ''' <summary>
    ''' 电子秤读回数据是否稳定枚举
    ''' </summary>
    Private Enum ScaleIsStable_Enum
        stable
        unstable
    End Enum

    ''' <summary>
    ''' 电子秤读回数据单位枚举
    ''' </summary>
    Private Enum ScaleUnit_Enum
        g
        kg
    End Enum
    ''' <summary>
    ''' 串口打开关闭状态枚举
    ''' </summary>
    Private Enum OpenClose_Enum
        Close
        Open
    End Enum

    ''' <summary>
    ''' 自动重连状态机枚举
    ''' </summary>
    Private Enum AutoConnectComportStatus_Enum
        Unknow
        Connected
        Disconnected
        reConnecting
    End Enum

    Dim g_ScaleData As ScaleData_Strut          '电子秤数据
    Dim g_strRcvd As String = ""                '当前串口接收到的数据
    Dim g_isScal_Connected As Boolean = False   '电子秤是连接到主机
    Dim g_LastRcvdData_TimePoint As DateTime

    Dim g_LastRcvdDataCnt As ULong '保存上一次串口数据接收计数，用于判断是否收到新的串口数据
    Dim g_NoRcvdData_Cnt As Integer = 0 '未收到串口数据计数，每100mS更新一次
    Dim g_LstCommPort As List(Of String) = New List(Of String) '用于保存串口列表
    Dim g_port_pointer_for_AutoConnect As Integer = 0 '在自动连接时，逐个串口尝试连接
    Dim g_Current_AutoConnectStatus As AutoConnectComportStatus_Enum = AutoConnectComportStatus_Enum.Unknow '当前自动连接状态

    ''' <summary>
    ''' 100mS 时钟，用于维护串口连接状态
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    Private Sub timer_AutoFindCommPort_Tick(sender As Object, e As EventArgs) Handles timer_AutoFindCommPort.Tick
        Select Case g_Current_AutoConnectStatus
            Case AutoConnectComportStatus_Enum.Unknow '未知连接状态
                If g_isScal_Connected Then
                    g_Current_AutoConnectStatus = AutoConnectComportStatus_Enum.Connected '连接状态
                Else
                    Dim tmpCommPortCnt As Integer = UpdateCommportList(g_LstCommPort) '重新刷新可用串口列表’
                    g_Current_AutoConnectStatus = AutoConnectComportStatus_Enum.reConnecting '重连状态
                End If

            Case AutoConnectComportStatus_Enum.Connected '连接状态
                If g_ScaleData.updateCnt = g_LastRcvdDataCnt Then '判断是否收到新数据
                    g_NoRcvdData_Cnt += 1
                    If g_NoRcvdData_Cnt >= 10 Then '连续1000mS没有收到新数据
                        g_ScaleData.isDataReady = False '电子秤数据不可用
                        g_isScal_Connected = False '复位连接状态
                        tss_CommPort.BackColor = Color.Crimson
                        If SerialPort1.IsOpen Then SerialPort1.Close() '关闭当前串口’
                        Dim tmpCommPortCnt As Integer = UpdateCommportList(g_LstCommPort) '重新刷新可用串口列表’
                        g_port_pointer_for_AutoConnect = 0 '寻找串口指针
                        g_Current_AutoConnectStatus = AutoConnectComportStatus_Enum.Disconnected '断开连接状态
                    End If
                Else
                    '两次计数不同说明收到新数据
                    If SerialPort1.IsOpen Then tss_CommPort.Text = SerialPort1.PortName
                    tss_CommPort.BackColor = Color.LightGreen
                    g_LastRcvdDataCnt = g_ScaleData.updateCnt
                    g_NoRcvdData_Cnt = 0
                End If

            Case AutoConnectComportStatus_Enum.Disconnected '断开连接状态
                Dim tmpLstCommportCnt As Integer = g_LstCommPort.Count
                If tmpLstCommportCnt > 0 And g_port_pointer_for_AutoConnect <= tmpLstCommportCnt - 1 Then
                    OpenClose_CommPort(g_LstCommPort(g_port_pointer_for_AutoConnect), OpenClose_Enum.Open)
                    If SerialPort1.IsOpen Then
                        tss_CommPort.Text = SerialPort1.PortName
                        tss_CommPort.BackColor = Color.Khaki
                    End If
                    g_NoRcvdData_Cnt = 0
                    g_Current_AutoConnectStatus = AutoConnectComportStatus_Enum.reConnecting
                End If

            Case AutoConnectComportStatus_Enum.reConnecting '重连中
                If g_ScaleData.updateCnt = g_LastRcvdDataCnt Then '判断是否收到新数据
                    g_NoRcvdData_Cnt += 1
                    If g_NoRcvdData_Cnt >= 10 Then '连续1000mS没有收到新数据
                        If g_port_pointer_for_AutoConnect < g_LstCommPort.Count - 1 Then
                            g_port_pointer_for_AutoConnect += 1
                        Else
                            Dim tmpCommPortCnt As Integer = UpdateCommportList(g_LstCommPort) '重新刷新可用串口列表’
                            g_port_pointer_for_AutoConnect = 0 '寻找串口指针
                        End If
                        g_Current_AutoConnectStatus = AutoConnectComportStatus_Enum.Disconnected '断开连接状态
                    End If
                Else
                    If SerialPort1.IsOpen Then tss_CommPort.Text = SerialPort1.PortName
                    tss_CommPort.BackColor = Color.LightGreen
                    g_LastRcvdDataCnt = g_ScaleData.updateCnt
                    g_NoRcvdData_Cnt = 0
                    g_Current_AutoConnectStatus = AutoConnectComportStatus_Enum.Connected
                End If

            Case Else
                g_Current_AutoConnectStatus = AutoConnectComportStatus_Enum.Unknow
        End Select

    End Sub

    ''' <summary>
    ''' 更新可用串口列表
    ''' </summary>
    ''' <param name="lstPortName">返回串口列表</param>
    ''' <returns>返回寻找可用串口数量</returns>
    Private Function UpdateCommportList(ByRef lstPortName As List(Of String)) As Integer
        lstPortName.Clear()
        Dim portNames As String() = Ports.SerialPort.GetPortNames
        lstPortName.AddRange（portNames）

        Return lstPortName.Count
    End Function

    ''' <summary>
    ''' 打开或关闭串口
    ''' </summary>
    ''' <param name="comportName"> 串口名称</param>
    ''' <param name="openClose">打开或关闭串口</param>
    ''' <returns>操作成功返回true，否则返回false </returns>
    Private Function OpenClose_CommPort(comportName As String, openClose As OpenClose_Enum) As Boolean
        '关闭串口
        If SerialPort1.IsOpen = True Then
            SerialPort1.Close()
        End If

        If openClose = OpenClose_Enum.Close Then
            Return Not SerialPort1.IsOpen
        Else
            '打开串口
            SerialPort1.PortName = comportName
            SerialPort1.Open()
            Return SerialPort1.IsOpen
        End If
    End Function

    ''' <summary>
    ''' 串口接收事件
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    Private Sub SerialPort1_DataReceived(sender As Object, e As SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
        '收到数据

        Dim rcvd As String = ""

        Dim bufflen As Integer = SerialPort1.BytesToRead
        If SerialPort1.BytesToRead > 0 Then

            Dim therecvBuffer(bufflen) As Byte
            SerialPort1.Read(therecvBuffer, 0, bufflen)
            Dim readStr As String = Encoding.GetEncoding("GBK").GetString(therecvBuffer)

            If readStr.Equals(vbNullChar) Then Return

            rcvd = rcvd & readStr
            rcvd = rcvd.Replace（vbNullChar, ""）
            g_strRcvd = g_strRcvd & readStr
            g_strRcvd = g_strRcvd.Replace（vbNullChar, ""）

            g_LastRcvdData_TimePoint = DateTime.Now
        End If

        'ST,NT,+  197.9 g
        'US,NT,+  197.4 g 
        'US,NT,+  197.4 g
        '收到换行符号或长度大于=18
        If rcvd.Length < 1 Then
            Return

        End If
        Dim listr As String = rcvd.Substring(rcvd.Length - 2)
        If listr.Equals(vbCrLf) Then
            listr = rcvd.Trim
            Console.WriteLine($"listr:{listr}")
            If listr.Length >= 10 Then
                If listr.Length >= 10 Then
                    '判断稳定状态
                    ' Dim tmpStableStr As String = Microsoft.VisualBasic.Mid(listr, 6, 2).Trim
                    Dim tmpUnit() As String = listr.Split(CChar("+"))
                    If tmpUnit.Length <> 2 Then
                        Return
                    End If

                    Dim tmpUnit1() As String = tmpUnit（1）.Trim.Split(CChar(" "))
                    If tmpUnit.Length <> 2 Then
                        Return
                    End If

                    If tmpUnit(0).Contains("ST") Then
                        '稳定
                        g_ScaleData.isStable = ScaleIsStable_Enum.stable
                        g_ScaleData.isDataReady = False
                    ElseIf tmpUnit(0).Contains("US") Then
                        '不稳定
                        g_ScaleData.isStable = ScaleIsStable_Enum.unstable
                        g_ScaleData.isDataReady = False
                    Else
                        '非法数据
                        g_strRcvd = ""
                        Return
                    End If

                    '判断单位





                    If tmpUnit1(1).Trim.Equals("kg") Then
                        g_ScaleData.weight_unit = ScaleUnit_Enum.g
                    ElseIf tmpUnit1(1).Trim.Equals("g") Then
                        g_ScaleData.weight_unit = ScaleUnit_Enum.kg
                    Else
                        '非法数据
                        g_strRcvd = ""
                        Return
                    End If

                    '计算重量

                    If Double.TryParse(tmpUnit1(0).Trim, g_ScaleData.weight_g) Then
                        If g_ScaleData.weight_unit = ScaleUnit_Enum.kg Then
                            g_ScaleData.weight_g = g_ScaleData.weight_g * 1000
                        End If
                        If g_ScaleData.weight_g > 5 Then


                            If g_ScaleData.isStable = ScaleIsStable_Enum.stable Then
                                loadedWeight(txt_testnum, g_ScaleData.weight_g.ToString, Color.Green)
                            ElseIf g_ScaleData.isStable = ScaleIsStable_Enum.unstable Then
                                loadedWeight(txt_testnum, g_ScaleData.weight_g.ToString, Color.Blue)
                            Else
                                loadedWeight(txt_testnum, "----", Color.Gray)
                            End If
                        Else
                            loadedWeight(txt_testnum, "----", Color.Gray)
                        End If

                    Else
                        '非法数据
                        g_strRcvd = ""
                        Return
                    End If

                    g_ScaleData.updateCnt = CULng(g_ScaleData.updateCnt + 1)    '有效计数 +1
                    g_ScaleData.isDataReady = True                              '数据就绪
                    g_isScal_Connected = True                                   '电子秤已连接
                End If

                g_strRcvd = ""
            End If
        End If


    End Sub
    Delegate Sub theSetopenUartshow(btn As TextBox， txt As String， bcolor As Color)
    Public Sub loadedWeight(testnum As TextBox， txt As String， txtcolor As Color)
        If testnum.InvokeRequired Then
            Dim dev As New theSetopenUartshow(AddressOf loadedWeight)
            testnum.Invoke(dev, New Object() {testnum, txt, txtcolor})
        Else
            testnum.Text = txt
            testnum.ReadOnly = False
            testnum.ForeColor = txtcolor


        End If
    End Sub



    ''' <summary>
    ''' 串口接收超时计数，每1mS中断判断一次，超时大于80mS就将缓冲区数据抛弃
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    Private Sub timer_Rcvd_Timeout_Tick(sender As Object, e As EventArgs) Handles timer_Rcvd_Timeout.Tick
        'ticks 1unit = 100nS
        Dim rcvTimespan As Long = DateTime.Now.Ticks - g_LastRcvdData_TimePoint.Ticks

        If rcvTimespan >= 80 * 10000 Then
            g_strRcvd = ""
        End If
    End Sub
#End Region


#Region "Web 数据接口"
    Public Function AccessApi2（dbName As String, theKey As String， dic As Dictionary(Of String, String), ProjectID As String） As JsonPtr
        Dim jsonString As String = String.Empty

        Dim ptr As String = $"Pwd=actop00803&DBName={dbName}&Key={theKey}&JsonData={JsonConvert.SerializeObject(dic)}&ProjectID={ProjectID}"

        '/http://uts-data.com/CommonApi/Combind_Sn_Info? Pwd%3D%26*$@%23235%26DBName%3Duts_zongqing%26Key%3DBarcode%26Barcode%3D1
        Try
            jsonString = PostData("http://uts-data.com/CommonApi/Combind_Sn_Info", ptr)
            Console.WriteLine(jsonString)

            If jsonString = Nothing Then
                Return Nothing
            End If

            Dim login As JsonPtr = JsonConvert.DeserializeObject(Of JsonPtr)(jsonString)
            If login.Message.Contains（"成功"） Then
                Return login
            Else
                Return Nothing
            End If


        Catch ex As Exception
            MsgBox($"{ex.Message}！盒码获取失败请联系管理员")
            Return Nothing
        End Try


    End Function
    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





#End Region


#Region "UIEven"
    Private Sub RichTextBox1_TextChanged(sender As Object, e As EventArgs)
        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 ObtainWeighingValue() As String
        Dim Whileint As Integer = 0
        While Whileint < 200
            If txt_LooadNum.ForeColor = Color.Green Then
                Return txt_LooadNum.Text
                Exit While
            Else
                Whileint = Whileint + 1
                delayms（100）

            End If

        End While

        If txt_LooadNum.ForeColor = Color.Green Then
        Else
            Return "False"
        End If
    End Function

    Private Sub TextBox2_PreviewKeyDown(sender As Object, e As PreviewKeyDownEventArgs) Handles colorbox.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 = "C:\Debug\AUTS_Ext_BarTenderConsole.exe"
        If e.KeyData = Keys.Enter Then

            If IsBoxReady Then
                If Entering_Cnt > 9 Then
                    MsgBox("箱体已满载，请更换箱体码再进行录入。")
                    Me.txt_BosCode.Focus()
                    Me.txt_BosCode.SelectAll()
                    Me.txt_BosCode.Enabled = True
                    IsBoxReady = False

                Else
                    Dim dic As New Dictionary(Of String, String）
                    Dim weightval As String = ObtainWeighingValue()
                    If weightval.Equals("False") Then
                        dic.Add("Mars_UnitWeigth"， txt_testnum.Text) '称重值
                    Else
                        dic.Add("Mars_UnitWeigth"， weightval) '称重值
                    End If

                    dic.Add("Mars_ColorBox_BarCode"， Me.colorbox.Text)

                    Dim apidata As JsonPtr = AccessApi2("uts_zongqing", "Mars_ColorBox_BarCode"， dic, _utsApp.ProcessStation.ParentProject.Index.ToString)

                    If Not IsNothing（apidata） Then
                        Dut_SN = apidata.Data.Barcode.Trim
                        devbox.Text = apidata.Data.Barcode

                        Customfield.Clear()
                        Customfield.Add("MacCode", apidata.Data.Mars_MacCodeP)
                        Customfield.Add("SnCode", Dut_SN)
                        Customfield.Add("ColorBoxCode", Me.colorbox.Text.Trim)
                        Customfield.Add("label_string", Dut_SN & "/" & apidata.Data.Mars_MacCodeP)
                        Customfield.Add("mars_OutBoxCode", txt_BosCode.Text.Trim)
                        Dim testresuli As String
                        If weightval.Equals("False") Then
                            Customfield.Add("Mars_UnitWeigth", txt_testnum.Text)
                            testresuli = CopmareTheSize(txt_LooadNum.Text, txt_testnum.Text, txt_UpNum.Text) '比较范围
                        Else
                            Customfield.Add("Mars_UnitWeigth", weightval)
                            testresuli = CopmareTheSize(txt_LooadNum.Text, weightval, txt_UpNum.Text) '比较范围
                        End If

                        If testresuli.Equals("False") Then

                            node.RowListIndex = 1
                            node.Description = "称重不在预设阈值内！"
                            node.TestReturn = New TestCommandReturn
                            node.TestReturn.LowerLimit = ""
                            node.TestReturn.UpperLimit = ""
                            node.TestReturn.RecordValue = "Fail"

                            TheTestResults(Dut_SN, TestResult.TestResultEnum.Fail, datenow, node, Customfield)
                            SetRichTextBox1Text(RichTextBox1, "称重不在预设阈值内！" & vbCrLf, Color.Red)
                        Else
                            'MsgBox("开始录入数据")
                            TheTestResults(Dut_SN, TestResult.TestResultEnum.Pass, datenow, Nothing, Customfield)
                            'MsgBox("完成录入数据")
                            PrintfNum = PrintfNum + 1
                            'Label7.Text = PrintfNum.ToString & "个"
                            lab_Processed_Unit_Cnt_ThisCycle.Text = PrintfNum.ToString & "个"
                            Printfcnt = My.Settings.P2_cnt + PrintfNum
                            lab_Processed_Unit_Cnt.Text = Printfcnt.ToString & "个"
                            My.Settings.Save()

                            SetRichTextBox1Text(RichTextBox1, $"{Entering_Cnt}.数据录入成功.colorbox:{Me.colorbox.Text.Trim},Mars_UnitWeigth:{txt_testnum.Text}！" & vbCrLf, Color.Blue)
                            Entering_Cnt = Entering_Cnt + 1
                        End If


                        Me.colorbox.Focus()
                        Me.colorbox.SelectAll()

                    Else
                        node.RowListIndex = 1
                        node.Description = "获取彩盒码关联条码错误！"
                        node.TestReturn = New TestCommandReturn
                        node.TestReturn.LowerLimit = ""
                        node.TestReturn.UpperLimit = ""
                        node.TestReturn.RecordValue = "Fail"
                        TheTestResults(Dut_SN, TestResult.TestResultEnum.Fail, datenow, node)
                        SetRichTextBox1Text(RichTextBox1, "获取彩盒码关联条码错误！" & vbCrLf, Color.Red)
                    End If
                End If

            Else
                MsgBox("箱体码未就绪，请先扫箱体码再进行录入。")
                Me.txt_BosCode.Focus()
                Me.txt_BosCode.SelectAll()
                Me.txt_BosCode.Enabled = True
            End If



        End If



    End Sub

    Public Function CopmareTheSize(loadint As String, numint As String, upint As String) As String

        Dim loadnum As Integer = 0
        Dim upnum As Integer = 0
        Dim connum As Integer = 0


        If Integer.TryParse(loadint, loadnum) AndAlso Integer.TryParse(numint, connum) AndAlso Integer.TryParse(upint, upnum) Then
            If loadnum < connum AndAlso connum < upnum Then
                Return CStr(connum)
            Else
                Return "False"
            End If
        Else
            Return "False"
        End If


    End Function
    Public Sub delayms(ms As Integer)
        Dim start As Integer = Environment.TickCount
        While (Math.Abs(Environment.TickCount - start) < ms)
            Application.DoEvents()
        End While

    End Sub

    Private Sub OpenUart_btn_Click(sender As Object, e As EventArgs) Handles OpenUart_btn.Click
        Dim Btn As Button = CType(sender, Button)


        If IsNothing(UartPort_cob) OrElse String.IsNullOrEmpty(UartPort_cob.Text) Then Return
        SerialPortCommSwitch(SerialPort1, UartPort_cob.Text, Btn)
    End Sub


    Private Sub SerialPortCommSwitch(Serial As IO.Ports.SerialPort, portName As String, btn As Button)
        If Serial.IsOpen Then
            Serial.Close()
            btn.Text = "打开串口"
            btn.BackColor = Color.LightGray
            btn.Enabled = True
        Else
            If String.IsNullOrEmpty(portName) Then
                MsgBox("串口为空，请选择串口")
                Return
            End If
            ConfigSerialPort(Serial, portName)
            Try
                Serial.Open()
            Catch ex As Exception
                MsgBox($"串口打开失败，详情：{ex.Message}")
                Serial.Close()
                Return
            End Try

            'SerialPort1.Close()
            btn.Text = "关闭串口"
            btn.BackColor = Color.SlateGray
            btn.Enabled = True
        End If
    End Sub
    Public Sub ConfigSerialPort(Serial As IO.Ports.SerialPort, portName As String)
        With Serial
            .PortName = portName                '串口名
            .BaudRate = 9600 ' _BaudRate      '波特率
            .DataBits = 8      '数据位
            .StopBits = Ports.StopBits.One            '停止位
            .Parity = Ports.Parity.None              '偶校验
            .RtsEnable = True
            .ReceivedBytesThreshold = 1
        End With
    End Sub
    Private Sub UartPort_cob_DropDown(sender As Object, e As EventArgs) Handles UartPort_cob.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
    End Sub


    Public IsBoxReady As Boolean = False
    Public Entering_Cnt As Integer = 1
    Private Sub txt_BosCode_PreviewKeyDown(sender As Object, e As PreviewKeyDownEventArgs) Handles txt_BosCode.PreviewKeyDown

        If e.KeyData = Keys.Enter Then
            IsBoxReady = True
            Entering_Cnt = 1
            Me.txt_BosCode.Enabled = False
            Me.colorbox.Focus()
            Me.colorbox.SelectAll()

        End If


    End Sub





#End Region



#Region "测试流程"

#End Region

End Class

Public Class JsonPtr
    Public Data As jsonrusil
    Public Message As String

End Class
Public Class jsonrusil
    Public ID As String

    Public ProjectID As String
    Public Barcode As String
    Public ImportDateTime As Date
    Public UpdateTime As Date
    Public Mars_ColorBox_BarCode As String
    Public Mars_OutBoxCode As String
    Public Mars_MacCodeP As String
    Public Mars_UnitWeigth As String
End Class





