Namespace UTSModule.Test.Command.ComPortCommand
    Public Class OpenComPortExecutor
        Inherits TestCommandExecutor

        Private ReadOnly _portList As List(Of ComPort)

        Private ReadOnly _portName As String

        Private ReadOnly _portParam As String

        Private ReadOnly _receiveTimeout As Integer

        Private _comPort As ComPort


        Public Sub New(command As TestCommand, portList As List(Of ComPort))
            MyBase.New(command)

            _portList = portList

            _portName = command.Parameter(0)
            _portParam = command.Parameter(1)
            _receiveTimeout = CInt(command.Parameter(2))

        End Sub

        Public Overrides Function Execute() As TestCommandReturn
            '从历史使用串口中查询
            If ComPortCommandManager.FindComPort(_portName, _comPort) = False Then
                Dim names As String() = IO.Ports.SerialPort.GetPortNames()
                For Each name As String In names
                    If String.Compare(_portName, name, True) = 0 Then
                        _comPort = New ComPort(_portName, String.Empty)
                        _portList.Add(_comPort)
                    End If
                Next
            End If

            '未查询到有效串口
            If _comPort Is Nothing Then
                CommandReturn.ExecuteResultTipString = $"串口打开失败,未查询到串口[{_portName}]存在"
                CommandReturn.ExecuteResult = False
                Return CommandReturn
            End If

            '未初始化成功
            _comPort.DefaultTimeout = _receiveTimeout
            If _comPort.InitializePort(_portParam) = False Then
                CommandReturn.ExecuteResultTipString = $"串口打开失败,无效的串口参数"
                CommandReturn.ExecuteResult = False
                Return CommandReturn
            End If

            '打开串口
            If _comPort.Open() Then
                CommandReturn.ExecuteResultTipString = $"串口打开成功"
                CommandReturn.ExecuteResult = True
            Else
                CommandReturn.ExecuteResultTipString = $"串口打开失败"
                CommandReturn.ExecuteResult = False
            End If


            Return CommandReturn
        End Function
    End Class
End Namespace