Imports System.Text

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

        Private _comPort As ComPort
        Private ReadOnly _portName As String
        Private ReadOnly _sendText As String
        Private ReadOnly _receiveTimeout As Integer

        Public Sub New(command As TestCommand)
            MyBase.New(command)

            _portName = command.Parameter(0)
            _sendText = command.Parameter(1)
            If command.Parameter(2) = "1" Then _sendText = _sendText & vbCrLf

            _receiveTimeout = CInt(command.Parameter(3))

            CommandReturn.LowerLimit = TestCommand.Parameter(4)
            CommandReturn.UpperLimit = TestCommand.Parameter(5)
        End Sub

        Public Overrides Function Execute() As TestCommandReturn
            '从历史使用串口中查询
            If ComPortCommandManager.FindComPort(_portName, _comPort) = False Then
                CommandReturn.ExecuteResultTipString = $"无效的串口名"
                CommandReturn.ExecuteResult = False
                Return CommandReturn
            End If

            '串口发送
             _comPort.ClearRecvCache()
            If _comPort.WriteText(_sendText) = False Then
                CommandReturn.ExecuteResult = False
                CommandReturn.ExecuteResultTipString = "执行串口通讯发送异常"
                Return CommandReturn
            End If

            '串口接收
            Dim buf() As Byte = _comPort.ReadBytes(_receiveTimeout)
            If buf.Length = 0 Then
                CommandReturn.RecordValue = String.Empty
                CommandReturn.ExecuteResult = False
                CommandReturn.ExecuteResultTipString = "执行串口通讯接收异常"
                Return CommandReturn
            End If

            '接收正常,处理数据是否在期望范围内
            CommandReturn.RecordValue = Encoding.UTF8.GetString(buf)
            CommandReturn.ExecuteResult = CompareFunction.StringCompare(CommandReturn.RecordValue, CommandReturn.LowerLimit, CommandReturn.UpperLimit)
            If CommandReturn.ExecuteResult Then
                CommandReturn.ExecuteResultTipString = "执行串口通讯收发正常，数据在有效范围内"
            Else
                CommandReturn.ExecuteResultTipString = "执行串口通讯收发正常，数据在有效范围外"
            End If

            Return CommandReturn
        End Function
    End Class
End Namespace