Imports System.IO
Imports System.IO.Ports
Imports UTS_Core.DebugLog
Imports UTS_Core.UTSModule
Imports UTS_Core.UTSModule.Station

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

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

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

        'InitGrid(_stationPlan)

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


    End Sub


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

        Show()
    End Sub
#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

    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
        '收到数据
        If SerialPort1.ReadBufferSize > 0 Then
            g_strRcvd += SerialPort1.ReadLine
            g_LastRcvdData_TimePoint = DateTime.Now
        End If

        'ST,NT,+  197.9 g
        'US,NT,+  197.4 g 
        'US,NT,+  197.4 g
        '收到换行符号或长度大于=18
        If Microsoft.VisualBasic.Right(g_strRcvd, 2) = vbCrLf OrElse g_strRcvd.Length >= 18 Then
            '以长度为判断依据
            If g_strRcvd.Length = 18 Then
                '判断稳定状态
                Dim tmpStableStr As String = Microsoft.VisualBasic.Mid(g_strRcvd, 6, 2).Trim
                If tmpStableStr = "ST" Then
                    '稳定
                    g_ScaleData.isStable = ScaleIsStable_Enum.stable
                    g_ScaleData.isDataReady = False
                ElseIf tmpStableStr = "US" Then
                    '不稳定
                    g_ScaleData.isStable = ScaleIsStable_Enum.unstable
                    g_ScaleData.isDataReady = False
                Else
                    '非法数据
                    g_strRcvd = ""
                    Exit Sub
                End If

                '判断单位
                Dim tmpUnit As String = Microsoft.VisualBasic.Mid(g_strRcvd, 20, 2).Trim
                If tmpUnit = "g" Then
                    g_ScaleData.weight_unit = ScaleUnit_Enum.g
                ElseIf tmpUnit = "kg" Then
                    g_ScaleData.weight_unit = ScaleUnit_Enum.kg
                Else
                    '非法数据
                    g_strRcvd = ""
                    Exit Sub
                End If

                '计算重量
                Dim tmpWeight As String = Microsoft.VisualBasic.Mid(g_strRcvd, 13, 7).Trim
                If Double.TryParse(tmpWeight, g_ScaleData.weight_g) Then
                    If g_ScaleData.weight_unit = ScaleUnit_Enum.kg Then g_ScaleData.weight_g = g_ScaleData.weight_g * 1000
                Else
                    '非法数据
                    g_strRcvd = ""
                    Exit Sub
                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 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

    End Sub

#End Region
End Class