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
Imports System.Threading

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
    Private NodePtr As TreeNode
    '最大装载数量 赋值需要减一  
    Private Max_Loading As Integer = 10
    Public g_Pcontrol As ProcessControlAPI
    Private Thread_setapi As Thread

    Public testcnt 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()
        My.Settings.Reload()
        ' Console.WriteLine(My.Settings.P1_cnt.ToString)

        '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

    Private IsMars As Boolean
    ''' <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)

        If Not IsNothing（lab_imger.Image） Then
            lab_imger.Image.Dispose()
        End If
        g_Pcontrol = New ProcessControlAPI(_utsApp)
        'Thread_setapi = New Thread(AddressOf Threadsetapistart)
        Dim revStationPlanPath As String = UtsPath.GetStationPacketResourceDirPath(_stationPlan.ParentPacket.Name)
        'Dim cont As Control = CType(lab_imger, Control)

        Select Case _utsApp.ProcessStation.ParentProject.Index
            Case 1
                'lab_imger.Image = Image.FromFile(revStationPlanPath & "\Mars.png")
                If File.Exists(revStationPlanPath & "\Mars.png") Then

                    'Dim img As Image = Image.FromFile(revStationPlanPath & "\Mars.jpg")

                    Dim FStream As FileStream = New FileStream(revStationPlanPath & "\Mars.png", FileMode.Open, FileAccess.Read)

                    Dim byteLength As Integer = CType(FStream.Length, Integer)
                    Dim fileBytes（byteLength） As Byte
                    FStream.Read(fileBytes, 0, byteLength)

                    ' //文件流关閉,文件解除锁定
                    FStream.Close()

                    lab_imger.Image = Image.FromStream(New MemoryStream(fileBytes))
                    '
                    'lab_imger.Image = img
                    'lab_projectname.Text = "Mars"
                End If
            Case 2
                If File.Exists(revStationPlanPath & "\Phobos.png") Then
                    'Dim img As Image = Image.FromFile(revStationPlanPath & "\Phobos.jpg")
                    'If Not IsNothing（lab_imger.Image） Then
                    '    lab_imger.Image.Dispose()
                    'End If
                    'lab_imger.Image = img
                    Dim FStream As FileStream = New FileStream(revStationPlanPath & "\Phobos.png", FileMode.Open, FileAccess.Read)

                    Dim byteLength As Integer = CType(FStream.Length, Integer)
                    Dim fileBytes（byteLength） As Byte
                    FStream.Read(fileBytes, 0, byteLength)

                    ' //文件流关閉,文件解除锁定
                    FStream.Close()
                    lab_imger.Image = Image.FromStream(New MemoryStream(fileBytes))

                    ' lab_projectname.Text = "Phobos"
                End If
        End Select
        ShowFormTitle(_utsApp.ProcessStation)
        '清除表格数据
        'InitBarcodeGrid()
        If _utsApp.ProcessStation.Name.ToLower.Contains("p2") Then
            txt_LooadNum.Text = _stationPlan.CompanyName
            txt_UpNum.Text = _stationPlan.BoxMumEditKey
            chk_auto.Checked = _stationPlan.AutoPrint

            Integer.TryParse(_stationPlan.CompanyLogo, Max_Loading)
            lab_sun.Text = $"0/{Max_Loading}"
            '计数是独立的
            UartPort_cob.Text = My.Settings.P2_PortName
            SerialPortCommSwitch(SerialPort1, My.Settings.P2_PortName, OpenUart_btn)
            lab_Processed_Unit_Cnt_ThisCycle.Text = "0"
            If _utsApp.ProcessStation.ParentProject.Index = 1 Then
                lab_Processed_Unit_Cnt.Text = My.Settings.Mars_P2_cnt.ToString
            ElseIf _utsApp.ProcessStation.ParentProject.Index = 2 Then
                lab_Processed_Unit_Cnt.Text = My.Settings.Phobos_P2_cnt.ToString
            End If
        Else
            SerialPort1.Close()
        End If

        ApplicationLog.WriteInfoLog($"测试页面站位变更完成!")

    End Sub
    Private Sub ShowFormTitle(Optional station As ProcessStation = Nothing)
        Dim myTitle As String '= "AUTS_FunctionTest  ( Build: " & Application.ProductVersion
        'If _utsApp.Account IsNot Nothing Then
        '    myTitle = myTitle & " , 用户 : " & _utsApp.Account.UserName
        'End If
        lab_projectconfig.Text = ""
        lab_projectname.Text = ""
        If station IsNot Nothing AndAlso station.Packet IsNot Nothing Then
            lab_projectname.Text = "项目 : " & station.ParentProject.Name & vbCrLf
            'myTitle = myTitle & "站序 : " & station.ArtworkOrder & vbCrLf
            myTitle = myTitle & "站位 : " & station.Name & vbCrLf
            myTitle = myTitle & "站名 : " & station.Description & vbCrLf

        End If



        lab_projectconfig.Text = myTitle
    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 bufflen As Integer = SerialPort1.BytesToRead
        If SerialPort1.BytesToRead > 0 Then
            Dim readStr As String = SerialPort1.ReadExisting
            g_strRcvd = g_strRcvd & readStr
            g_LastRcvdData_TimePoint = DateTime.Now
        End If

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

        Dim listr As String = ""

        ' If listr.Equals(vbCrLf) Then
        If InStr(g_strRcvd, vbCrLf) > 0 Then
            listr = g_strRcvd.Trim
            g_strRcvd = ""

            Console.WriteLine($"listr:{listr} , Len = {listr.Length }")
            'ST,NT,+  175.4 g

            If listr.Length >= 16 AndAlso
                Microsoft.VisualBasic.Mid(listr, 3, 1) = "," AndAlso
                Microsoft.VisualBasic.Mid(listr, 6, 1) = "," AndAlso
                Microsoft.VisualBasic.Mid(listr, 7, 1) = "+" Then

                Console.WriteLine("String OK!")

                loadedWeight(LiveData, listr, Color.Gray)


                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.kg
                    ElseIf tmpUnit1(1).Trim.Equals("g") Then
                        g_ScaleData.weight_unit = ScaleUnit_Enum.g
                    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 = ""

            'g_ScaleData.isStable = ScaleIsStable_Enum.unstable   '是否稳定
            ''g_ScaleData.weight_g As Double              '重量，以 g 为单位
            ''g_ScaleData.weight_unit As ScaleUnit_Enum   '重量单位
            'g_ScaleData.isDataReady = False           '数据是否可用
            'g_ScaleData.updateCnt = 0             '更新计数
            LiveData.Text = "----"
            loadedWeight(txt_testnum, "----", Color.Gray)
        End If
    End Sub
#End Region


#Region "Web 数据接口"

    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)

    End Sub
    Delegate Sub IPSetRichTextBox1Text(inTextBox1 As RichTextBox, text As String， txtcolor As Color)
    Private Sub SetRichTextBox1Text(inTextBox1 As RichTextBox, text As String， txtcolor As Color)
        If InvokeRequired = True Then
            Dim dev As New IPSetRichTextBox1Text(AddressOf SetRichTextBox1Text)
            Me.Invoke(dev, New Object() {inTextBox1, text, txtcolor})
        Else
            With inTextBox1
                .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 < 100
            If txt_testnum.ForeColor = Color.Green Then
                Return txt_testnum.Text
                Exit While
            Else
                Whileint = Whileint + 1
                delayms（100）

            End If

        End While

        If txt_testnum.ForeColor = Color.Green Then
            Return txt_testnum.Text
        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 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 Thread_setapi.IsAlive Then
            '    G3label_tip.Text = "数据正在录入"
            '    MsgBox("数据正在录入")
            'End If
            If String.IsNullOrWhiteSpace(colorbox.Text) Then

                G3label_tip.Text = "彩盒码为空，请输入箱号！"
                MsgBox("彩盒码为空，请输入箱号！")
                colorbox.Focus()
                colorbox.SelectAll()
                Return
            End If

            If IsNothing(NodePtr) OrElse String.IsNullOrWhiteSpace(txt_BosCode.Text) Then

                G3label_tip.Text = "箱号为空，请输入箱号再进行录入"
                MsgBox("箱号为空，请输入箱号再进行录入")
                Me.txt_BosCode.Focus()
                Me.txt_BosCode.SelectAll()
                Me.txt_BosCode.Enabled = True

                Return
            End If


            If NodePtr.Nodes.Count < Max_Loading Then
                '查询 sn


                If DuplicateChecking(NodePtr, colorbox.Text.Trim) Then          '查重

                    Dim weightval As String = ObtainWeighingValue()             '查稳定态 3 S
                    If weightval.Equals("False") Then
                        G3label_tip.Text = "称重超时，请重新扫码称重！"
                        MsgBox("称重超时，请重新扫码称重！")
                        colorbox.Focus()
                        colorbox.SelectAll()
                        Return
                    End If

                    Dim testresuli As String = CopmareTheSize(txt_LooadNum.Text, weightval, txt_UpNum.Text) '比较阈值

                    If testresuli.Equals("False") Then
                        G3label_tip.Text = "称重值不在阈值范围内，检查彩盒部件是否有缺失！"
                        MsgBox("称重值不在阈值范围内，检查彩盒部件是否有缺失！")
                        colorbox.Focus()
                        colorbox.SelectAll()
                        Return
                    Else
                        Dim dic As New Dictionary(Of String, String）
                        'dic.Add("OutBoxCode"， txt_BosCode.Text) '称重值
                        dic.Add("ColorBox_BarCode"， colorbox.Text)
                        dic.Add("UnitWeigth"， weightval)
                        dic.Add("UpdateTime"， $"{Now:yyyy-MM-dd HH:mm:ss}")
                        ' Dim jsonclass As ContJsonPtr = AccessApi1("http://uts-data.com/CommonApi/Combind_Sn_Info", "uts_zongqing", "ColorBox_BarCode"， _utsApp.ProcessStation.ParentProject.Index.ToString， dic)
                        Dim jsonclass As CombindSnInfo = g_Pcontrol.API_Combind_Sn_Info("ColorBox_BarCode", _utsApp.ProcessStation.ParentProject.Index.ToString, dic)
                        If IsNothing(jsonclass) Then
                            G3label_tip.Text = "未查询到彩盒码关联数据，请核实彩盒码！"
                            MsgBox("未查询到彩盒码关联数据，请核实彩盒码！")
                            colorbox.Focus()
                            colorbox.SelectAll()
                            Return
                        End If


                        '10-28 czh 此处注释需要保留 该 注释 作用为防止彩盒码在不同装箱重复装箱，通过判断流程标记位来确定
                        If IsNothing（jsonclass.data） OrElse Not jsonclass.data.ContainsKey($"RESULT{_utsApp.ProcessStation.SnListOrder}") OrElse
                             String.IsNullOrEmpty(jsonclass.data.Item($"RESULT{_utsApp.ProcessStation.SnListOrder}")) OrElse
                             jsonclass.data.Item($"RESULT{_utsApp.ProcessStation.SnListOrder}").Equals(("0")) Then


                        Else
                            Dim strInputMsg As String = InputBox($"该彩盒码已录入，箱体码为:{jsonclass.data.Item("OUTBOXCODE")}，请输入密码确认是否覆盖原记录！", "密码确认")
                            If strInputMsg <> "Cc2022OK" Then
                            Else
                                colorbox.Focus()
                                colorbox.SelectAll()
                                Return
                            End If

                        End If    ' 10-28 czh

                        devbox.Text = jsonclass.data.Item("BARCODE")
                        If chk_flow.Checked Then
                            If g_Pcontrol.IsFrontStation(_utsApp.ProcessStation.SnListOrder, jsonclass.data.Item("BARCODE")) Then
                                g_Pcontrol.SetStationflag(_utsApp.ProcessStation.SnListOrder, jsonclass.data.Item("BARCODE"), "0")
                            Else
                                colorbox.Focus()
                                colorbox.SelectAll()
                                Return
                            End If
                        End If


                        Dim node As New TreeNode
                        node.Text = $"（{Tree_ViewEx1.Nodes(0).Nodes.Count + 1}）彩盒码:" & colorbox.Text.Trim
                        node.Tag = jsonclass
                        ' node.ExpandAll()
                        Tree_ViewEx1.Nodes(0).Nodes.Add(node)
                        G3label_tip.Text = "称重完成！"
                        lab_sun.Text = $"{Tree_ViewEx1.Nodes(0).Nodes.Count }/{Max_Loading}"
                        node.ExpandAll()

                        node.EnsureVisible()
                        If chk_auto.Checked Then
                            If NodePtr.Nodes.Count = Max_Loading Then
                                Me.txt_BosCode.Focus()
                                Me.txt_BosCode.SelectAll()
                                Me.txt_BosCode.Enabled = True
                                ' btn_entering.PerformClick()
                                G3label_tip.Text = "开始上传装箱数据！"
                                btn_entering_Click（Nothing， Nothing）
                                Return
                            End If
                        End If

                    End If


                    colorbox.Focus()
                    colorbox.SelectAll()

                Else
                    G3label_tip.Text = "彩盒码已记录，请输入新的彩盒码！"
                    MsgBox("彩盒码已记录，请输入新的彩盒码！")
                    colorbox.Focus()
                    colorbox.SelectAll()
                    Return
                End If

            Else
                G3label_tip.Text = $"装箱数已满，最大装载量为:{Max_Loading}"
                MsgBox($"装箱数已满，最大装载量为:{Max_Loading}")

                Me.txt_BosCode.Focus()
                Me.txt_BosCode.SelectAll()
                Me.txt_BosCode.Enabled = True

                Return
            End If

            '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
            '    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 DuplicateChecking(node As TreeNode， txt As String) As Boolean
        For Each index As TreeNode In node.Nodes
            If index.Text.Contains(txt.Trim) Then
                Return False
            End If
        Next
        '  Dim d_CombindSnInfo As CombindSnInfo = g_Pcontrol.API_Get_Sn_Info(DutSN, _utsApp.ProcessStation.ParentProject.Index.ToString)


        Return True
    End Function


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

        Dim loadnum As Double = 0
        Dim upnum As Double = 0
        Dim connum As Double = 0


        If Double.TryParse(loadint, loadnum) AndAlso Double.TryParse(numint, connum) AndAlso Double.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)

        My.Settings.P2_PortName = UartPort_cob.Text
        My.Settings.Save()
    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
                G3label_tip.Text = "串口为空，请选择串口"
                MsgBox("串口为空，请选择串口")
                Return
            End If
            ConfigSerialPort(Serial, portName)
            Try
                Serial.Open()
            Catch ex As Exception
                G3label_tip.Text = $"串口打开失败，详情：{ex.Message}"
                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 Sub TreeViewEx1_NodeMouseClick(sender As Object, e As TreeNodeMouseClickEventArgs) Handles Tree_ViewEx1.NodeMouseDoubleClick
        If e.Button <> MouseButtons.Left Then Return
        Dim node As TreeNode = Tree_ViewEx1.SelectedNode

        If node Is Nothing Then Return
        If node.Level = 0 Then
            txt_inputnum.Text = node.Nodes.Count.ToString
            txt_MacCode.Text = "------"
            txt_colorbox.Text = "------"
            txt_labstring.Text = "------"
            txt_SnCode.Text = "------"
            txt_unitweight.Text = "------"
            Return
        End If

        Dim nodeboj As CombindSnInfo = CType(node.Tag, CombindSnInfo)
        txt_MacCode.Text = nodeboj.data.Item("MACCODE")
        txt_colorbox.Text = nodeboj.data.Item("COLORBOX_BARCODE")
        txt_inputnum.Text = "1"
        txt_labstring.Text = nodeboj.data.Item("BARCODE")
        txt_SnCode.Text = nodeboj.data.Item("BARCODE")
        txt_unitweight.Text = nodeboj.data.Item("UNITWEIGTH")

    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Btn_delete.Click

        If IsNothing(Tree_ViewEx1) Then Return
        Dim node As TreeNode = Tree_ViewEx1.SelectedNode
        If Tree_ViewEx1.Nodes(0).Text.Equals（node.Text） Then
            If MsgBox("该节点为箱体节点，删除将丢失已存在该箱体的记录。是否删除？", MsgBoxStyle.OkCancel) = MsgBoxResult.Ok Then
                Tree_ViewEx1.Nodes.RemoveAt(0)
                Tree_ViewEx1.Nodes.Clear()
                'txt_BosCode.Text = ""

                txt_BosCode.ReadOnly = False
                txt_BosCode.Enabled = True
                txt_BosCode.Focus()
                txt_BosCode.SelectAll()
            End If
        Else
            ' Dim buffstr() As String = node.Text.Split(CChar(":"))
            Dim nodeboj As CombindSnInfo = CType(node.Tag, CombindSnInfo)

            Dim dic As New Dictionary(Of String, String）
            dic.Add("OutBoxCode"， "") '称重值
            dic.Add("ColorBox_BarCode"， nodeboj.data.Item("COLORBOX_BARCODE"))
            dic.Add("UnitWeigth"， "")
            dic.Add("UpdateTime"， $"{Now:yyyy-MM-dd HH:mm:ss}")
            'Dim jsonclass As ContJsonPtr = AccessApi1("http://uts-data.com/CommonApi/Combind_Sn_Info", "uts_zongqing", "ColorBox_BarCode"， _utsApp.ProcessStation.ParentProject.Index.ToString， dic)
            Dim jsonclass As CombindSnInfo = g_Pcontrol.API_Combind_Sn_Info("ColorBox_BarCode", _utsApp.ProcessStation.ParentProject.Index.ToString， dic)
            g_Pcontrol.SetStationflag(_utsApp.ProcessStation.SnListOrder, jsonclass.data.Item("BARCODE"), "0")
            Tree_ViewEx1.Nodes(0).Nodes.Remove(node)
            lab_sun.Text = $"{Tree_ViewEx1.Nodes(0).Nodes.Count }/{Max_Loading}"
            For nodeindex As Integer = 0 To Tree_ViewEx1.Nodes(0).Nodes.Count - 1
                Dim innode As TreeNode = Tree_ViewEx1.Nodes(0).Nodes(nodeindex)
                Dim stxt() As String = innode.Text.Split(CChar(":"))
                If stxt.Length > 1 Then
                    innode.Text = $"（{nodeindex + 1}）彩盒码:" & stxt(1)
                End If

            Next
        End If

    End Sub
    Private Sub txt_BosCode_PreviewKeyDown(sender As Object, e As PreviewKeyDownEventArgs) Handles txt_BosCode.PreviewKeyDown

        If e.KeyData = Keys.Enter Then

            If String.IsNullOrWhiteSpace(txt_BosCode.Text) Then
                G3label_tip.Text = "箱号为空，请输入箱号！"
                MsgBox("箱号为空，请输入箱号！")
                txt_BosCode.Focus()
                txt_BosCode.SelectAll()
                Me.txt_BosCode.Enabled = True
                Return
            End If
            'Dim jsonclass As JsonPtr = AccessApi2("http://uts-data.com/CommonApi/Get_Sn_Info"， "uts_zongqing", txt_BosCode.Text.Trim, _utsApp.ProcessStation.ParentProject.Index.ToString)
            Dim jsonclass As CombindSnInfo = g_Pcontrol.API_Get_Sn_Info(txt_BosCode.Text.Trim, _utsApp.ProcessStation.ParentProject.Index.ToString)
            If IsNothing(jsonclass) Then


                NodePtr = New TreeNode
                NodePtr.Text = "箱体码:" & txt_BosCode.Text.Trim
                NodePtr.Tag = Now



                Tree_ViewEx1.Nodes.Clear()
                Tree_ViewEx1.Nodes.Add(NodePtr)
                Tree_ViewEx1.Nodes(0).Expand()
                lab_sun.Text = $"0/{Max_Loading}"

                Me.txt_BosCode.Enabled = False
                Me.colorbox.Focus()
                Me.colorbox.SelectAll()

            Else
                G3label_tip.Text = "该箱号已使用，请更换箱号！"
                MsgBox("该箱号已使用，请更换箱号！")
                txt_BosCode.Focus()
                txt_BosCode.SelectAll()
                Me.txt_BosCode.Enabled = True
                Return
            End If



        End If


    End Sub







    'Public Function AccessApi2(uart As String, dbName As String, theKey As String， ProjectID As String， Optional dic As Dictionary(Of String, String) = Nothing) As JsonPtr

    '    Dim jsonString As String = String.Empty

    '    Dim ptr As String = $"Pwd=actop00803&DBName={dbName}&Key={theKey}"
    '    If Not IsNothing（dic） Then
    '        ptr = ptr & $"&JsonData={JsonConvert.SerializeObject(dic)}"
    '    End If
    '    ptr = ptr & $"&ProjectID={ProjectID}"
    '    '/http://uts-data.com/CommonApi/Combind_Sn_Info? Pwd%3D%26*$@%23235%26DBName%3Duts_zongqing%26Key%3DBarcode%26Barcode%3D1
    '    Try
    '        jsonString = PostData(uart, 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


    Private Sub btn_entering_Click(sender As Object, e As EventArgs) Handles btn_entering.Click

        'Select Case testcnt
        '    Case 0
        '        apitest.API_Queue_AllocationBarCode("1000785740027A", "1")
        '    Case 1
        '        Dim dic As New Dictionary(Of String， String）
        '        dic.Add("ColorBox_BarCode", "CTHM08711382257036759")
        '        apitest.API_Queue_Combind_Sn_Info("ColorBox_BarCode", "1", dic)
        '    Case 2
        '        apitest.API_Queue_Get_Sn_Info("1000785740027A", "1")
        'End Select
        'testcnt = testcnt + 1
        'If testcnt > 2 Then
        '    testcnt = 0
        'End If
        'Console.WriteLine($"{Date.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")}:回复对列数量:{apitest.g_API_Queue_ResultList.Count  }{vbCrLf }")

        If Tree_ViewEx1.Nodes.Count = 0 Then
            G3label_tip.Text = "未添加箱体码信息，请先添加箱体码信息再进行数据录入！"
            MsgBox("未添加箱体码信息，请先添加箱体码信息再进行数据录入！")
            txt_BosCode.Focus()
            txt_BosCode.SelectAll()
            Me.txt_BosCode.Enabled = True
            Return
        ElseIf Tree_ViewEx1.Nodes.Count = 1 Then
            If Tree_ViewEx1.Nodes(0).Nodes.Count < Max_Loading Then
                If MsgBox("该箱体未满。是否继续装载？", MsgBoxStyle.OkCancel) = MsgBoxResult.Ok Then
                    Me.colorbox.Focus()
                    Me.colorbox.SelectAll()
                    Return
                End If
            End If
            InputBoxInformation(Tree_ViewEx1)
            txt_BosCode.Focus()
            txt_BosCode.SelectAll()
            Me.txt_BosCode.Enabled = True
        Else
            G3label_tip.Text = "箱体码信息异常，请联系开发者"
            MsgBox("箱体码信息异常，请联系开发者")
            txt_BosCode.Focus()
            txt_BosCode.SelectAll()
            Me.txt_BosCode.Enabled = True
            Return
        End If

    End Sub
    Public Sub InputBoxInformation(TreeView As UTS_Core.UTSModule.Station.TreeViewEx)
        Dim Customfield As New Dictionary(Of String， String)
        Dim headnode As TreeNode = TreeView.Nodes(0)
        Dim jsonclass As CombindSnInfo
        Dim ricttxt As String = $"{Now:yyyy:HH:mm:ss:fff}:{headnode.Text} {vbCrLf },装载数量：{headnode.Nodes.Count}"
        Dim datenow As Date = CDate(headnode.Tag)
        Dim strbuff() As String = headnode.Text.Split(CChar(":"))
        For i As Integer = 0 To headnode.Nodes.Count - 1
            Dim index As TreeNode = headnode.Nodes(i)
            jsonclass = CType(index.Tag, CombindSnInfo)
            Customfield.Clear()
            Customfield.Add("OutBoxCode", strbuff(1))

            Customfield.Add("MacCode", jsonclass.data.Item("MACCODE"))
            Customfield.Add("SnCode", jsonclass.data.Item("BARCODE"))
            Customfield.Add("ColorBoxCode", jsonclass.data.Item("COLORBOX_BARCODE"))
            'Customfield.Add("label_string", jsonclass.data.Item("MACCODE"))
            Customfield.Add("UnitWeigth", jsonclass.data.Item("UNITWEIGTH"))

            'If Not SetMars_OutBoxCode(strbuff(1), jsonclass.Data.Mars_ColorBox_BarCode, jsonclass.Data.Mars_UnitWeigth) Then
            '    MsgBox($"第{i}个彩盒码录入数据库失败,请联系开发者。彩盒码：{jsonclass.Data.Mars_ColorBox_BarCode}")
            '    Me.colorbox.Focus()
            '    Me.colorbox.SelectAll()
            '    Return
            'End If
            Dim dic As New Dictionary(Of String， String)
            dic.Add("OutBoxCode", strbuff(1))
            dic.Add("UnitWeigth", jsonclass.data.Item("UNITWEIGTH"))
            dic.Add("ColorBox_BarCode", jsonclass.data.Item("COLORBOX_BARCODE"))
            ' dic.Add("MacCode", jsonclass.data.Item("MACCODE"))
            ' dic.Add("SnCode", jsonclass.data.Item("BARCODE"))
            TheTestResults(jsonclass.data.Item("BARCODE"), TestResult.TestResultEnum.Pass, datenow, Nothing, Customfield)
            g_Pcontrol.API_Queue_Combind_Sn_Info("ColorBox_BarCode", _utsApp.ProcessStation.ParentProject.Index.ToString, dic)
            If chk_flow.Checked Then
                g_Pcontrol.SetStationflag(_utsApp.ProcessStation.SnListOrder, jsonclass.data.Item("BARCODE"), "1")
            End If
            '  ricttxt = $"{ricttxt}{i}:{index.Text }{vbCrLf }"
        Next
        'ricttxt = $"{ricttxt}-----------------{vbCrLf}"
        'SetRichTextBox1Text(RichTextBox1, ricttxt, Color.Blue)
        ListBox1.Items.Add(ricttxt)

        'TestBoxnum = TestBoxnum + 1
        'Label3.Text = TestBoxnum.ToString & "箱"

        ' Isthread = True

        '  ThreadIsOpen(True)
        PrintfNum = PrintfNum + 1
        'Label7.Text = PrintfNum.ToString & "个"

        lab_Processed_Unit_Cnt_ThisCycle.Text = PrintfNum.ToString

        If _utsApp.ProcessStation.ParentProject.Index = 1 Then
            My.Settings.Mars_P2_cnt = My.Settings.Mars_P2_cnt + 1
            lab_Processed_Unit_Cnt.Text = My.Settings.Mars_P2_cnt.ToString
        ElseIf _utsApp.ProcessStation.ParentProject.Index = 2 Then
            My.Settings.Phobos_P2_cnt = My.Settings.Phobos_P2_cnt + PrintfNum
            lab_Processed_Unit_Cnt.Text = My.Settings.Phobos_P2_cnt.ToString
        End If
        G3label_tip.Text = "装箱完成!"
        My.Settings.Save()
    End Sub



    Public Function AccessApi1(uart As String, dbName As String, theKey As String， ProjectID As String， Optional dic As Dictionary(Of String, String) = Nothing) As ContJsonPtr

        Dim jsonString As String = String.Empty

        Dim ptr As String = $"Pwd=actop00803&DBName={dbName}&Key={theKey}"
        If Not IsNothing（dic） Then
            ptr = ptr & $"&JsonData={JsonConvert.SerializeObject(dic)}"
        End If
        ptr = ptr & $"&ProjectID={ProjectID}"

        Try
            jsonString = PostData(uart, ptr)
            Console.WriteLine(jsonString)

            If jsonString = Nothing Then
                Return Nothing
            End If
            Dim login As ContJsonPtr = JsonConvert.DeserializeObject(Of ContJsonPtr)(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

    Private Sub chk_auto_CheckedChanged(sender As Object, e As EventArgs) Handles chk_auto.CheckedChanged
        btn_entering.Enabled = Not chk_auto.Checked
    End Sub

    '  Private maclist As List(Of String）
    Private Sub ThreadIsOpen（isopen As Boolean）
        'If isopen Then
        '    If Thread_setapi.IsAlive Then
        '        Thread_setapi.Abort()
        '        Thread_setapi = New Thread(AddressOf Threadsetapistart)
        '    End If
        '    Thread_setapi.Start()
        'Else
        '    If Thread_setapi.IsAlive Then
        '        Thread_setapi.Abort()
        '    End If
        '    Thread_setapi.Abort()
        '    Thread_setapi = New Thread(AddressOf Threadsetapistart)

        'End If
    End Sub
    Public Isthread As Boolean

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

    End Sub



    'Public Sub Threadsetapistart()
    '    While True
    '        If Isthread Then
    '            Dim headnode As TreeNode = Tree_ViewEx1.Nodes(0)


    '            Dim li As New List(Of String)
    '            For i As Integer = 0 To headnode.Nodes.Count - 1
    '                If chk_auto.Checked Then
    '                    Dim jsonclass As JsonPtr
    '                    Dim index As TreeNode = headnode.Nodes(i)
    '                    jsonclass = CType(index.Tag, JsonPtr)
    '                    li.Add(jsonclass.Data.Barcode)
    '                    '
    '                End If
    '            Next

    '            For Each strindex As String In li
    '                g_Pcontrol.SetStationflag("P2", strindex, "1")
    '            Next

    '            Isthread = False
    '            Exit While
    '        End If

    '        Thread.Sleep(100)
    '    End While
    'End Sub

#End Region



#Region "测试流程"

#End Region
    Public g_totalcnt_Press_Cnt As Integer
    Public g_thistimecnt_Press_Cnt As Integer
    Private Sub lab_Processed_Unit_Cnt_Click(sender As Object, e As EventArgs) Handles lab_Processed_Unit_Cnt.Click
        g_totalcnt_Press_Cnt += 1

        If g_totalcnt_Press_Cnt >= 5 Then

            lab_Processed_Unit_Cnt.Text = "0"
            If _utsApp.ProcessStation.ParentProject.Index = 1 Then
                My.Settings.Mars_P2_cnt = 0
            ElseIf _utsApp.ProcessStation.ParentProject.Index = 2 Then
                My.Settings.Phobos_P2_cnt = 0
            End If
            ' My.Settings.Phobos_T1 = 0
            My.Settings.Save()
        End If

    End Sub

    Private Sub lab_Processed_Unit_Cnt_ThisCycle_Click(sender As Object, e As EventArgs) Handles lab_Processed_Unit_Cnt_ThisCycle.Click
        g_thistimecnt_Press_Cnt += 1

        If g_thistimecnt_Press_Cnt >= 5 Then
            PrintfNum = 0
            lab_Processed_Unit_Cnt_ThisCycle.Text = "0"
        End If
    End Sub

    Private Sub chk_flow_Click(sender As Object, e As EventArgs) Handles chk_flow.Click

        Dim strInputMsg As String = InputBox("请输入用户密码", "密码确认")
        If strInputMsg <> "Cc2022OK" Then
            chk_flow.Checked = Not chk_flow.Checked
            Return
        End If

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





