Imports System.IO
Imports System.IO.Ports
Imports _485_BurningTool.BLV_Bootloader
Imports _485_BurningTool.CommunicationFlow
Imports _485_BurningTool.DataProcessing
Imports _485_BurningTool.RuningLog
Imports Newtonsoft.Json


Public Class Form1

    Private m_CommunicationFlow As CommunicationProtocolEntity
    Dim m_Applicationconfig As Dictionary(Of String, String)

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

        Text = $"{Application.ProductName}_V{Application.ProductVersion}"
        DataGridView1.ColumnHeadersDefaultCellStyle.Font = New Font("宋体", 12, FontStyle.Bold)


        Cmb_CommunicationMode_GetProtocolList()
        Cmb_CommunicationProtocol_GetProtocolList()
        CreateCommunicationFlow()


        LoadNetworkSettings()
        LoadSettings()
    End Sub

    '加载网络设置
    Public Sub LoadNetworkSettings()
        CboLocalIp.Items.Clear()
        CboLocalIp.Items.AddRange(GetLocalIp().ToArray)
        CboLocalIp.SelectedIndex = 0
        NudLocalPort.Value = 5580
        NudRemotePort.Value = 3341

    End Sub


    '判断键值对存不存该键值
    ''' <summary>
    ''' 
    ''' </summary>
    ''' <param name="key"></param>
    ''' <param name="mode">1获取 2设置</param>
    ''' <returns></returns>
    Private Function m_ApplicationconfigContainsKey(key As String, Optional val As String = Nothing, Optional mode As Integer = 1) As String
        If m_Applicationconfig.ContainsKey(key) Then
            If mode = 1 Then
                Return m_Applicationconfig(key)
            ElseIf mode = 2 Then
                m_Applicationconfig(key) = val
            End If
        Else
            If mode = 1 Then
                Return Nothing
            Else
                m_Applicationconfig.Add(key, val)
            End If

        End If
    End Function

    Private Sub SaveSettings()


        m_ApplicationconfigContainsKey("Cbo_Port", Cbo_Port.SelectedIndex, 2)
        m_ApplicationconfigContainsKey("cbo_Baud", Cbo_Baud.SelectedIndex, 2)
        My.Settings.m_Applicationconfig = JsonConvert.SerializeObject(m_Applicationconfig) '
        My.Settings.BootBaud = CInt(Text_BootBaud.Text)
        My.Settings.UpBaud = CInt(c_UpBaud.Text)
        My.Settings.ProtocolName = Cmb_CommunicationProtocol.Text
        My.Settings.HexFilePath = Tb_HexFilePath.Text
        My.Settings.Save()
    End Sub

    '创建通信对象
    Private Sub CreateCommunicationFlow()
        If m_CommunicationFlow Is Nothing Then
            m_CommunicationFlow = New CommunicationProtocolEntity()
        End If
    End Sub

    '获取协议列表
    Private Sub Cmb_CommunicationMode_GetProtocolList()
        Cmb_CommunicationMode.Items.Clear()
        Dim protocolList As List(Of String) = GetProtocolList(GetType(CommunicationType))
        Cmb_CommunicationMode.Items.AddRange(protocolList.ToArray())
        'If Cmb_CommunicationMode.Items.Count > 0 Then
        '    Cmb_CommunicationMode.SelectedIndex = 0
        'End If
    End Sub
    '获取协议列表
    Private Sub Cmb_CommunicationProtocol_GetProtocolList()
        Cmb_CommunicationProtocol.Items.Clear()
        Dim protocolList As List(Of String) = GetProtocolList(GetType(ProtocolEnum))
        Cmb_CommunicationProtocol.Items.AddRange(protocolList.ToArray())
        'If Cmb_CommunicationProtocol.Items.Count > 0 Then
        '    Cmb_CommunicationProtocol.SelectedIndex = 0
        'End If
    End Sub

    '获取枚举描述
    Private Function GetProtocolList(enumValue As Type) As List(Of String)
        Dim protocolList As New List(Of String)

        Dim enumValues() As Integer = CType([Enum].GetValues(enumValue), Integer())
        Dim minValue As Integer = enumValues.Min()
        Dim maxValue As Integer = enumValues.Max()
        Dim index As Integer

        For i = minValue To maxValue - 1
            index = i
            protocolList.Add($"{i.ToString}|{GetEnumDescription([Enum].Parse(enumValue, index))}")
        Next
        Return protocolList
    End Function

    Private Function LoadSettings() As Boolean
        Try
            My.Settings.Reload()
            m_Applicationconfig = JsonConvert.DeserializeObject(Of Dictionary(Of String, String))(My.Settings.m_Applicationconfig)
        Catch ex As Exception
            Return False
        End Try
        Dim Portindex As Integer = 0
        Dim Baudindex As Integer = 0
        Dim BootBaud As Integer = My.Settings.BootBaud
        Dim UpBaud As Integer = My.Settings.UpBaud
        If Not IsNothing（m_Applicationconfig） Then
            Try
                Integer.TryParse(m_Applicationconfig("Cbo_Port"), Portindex)
                Integer.TryParse(m_Applicationconfig("cbo_Baud")， Baudindex)

            Catch ex As Exception

            End Try
        Else
            m_Applicationconfig = New Dictionary(Of String, String)
        End If

        Cbo_Port_DropDown(Nothing, Nothing)
        'CCbo_Baud_DropDown(Nothing, Nothing)
        If Portindex < 0 Then Portindex = 0
        If Portindex < Cbo_Port.Items.Count Then
            'Cbo_Port.SelectedIndex = Portindex
            Cbo_Port.Text = Cbo_Port.Items(Portindex)
        End If
        Text_BootBaud.Text = BootBaud
        c_UpBaud.Text = UpBaud
        Cbo_Baud.Text = Cbo_Baud.Items(Baudindex)
        If Not String.IsNullOrEmpty(My.Settings.HexFilePath) Then
            Tb_HexFilePath.Text = My.Settings.HexFilePath
        End If

        Cmb_CommunicationProtocol.Text = My.Settings.ProtocolName
        Cmb_CommunicationProtocol_SelectedIndexChanged(Nothing, Nothing)
        Return True
    End Function

    Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
        ' LoadSettings()
        SaveSettings()
    End Sub

    Private Sub ToolStripButton1_Click(sender As Object, e As EventArgs)
        RText_OutputText.Clear()
    End Sub

    Private Sub RText_OutputText_TextChanged(sender As Object, e As EventArgs) Handles RText_OutputText.TextChanged
        If RText_OutputText.Lines.Length > 10000 Then
            Dim lines() As String = RText_OutputText.Lines
            Dim newLines(lines.Length - 1000) As String
            Array.Copy(lines, 1000, newLines, 0, newLines.Length)
        End If
        RText_OutputText.ScrollToCaret()
    End Sub

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

    End Sub

    Private Sub Cbo_Port_DropDown(sender As Object, e As EventArgs) Handles Cbo_Port.DropDown
        Cbo_Port.Items.Clear()
        Cbo_Port.Items.AddRange(SerialPort.GetPortNames())

    End Sub
    Public IsUpgradeAllSel As Boolean = False
    Private Sub DataGridView1_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
        Try


            If e.ColumnIndex = 1 Then
                'Console.WriteLine(DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).EditedFormattedValue)
                'Console.WriteLine(DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value)
                If DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value = 1 Then
                    DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value = 0
                    IsUpgradeAllSel = True
                    Chk_UpgradeAllSel.Checked = False
                    IsUpgradeAllSel = False
                Else
                    DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value = 1
                    For i = 0 To DataGridView1.Rows.Count - 1
                        If DataGridView1.Rows(i).Cells(1).Value = 0 Then
                            Return
                        End If
                    Next
                    IsUpgradeAllSel = True
                    Chk_UpgradeAllSel.Checked = True
                    IsUpgradeAllSel = False
                End If

            End If
        Catch ex As Exception

        End Try
    End Sub


    Private Sub Btn_OpenPort_Click(sender As Object, e As EventArgs) Handles Btn_OpenPort.Click
        If Btn_OpenPort.Text = "关闭连接" Then
            Btn_OpenPort.Text = "打开连接"
            Btn_OpenPort.BackColor = Color.Transparent
            Cbo_Port.Enabled = True
            Cbo_Baud.Enabled = True
            m_CommunicationFlow.m_Transmitter.CloseTransmitter()
        Else

            Cbo_Port.Enabled = False
            Cbo_Baud.Enabled = False
            If IsNothing(m_CommunicationFlow.m_Transmitter) Then
                Tab_SerialSettings_SelectedIndexChanged(Nothing, Nothing)
            End If
            m_CommunicationFlow.RefreshTransmitter()
            Btn_OpenPort.Text = "关闭连接"
            Btn_OpenPort.BackColor = Color.Red
            Select Case Tab_SerialSettings.SelectedIndex
                Case 0
                    m_CommunicationFlow.m_Transmitter.SetTransmitterParameter(Cbo_Port.Text， CInt(Cbo_Baud.Text))
                Case 1
                    m_CommunicationFlow.m_Transmitter.SetTransmitterParameter(CboLocalIp.Text, NudLocalPort.Value, CboLongIP.Text, NudRemotePort.Value)
            End Select
            m_CommunicationFlow.m_Transmitter.OpenTransmitter()
            If m_CommunicationFlow.m_Transmitter.IsTransmitter AndAlso m_CommunicationFlow.m_Transmitter.GetTransmitterStatus Then
            Else
                MsgBox("创建连接失败！")
                Btn_OpenPort_Click(Nothing, Nothing)
                Return
            End If

        End If

    End Sub

    Private Sub Cbo_Port_SelectedIndexChanged(sender As Object, e As EventArgs) Handles Cbo_Port.SelectedIndexChanged
        '判断通信对象是否实例化
        'If IsNothing(m_CommunicationFlow.m_Transmitter) Then
        '    Tab_SerialSettings_SelectedIndexChanged(Nothing, Nothing)
        'End If
        'If String.IsNullOrEmpty(Cbo_Port.Text) Then
        '    MsgBox("选择未知串口")
        '    Return
        'End If
        'm_CommunicationFlow.m_Transmitter.SetTransmitterParameter(Cbo_Port.Text)
    End Sub

    Private Sub Cmb_CommunicationProtocol_SelectedIndexChanged(sender As Object, e As EventArgs) Handles Cmb_CommunicationProtocol.SelectedIndexChanged
        'If m_CommunicationFlow.m_CommunicationTypeIndex = CommunicationType.None Then
        '    MsgBox("请先选择通信器通信方式!")
        '    Return
        'End If
        If String.IsNullOrEmpty(Cmb_CommunicationProtocol.Text) Then Return
        Dim strbuuf() As String = Cmb_CommunicationProtocol.Text.Split("|")
        m_CommunicationFlow.ChangeProtocol(strbuuf(1))
    End Sub

    Private Sub Btn_Search_Click_1(sender As Object, e As EventArgs) Handles Btn_Search.Click
        If Btn_Search.Text = "停止搜索" Then
            If Not IsNothing(m_CommunicationFlow.m_Receiver) Then
                Dim mReceiver As BLV_Bootloader = m_CommunicationFlow.m_Receiver
                m_CommunicationFlow.m_Receiver.SetSearchEquipmentProcessSwitch(False)
                m_CommunicationFlow.SetThreadFlag(False)
                m_CommunicationFlow.m_Transmitter.ClearReadData()
            End If

            If IsNothing(sender) Then Return
            Btn_Search.Text = "搜索"
            OutputLogsToTheControl(RText_OutputText, New RuningLogConfig("停止搜索设备!", Color.Black), 1)

        Else
            Btn_Search.Text = "停止搜索"

            If IsNothing(m_CommunicationFlow.m_Transmitter) OrElse m_CommunicationFlow.m_Transmitter.IsTransmitter = False Then
                MsgBox("发送器未打开，请先打开发送器！")
                Btn_Search.PerformClick()
                Return
            End If
            If IsNothing(m_CommunicationFlow.m_Receiver) Then
                MsgBox("请先选择通信协议")
                Btn_Search.PerformClick()
                Return
            Else
                Dim BootTimeout, Myaddr, startaddr, stopaddr, EffTimeTime, vsendTimeout, UpBaud As Integer
                If Not GetinputTextToint(txt_BootTimeout.Text, BootTimeout) Then
                    MsgBox("未输入正确的超时时间！")
                    Btn_Search.PerformClick()
                    Return
                End If
                If Not GetinputTextToint(EffTime.Text, EffTimeTime) Then
                    MsgBox("未输入正确的有效时间！")
                    Btn_Search.PerformClick()
                    Return
                End If
                'If Not Integer.TryParse(Txt_Myaddr.Text, Myaddr) Then
                '    MsgBox("未输入正确的本机地址！")
                '    Btn_Search.PerformClick()
                '    Return
                'End If
                'If Not Integer.TryParse(Txt_startaddr.Text, startaddr) OrElse Not Integer.TryParse(Txt_stopaddr.Text, startaddr) Then
                '    MsgBox("未输入正确的起始地址或结束地址！")
                '    Btn_Search.PerformClick()
                '    Return
                'End If
                If Not Integer.TryParse(Sendtimeout.Text, vsendTimeout) Then
                    MsgBox("未输入正确的超时时间！")
                    Btn_Search.PerformClick()
                    Return
                End If
                DataGridView1.Rows.Clear()

                '判断协议类对象是否是实例化
                If m_CommunicationFlow.IsCreateProtocol Then

                    OutputLogsToTheControl(RText_OutputText, New RuningLogConfig("开始搜索设备!", Color.Black), 1)
                    Dim li As List(Of (number As Integer, Cmdconfig)) = New List(Of (number As Integer, Cmdconfig))

                    Dim d_Cmdconfig As Cmdconfig = New Cmdconfig({CmdType.SearchCommand, 1, 0, 10， vsendTimeout})


                    'Integer.TryParse(txt_BootTimeout.Text, BootTimeout)
                    d_Cmdconfig.CmdArgs.Add(BootTimeout)
                    d_Cmdconfig.CmdArgs.Add(EffTimeTime)
                    d_Cmdconfig.SetProtocol(m_CommunicationFlow.m_Receiver)
                    d_Cmdconfig.setCmdSendcontinueTime(60)
                    li.Add((CmdType.SearchCommand, d_Cmdconfig))
                    m_CommunicationFlow.m_Transmitter.ClearSendData()
                    'm_CommunicationFlow.m_Receiver.MainProcess(WorkflowType.SearchEquipment, li, 60, DataGridView1, RText_OutputText, CInt(Txt_Myaddr.Text), CInt(Txt_startaddr.Text), CInt(Txt_stopaddr.Text), CInt(Cbo_Baud.Text), Btn_Search)

                    If mtest(CmdType.SearchCommand, WorkflowType.SearchEquipment, li, Btn_Search) Then

                    Else
                        OutputLogsToTheControl(RText_OutputText, New RuningLogConfig("参数异常,搜索结束!", Color.Red), 1)
                        'Btn_Search_Click_1(Nothing, Nothing)
                    End If
                Else
                    MsgBox("请先选择通信协议")

                End If
            End If
            ' OutputLogsToTheControl(RText_OutputText, New RuningLogConfig("结束搜索设备!", Color.Black), 1)
            'Btn_Search_Click_1(Nothing, Nothing)


        End If

    End Sub

    Public Function mtest(gCmdType As Integer, gWorkflowType As Integer, li As List(Of (number As Integer, Cmdconfig)), btn As Button， Optional addtypeli As List(Of (Integer, Integer)) = Nothing) As Boolean
        Dim Parameterlist As Parameterlist = CreateParameterlist(gCmdType, li, gWorkflowType, btn， 0)
        If IsNothing(Parameterlist) Then Return False
        'Parameterlist.CmdSendcontinueTime = 60
        RText_OutputText.Clear()
        Parameterlist.addtypeli = addtypeli
        Try

            m_CommunicationFlow.SetThreadParameter(Parameterlist)
        Catch ex As Exception
            Console.WriteLine(ex.Message)
            Return False
        End Try

        Return True
    End Function
    '创建Parameterlist对象
    ''' <summary>
    ''' 
    ''' </summary>
    ''' <param name="CurrentStep">第一个流程节点</param>
    ''' <param name="li">流程列表</param>
    ''' <param name="Action">功能类型</param>
    ''' <param name="btn">触发按钮</param>
    ''' <param name="NextAction">运行状态</param>
    ''' <returns></returns>
    Public Function CreateParameterlist(CurrentStep As Integer, li As List(Of (number As Integer, Cmdconfig)), Action As Integer, btn As Button, NextAction As Integer) As Parameterlist
        Dim Parameterlist As New Parameterlist
        Dim BootTimeout, NTimeOut, Myaddr, startaddr, stopaddr, EffTimeTime, bootbaud, Appbaud, UpBaud, cDevNumber, DeviceType, TransnDuion, Throughport As Integer
        cDevNumber = 1
        If Not GetinputTextToint(txt_BootTimeout.Text, BootTimeout) Then
            MsgBox("未输入正确的超时时间！")
            btn.PerformClick()
            Return Nothing
        End If

        If Not GetinputTextToint(EffTime.Text, EffTimeTime) Then
            MsgBox("未输入正确的有效时间！")
            btn.PerformClick()
            Return Nothing
        End If
        If Not GetinputTextToint(Txt_Myaddr.Text, Myaddr) Then
            MsgBox("未输入正确的本机地址！")
            btn.PerformClick()
            Return Nothing
        End If
        If Not GetinputTextToint(Txt_startaddr.Text, startaddr) Then
            MsgBox("未输入正确的起始地址或结束地址！")
            btn.PerformClick()
            Return Nothing
        End If
        If Not GetinputTextToint(Txt_stopaddr.Text, stopaddr) Then
            MsgBox("未输入正确的发送范围！")
            btn.PerformClick()
            Return Nothing
        End If
        If Not GetinputTextToint(l_DeviceType.Text, DeviceType) Then
            MsgBox("设备类型输入错误！")
            btn.PerformClick()
            Return Nothing
        End If
        If Not Integer.TryParse(Cbo_Baud.Text, UpBaud) Then
            MsgBox("未输入正确的APP波特率！")
            btn.PerformClick()
            Return Nothing
        End If
        If Not Integer.TryParse(Text_BootBaud.Text, bootbaud) Then
            MsgBox("未输入正确的Boot波特率！")
            btn.PerformClick()
            Return Nothing

        End If

        If Action = WorkflowType.FlashGroupUpgrade OrElse Action = WorkflowType.FlashWrite Then
            If Not Integer.TryParse(c_UpBaud.Text, Appbaud) Then
                MsgBox("未输入正确的升级波特率！")
                btn.PerformClick()
                Return Nothing
            End If
        End If

        If Tab_SerialSettings.SelectedIndex = 1 Then
            If String.IsNullOrEmpty(Me.Throughport.Text) OrElse Not Integer.TryParse(Me.Throughport.Text, Throughport) Then
                MsgBox("未选择透传串口！")
                btn.PerformClick()
                Return Nothing
            End If
            If String.IsNullOrEmpty(TransmissionDuration.Text) OrElse Not Integer.TryParse(TransmissionDuration.Text, TransnDuion) Then
                MsgBox("未输入透传超时时间！")
                btn.PerformClick()
                Return Nothing
            End If



        End If
        If Tab_SerialSettings.SelectedIndex = 1 Then
            If Not Integer.TryParse(NudTimeOut1.Text, NTimeOut) Then
                MsgBox("未输入正确的透传超时时间！")
                btn.PerformClick()
                Return Nothing
            End If
        End If

        If startaddr = 255 Then
            If Not Integer.TryParse(DevNumber.Text, cDevNumber) Then
                MsgBox("未输入正确的设备数量！")
                btn.PerformClick()
                Return Nothing
            End If
        End If
        Parameterlist.NTimeOut = NTimeOut
        Parameterlist.Throughport = Throughport
        Parameterlist.TransnDuion = TransnDuion
        Parameterlist.DevNumber = cDevNumber
        Parameterlist.EnableFlag = True
        Parameterlist.Action = Action
        Parameterlist.StartAddress = Myaddr
        Parameterlist.ReceiveAddress = startaddr
        Parameterlist.ReceiveAddressRangeLength = stopaddr
        Parameterlist.DeviceType = DeviceType
        Parameterlist.AppBaudRate = UpBaud
        Parameterlist.btn = btn
        Parameterlist.DataGrid = DataGridView1
        Parameterlist.RText_OutputText = RText_OutputText
        Parameterlist.BootBaudRate = bootbaud
        Parameterlist.ProcessList = li
        Parameterlist.CurrentStep = CurrentStep
        Parameterlist.NextAction = NextAction
        Parameterlist.UpgradeBaudRate = Appbaud
        Return Parameterlist
    End Function

    Public Function GetinputTextToint(str As String, ByRef result As Integer) As Boolean
        '判断字符串是不是Hex字符串
        If IsHexStr(str) Then
            '将HEx字符串转换为byte
            result = Convert.ToInt32(str, 16)
            Return True
        End If
        Return False
    End Function
    Public Function IsHexStr(str As String) As Boolean
        Dim reg As New System.Text.RegularExpressions.Regex("^[0-9A-Fa-f]+$")
        Return reg.IsMatch(str)
    End Function


    Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
        Dim dlg As New OpenFileDialog
        dlg.InitialDirectory = Application.StartupPath
        dlg.Filter = "Logic File|*.dat;*.ihex;*.hex;*.bin;"
        Dim oldPath As String = Tb_HexFilePath.Text
        If System.IO.File.Exists(oldPath) Then
            dlg.InitialDirectory = System.IO.Path.GetDirectoryName(oldPath)
            dlg.FileName = oldPath
        Else
            dlg.InitialDirectory = Application.StartupPath
        End If

        If dlg.ShowDialog() = Windows.Forms.DialogResult.OK Then
            Tb_HexFilePath.Text = dlg.FileName
            ' btn_Reload.PerformClick()
            ParsSelectedUpgradeFile(Tb_HexFilePath.Text)
        End If
    End Sub
    '解析选取的升级文件
    Public Function ParsSelectedUpgradeFile(filepath As String) As SendFileconig
        'Dim resultli As List(Of (number As Integer, Byte()))
        '判断文件存不存在
        If Not System.IO.File.Exists(filepath) Then
            MsgBox("文件不存在！")
            Return Nothing
        End If
        '判断文件格式
        If System.IO.Path.GetExtension(filepath).ToLower() = ".ihex" OrElse System.IO.Path.GetExtension(filepath).ToLower() = ".hex" Then
            Dim resultli = ParsHexFile(filepath)
            Dim tmpStrCks As String = ""
            If resultli.IsFileAnalysis Then
                Dim tmpHexValidLenght As UInt32 = resultli.EndAddr - resultli.SendAddr
                MsgBox("Hex 装载成功！" & vbCrLf &
                  "起始偏移地址 ：0x" & Hex(resultli.SendAddr) & vbCrLf &
                  "    结束地址 ：0x" & Hex(resultli.EndAddr) & vbCrLf &
                  "    文件长度 ：" & tmpHexValidLenght.ToString & vbCrLf &
                   "    文件版本 ：" & resultli.NVersions & vbCrLf
                  )
                Dim checkSum(3) As Byte
                CalcCheckSum(resultli.Sendlist, resultli.SendLen, checkSum)
                tmpStrCks = HexByte2Str(checkSum(3))
                tmpStrCks = tmpStrCks & " " & HexByte2Str(checkSum(2))
                tmpStrCks = tmpStrCks & " " & HexByte2Str(checkSum(1))
                tmpStrCks = tmpStrCks & " " & HexByte2Str(checkSum(0))

                If String.IsNullOrEmpty(resultli.NVersions) Then
                    Label27.Text = "未识别"
                Else
                    Label27.Text = resultli.NVersions.Replace("_", " ")
                End If


                lab_HexLastModifyDate.Text = IO.File.GetLastWriteTime(Tb_HexFilePath.Text)
                lab_HexDataLenght.Text = Format(tmpHexValidLenght, "###,###") & " Bytes"
                lab_HexDataCks.Text = tmpStrCks
                Label22.Text = "0x" & Hex(resultli.SendAddr)
                Label23.Text = "0x" & Hex(resultli.EndAddr)
            Else
                MsgBox(resultli.Analysis)
            End If
            Return resultli
        ElseIf System.IO.Path.GetExtension(filepath).ToLower() = ".dat" OrElse System.IO.Path.GetExtension(filepath).ToLower() = ".bin" Then
            Dim resultli As SendFileconig
            Dim datalen As Integer

            If GetinputTextToint(ToolStripTextBox1.Text, datalen) Then
            Else
                MsgBox("bin文件起始地址输入有误！")
                Return Nothing
            End If

            resultli = ParsbinFile(datalen, filepath)
            Dim tmpStrCks As String = ""
            If resultli.IsFileAnalysis Then
                Dim tmpHexValidLenght As UInt32 = resultli.EndAddr - resultli.SendAddr
                MsgBox("Hex 装载成功！" & vbCrLf &
                  "起始偏移地址 ：0x" & Hex(resultli.SendAddr) & vbCrLf &
                  "    结束地址 ：0x" & Hex(resultli.EndAddr) & vbCrLf &
                  "    文件长度 ：" & tmpHexValidLenght.ToString & vbCrLf &
                   "    文件版本 ：" & resultli.NVersions & vbCrLf
                  )
                Dim checkSum(3) As Byte
                CalcCheckSum(resultli.Sendlist, resultli.SendLen, checkSum)
                tmpStrCks = HexByte2Str(checkSum(3))
                tmpStrCks = tmpStrCks & " " & HexByte2Str(checkSum(2))
                tmpStrCks = tmpStrCks & " " & HexByte2Str(checkSum(1))
                tmpStrCks = tmpStrCks & " " & HexByte2Str(checkSum(0))

                If String.IsNullOrEmpty(resultli.NVersions) Then
                    Label27.Text = "未识别"
                Else
                    Label27.Text = resultli.NVersions.Replace("_", " ")
                End If


                lab_HexLastModifyDate.Text = IO.File.GetLastWriteTime(Tb_HexFilePath.Text)
                lab_HexDataLenght.Text = Format(tmpHexValidLenght, "###,###") & " Bytes"
                lab_HexDataCks.Text = tmpStrCks
                Label22.Text = "0x" & Hex(resultli.SendAddr)
                Label23.Text = "0x" & Hex(resultli.EndAddr)
            Else
                MsgBox(resultli.Analysis)
            End If
            Return resultli

        End If
        Return Nothing

    End Function
    Private Function HexByte2Str(hexByte As Byte) As String
        If hexByte < 16 Then
            Return "0" & Hex(hexByte)
        Else
            Return Hex(hexByte)
        End If
    End Function
    Public Function ParsbinFile(start As Long， filepath As String) As SendFileconig
        Dim resultli As SendFileconig = New SendFileconig
        resultli.IsFileAnalysis = False
        resultli.Sendlist.Clear()
        Dim datalen As Integer = 0 '256
        Dim kuai As Integer = 512
        If Integer.TryParse(txt_BlockLength.Text, kuai) Then
            resultli.BlockLength = kuai
        Else
            MsgBox("块大小异常！")
            resultli.Analysis = "块大小异常！！"
            Return resultli
        End If


        If Integer.TryParse(txt_cdataleng.Text, datalen) Then

        Else
            MsgBox("数据长度输入有误！")
            resultli.Analysis = "数据长度输入有误！！"
            Return resultli
        End If


        ''以二进制读取文件内容
        Dim dataFile() As Byte = File.ReadAllBytes(filepath)

        '以datalen 为单位，将文件内容拆分成多个数组 添加到  resultli.Sendlist 中
        Dim temp As Byte()
        Dim li As List(Of Byte）
        Dim kuaiaddr As Integer
        Dim chazhi As Integer = 0
        Dim datalen2 As Integer
        chazhi = dataFile.Length Mod 4
        If chazhi > 0 Then
            chazhi = 4 - chazhi
            '将dataFile 补0 成4的倍数
            ReDim Preserve dataFile(dataFile.Length + chazhi - 1)
            For i As Integer = dataFile.Length - chazhi To dataFile.Length - 1
                dataFile(i) = 0
            Next


        End If

        For i As Integer = 0 To dataFile.Length Step datalen

            kuaiaddr = start + i
            li = New List(Of Byte)
            '判断是否有足够长度进行拷贝
            datalen2 = datalen
            If dataFile.Length - i <datalen Then

                datalen2= dataFile.Length - i
                chazhi= datalen - datalen2
                temp= New Byte(datalen2 - 1) {}
            Else
                temp = New Byte(datalen2 - 1) {}
            End If
            Array.Copy(dataFile, i, temp, 0, datalen2)


            li.AddRange(temp)

            resultli.Sendlist.Add((kuaiaddr, li))
        Next



        resultli.SendAddr = start
        resultli.SendLen = dataFile.Length
        resultli.EndAddr = start + dataFile.Length '+ chazhi
        resultli.IsFileAnalysis = True
        resultli.NVersions = "bin文件无版本信息！"
        Return resultli
    End Function


    '起始地址
    Public filestartaddr As Integer
    '解析hex文件 
    Private Function ParsHexFile(filepath As String) As SendFileconig
        Dim resultli As SendFileconig = New SendFileconig
        resultli.IsFileAnalysis = False
        Dim file As New System.IO.FileStream(filepath, FileMode.Open, FileAccess.Read)
        file.Close()
        'Dim reader As New System.IO.BinaryReader(file)
        'Dim hex As String = reader.ReadString()
        Dim hex As String = System.IO.File.ReadAllText(filepath)

        Dim lines As String() = hex.Trim.Split(vbCrLf)
        Dim length As Integer
        Dim addr, tempCheckSum, CheckSum As Integer
        Dim datatype As Byte
        Dim hstr As String
        Dim DataType_00_Idx As Integer = 0
        Dim DataType_00_sount As Integer = 0
        Dim libyte As List(Of Byte)
        Dim mindex As Integer = 0
        Dim datalen As Integer = 0 '256
        Dim kuai As Integer = 512

        Dim A2node As String = ""
        Dim A2cont As Integer = 0


        If Integer.TryParse(txt_BlockLength.Text, kuai) Then
            resultli.BlockLength = kuai
        Else
            MsgBox("块大小异常！")
            resultli.Analysis = "块大小异常！！"
            Return resultli
        End If


        If Integer.TryParse(txt_cdataleng.Text, datalen) Then

        Else
            MsgBox("数据长度输入有误！")
            resultli.Analysis = "数据长度输入有误！！"
            Return resultli
        End If
        ' datalen = datalen + 1

        '偏移地址 0x04 数据类型指示偏移地址
        Dim LineAddOffestBase As Integer = 0
        For Each line As String In lines
            '按照hex文件格式解析
            line = line.Trim
            hstr = line.Substring(1)
            Dim linebyte As Byte() = GetStringToDataByte(hstr)


            If line.Substring(0, 1) = ":" Then
                '数据行
                length = linebyte(0)
                ' addr = 24736
                addr = linebyte(1) * 256 + linebyte(2) + DataType_00_sount + LineAddOffestBase
                '数据类型
                datatype = linebyte(3)
                Dim datalist As List(Of Byte) = New List(Of Byte)
                '数据内容
                Dim dataarry(length - 1) As Byte
                Array.Copy(linebyte, 4, dataarry, 0, dataarry.Length)
                CheckSum = linebyte(length + 4)
                datalist.AddRange(dataarry)
                tempCheckSum = CalcCheckSum(linebyte, linebyte.Length)
                If tempCheckSum <> &HFF Then
                    'MsgBox("校验错误,文件损坏！！")
                    'filestartaddr = -1
                    resultli.Analysis = "校验错误,文件损坏！！"
                    Return resultli
                End If

                If A2cont = 0 Then
                    'Console.WriteLine(hstr)
                    If hstr.Contains("2A2A2A") Then
                        A2cont += 1
                        '获取A2A2A2的地址
                        Dim eindex As Integer = hstr.IndexOf("2A2A2A")
                        A2node = hstr.Substring(eindex, hstr.Length - 2 - eindex)
                    End If
                ElseIf A2cont = 1 Then
                    'Console.WriteLine(hstr)
                    If hstr.Contains("2A2A2A") Then
                        A2cont = 0
                        A2node = A2node + hstr.Substring(8, hstr.IndexOf("2A2A2A") - 2)
                        Dim A2nodearry As Byte() = GetStringToDataByte(A2node.Replace(" ", ""))
                        A2node = System.Text.Encoding.ASCII.GetString(A2nodearry)
                        resultli.SetVersionsInfo(A2node)
                    Else
                        A2node = A2node + ByteArrayToHexString(dataarry)
                    End If

                End If



                Select Case datatype
                    Case 0
                        If DataType_00_Idx = &H0 Then
                            filestartaddr = addr
                            resultli.SendAddr = addr
                            resultli.EndAddr = addr
                        End If
                        DataType_00_Idx += 1

                        If resultli.Sendlist.Count = 194 Then
                            Console.WriteLine("")
                        End If

                        If addr - resultli.EndAddr > 0 Then  '判断 是否需要补零
                            mindex = addr - resultli.EndAddr  '获取补零 个数
                            '判断当前最后一包的数据是否足够容纳 差值

                            'If resultli.Sendlist(resultli.Sendlist.Count - 1).Item2.Count + mindex > datalen Then '
                            '    libyte = New List(Of Byte) ' 255 +3 
                            '    For ni = 0 To mindex - 1 '0.1.2
                            '        If resultli.Sendlist(resultli.Sendlist.Count - 1).Item2.Count < datalen Then  '255+0'1+2
                            '            resultli.Sendlist(resultli.Sendlist.Count - 1).Item2.Add(&H0)
                            '        Else
                            '            libyte.Add(&H0)

                            '            resultli.Sendlist.Add((resultli.EndAddr + ni, libyte)) '1
                            '        End If


                            '    Next
                            'Else
                            '    For i As Integer = 1 To addr - resultli.EndAddr
                            '        'datalist.Add(&HFF)
                            '        resultli.Sendlist(resultli.Sendlist.Count - 1).Item2.Add(&H0)

                            '        If resultli.Sendlist(resultli.Sendlist.Count - 1).Item2.Count < datalen Then  '255+0'1+2
                            '            resultli.Sendlist(resultli.Sendlist.Count - 1).Item2.Add(&H0)
                            '        Else
                            '            libyte.Add(&H0)

                            '            resultli.Sendlist.Add((resultli.EndAddr + ni, libyte)) '1
                            '        End If

                            '    Next
                            'End If
                            For ni = 0 To mindex - 1
                                If resultli.Sendlist(resultli.Sendlist.Count - 1).Item2.Count < datalen Then
                                    resultli.Sendlist(resultli.Sendlist.Count - 1).Item2.Add(&H0)
                                Else
                                    libyte = New List(Of Byte)
                                    libyte.Add(&H0)
                                    resultli.Sendlist.Add((resultli.EndAddr + ni, libyte))

                                End If
                            Next
                            'If resultli.Sendlist(resultli.Sendlist.Count - 1).Item2.Count + mindex > datalen Then '

                        End If



                        If resultli.Sendlist.Count < 1 Then
                            libyte = New List(Of Byte)
                            libyte.AddRange(datalist.ToArray)
                            resultli.Sendlist.Add((addr, libyte))
                        Else
                            If resultli.Sendlist(resultli.Sendlist.Count - 1).Item2.Count + datalist.Count > datalen Then



                                mindex = datalen - resultli.Sendlist(resultli.Sendlist.Count - 1).Item2.Count
                                libyte = New List(Of Byte)


                                For ndixt = 0 To length - 1
                                    If ndixt < mindex Then
                                        resultli.Sendlist(resultli.Sendlist.Count - 1).Item2.Add(datalist(ndixt))
                                    Else
                                        libyte.Add(datalist(ndixt))

                                    End If
                                Next

                                resultli.Sendlist.Add((addr + mindex, libyte))

                            Else
                                resultli.Sendlist(resultli.Sendlist.Count - 1).Item2.AddRange(datalist.ToArray)
                            End If
                        End If


                        resultli.SendLen += datalist.Count
                        resultli.EndAddr = addr + datalist.Count

                       ' Console.WriteLine("包长：" & DataType_00_Idx.ToString & "addr = " & addr & "  datalist.Length = " & datalist.Count & "  resultli.SendLen = " & resultli.SendLen & "  resultli.EndAddr = " & resultli.EndAddr)

                    Case 1
                        If resultli.EndAddr = 0 Then
                            resultli.Analysis = "文件发送数据内容为空！！"
                            Return resultli
                        Else
                            'MsgBox(“数据装载成功，行数=” & LineCnt & “ ， EndAdd = ” & endAddr)
                            resultli.IsFileAnalysis = True
                            Return resultli
                        End If
                    Case 2
                        If length = 2 Then
                            'Console.WriteLine("地址：" & addr & "  长度：" & datalist.Count)
                            DataType_00_sount = linebyte(4) * 256 + linebyte(5)

                            DataType_00_sount = DataType_00_sount << 4
                            'filestartaddr = DataType_00_sount
                            'resultli.SendAddr = DataType_00_sount
                            resultli.EndAddr = DataType_00_sount

                        Else
                            resultli.Analysis = "文件偏移地址异常！！"
                            Return resultli   '确认DataLen必须是2，否则报错’
                        End If

                    Case 4 '扩展线性地址’
                        If length = 2 Then
                            LineAddOffestBase = linebyte(4) * 256 + linebyte(5)
                            LineAddOffestBase = LineAddOffestBase << 16
                        Else
                            resultli.Analysis = "文件偏移地址异常！！"
                            Return resultli   '确认DataLen必须是2，否则报错’
                        End If
                    Case Else
                        Continue For
                End Select

            End If

        Next
        resultli.Analysis = "未找到文件结束符！！"
        Return resultli
    End Function


    Private Function CalcCheckSum(ByVal buf() As Byte, ByVal len As UInt16) As Byte
        Dim sum As Int16 = 0
        Dim i As UInt16 = 0
        Dim retByte As Byte

        For i = 0 To len - 1
            sum += buf(i)
            sum = sum And &HFF
        Next

        retByte = (Not sum) And &HFF

        Return retByte
    End Function
    Private Sub CalcCheckSum(ByVal buflisrList As List(Of (number As Integer, List(Of Byte))), ByVal len As UInt32, ByRef resultBuf() As Byte)
        Dim sum As Int64 = 0
        Dim i As UInt32 = 0
        Dim j As UInt32 = 0
        Dim retByte As Int64
        For i = 0 To buflisrList.Count - 1
            For j = 0 To buflisrList(i).Item2.Count - 1
                'Console.WriteLine($"sum={sum} +buf={buflisrList(i).Item2(j)}")
                sum += buflisrList(i).Item2(j)
                sum = sum And &HFFFFFFFF
            Next
        Next


        'Do
        '    For j = 0 To 127
        '        sum += buf(i + j)
        '        sum = sum And &HFFFFFFFF
        '    Next
        '    i += 128
        'Loop Until i >= len

        'retByte = (Not sum) And &HFFFFFFFF
        retByte = sum

        'TextBox1.Text = Hex(retByte)

        resultBuf(0) = (retByte \ &H1000000) And &HFF
        resultBuf(1) = (retByte \ &H10000) And &HFF
        resultBuf(2) = (retByte \ &H100) And &HFF
        resultBuf(3) = retByte And &HFF
    End Sub


    Private Sub TextBox1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles Txt_startaddr.KeyPress, txt_BootTimeout.KeyPress, Txt_stopaddr.KeyPress, Txt_Myaddr.KeyPress, l_DeviceType.KeyPress, EffTime.KeyPress, ToolStripTextBox1.KeyPress
        ' e.Handled = Not $"0123456789{vbBack}".Contains(e.KeyChar) '如果要只允许输入数字，就把上一行字符串中的字母删除
        '设置只允许输入HEX 字符
        e.Handled = Not $"0123456789ABCDEFabcdef{vbBack}".Contains(e.KeyChar) '如果要只允许输入数字，

    End Sub

    Private Sub Tab_SerialSettings_SelectedIndexChanged(sender As Object, e As EventArgs) Handles Tab_SerialSettings.SelectedIndexChanged
        If Btn_OpenPort.Text = "Disconnect" Then
            Btn_OpenPort.PerformClick()
        End If


        Dim str As String = GetEnumDescription(CType(Tab_SerialSettings.SelectedIndex + 1, CommunicationType))
        Select Case Tab_SerialSettings.SelectedIndex
            Case 0
                m_CommunicationFlow.ChangeCommunicationType(str, RText_OutputText)
                Tab_SerialSettings.Height = 60
            Case 1
                m_CommunicationFlow.ChangeCommunicationType(str, RText_OutputText)
                Tab_SerialSettings.Height = 160
        End Select

    End Sub

    Private Sub Cbo_Baud_SelectedIndexChanged(sender As Object, e As EventArgs) Handles Cbo_Baud.SelectedIndexChanged

        ''判断通信对象是否实例化
        'If IsNothing(m_CommunicationFlow.m_Transmitter) Then
        '    Tab_SerialSettings_SelectedIndexChanged(Nothing, Nothing)
        'End If
        ''判断串口和波特率是否为空
        'If String.IsNullOrEmpty(Cbo_Port.Text) OrElse String.IsNullOrEmpty(Cbo_Baud.Text) Then
        '    MsgBox("未知串口或波特率为空")
        '    Return
        'End If

        'm_CommunicationFlow.m_Transmitter.SetTransmitterParameter(Cbo_Port.Text， CInt(Cbo_Baud.Text))
    End Sub

    Private Sub ToolStripButton1_Click_1(sender As Object, e As EventArgs) Handles ToolStripButton1.Click
        RText_OutputText.Clear()
    End Sub

    Private Sub Btn_Upgrade_Click(sender As Object, e As EventArgs) Handles Btn_Upgrade.Click

        If Btn_Upgrade.Text.Equals("升级设备") Then
            Btn_Upgrade.Text = "停止升级"
            '获取文件信息()
            'Dim resultli As SendFileconig = ParsSelectedUpgradeFile(Tb_HexFilePath.Text)
            'If IsNothing(resultli) Then
            '    MsgBox("文件解析失败")
            '    Btn_Upgrade.PerformClick()
            '    Return
            'End If
            'If Not resultli.IsFileAnalysis Then
            '    MsgBox(resultli.Analysis)
            '    Btn_Upgrade.PerformClick()
            '    Return
            'End If
            'EnterTheUpgradeProcess(resultli)
            'OutputLogsToTheControl(RText_OutputText, New RuningLogConfig("结束升级!", Color.Black), 1)
            'Btn_Upgrade.Text = "Upgrade"


            '获取文件信息()
            Dim resultli As SendFileconig = ParsSelectedUpgradeFile(Tb_HexFilePath.Text)
            If IsNothing(resultli) Then
                MsgBox("文件解析失败")
                Btn_Upgrade.PerformClick()
                Return

            End If
            If Not resultli.IsFileAnalysis Then
                MsgBox(resultli.Analysis)
                Btn_Upgrade.PerformClick()
                Return

            End If



            'EnterTheUpgradeProcess(resultli)
            'OutputLogsToTheControl(RText_OutputText, New RuningLogConfig("结束升级!", Color.Black), 1)
            Dim BootTimeout, Myaddr, startaddr, stopaddr, Appbaud, UpBaud, EffTimeTime, DeviceType, vsendTimeout As Integer
            If Not Integer.TryParse(Sendtimeout.Text, vsendTimeout) Then
                MsgBox("未输入正确的超时时间！")
                Btn_Upgrade.PerformClick()
                Return
            End If

            If Not GetinputTextToint(EffTime.Text, EffTimeTime) Then
                MsgBox("未输入正确的有效时间！")
                Btn_Upgrade.PerformClick()
                Return
            End If
            If IsNothing(m_CommunicationFlow.m_Transmitter) OrElse m_CommunicationFlow.m_Transmitter.IsTransmitter = False Then
                MsgBox("发送器未打开，请先打开发送器！")
                Btn_Upgrade.PerformClick()
                Return
            End If
            If Not GetinputTextToint(txt_BootTimeout.Text, BootTimeout) Then
                MsgBox("未输入正确的超时时间！")
                Btn_Upgrade.PerformClick()
                Return

            End If
            If Not Integer.TryParse(c_UpBaud.Text, UpBaud) Then
                MsgBox("未输入正确的波特率！")
                Btn_Upgrade.PerformClick()
                Return
            End If
            If Not Integer.TryParse(ResendNumber.Text, startaddr) Then
                MsgBox("未输入正确的重发次数！")
                Btn_Upgrade.PerformClick()
                Return
            End If
            If Not Integer.TryParse(ResendIntervalr.Text, stopaddr) Then
                MsgBox("未输入正确的发送间隔！")
                Btn_Upgrade.PerformClick()
                Return
            End If
            If IsNothing(m_CommunicationFlow.m_Receiver) Then
                MsgBox("请先选择通信协议")
                Btn_Upgrade.PerformClick()
                Return
            End If



            If m_CommunicationFlow.IsCreateProtocol Then
                ' DataGridView1.Rows.Clear()

                ''判断协议类对象是否是实例化
                ' If m_CommunicationFlow.m_Receiver.IsCreateProtocol Then
                Dim d_Cmdconfig As Cmdconfig
                OutputLogsToTheControl(RText_OutputText, New RuningLogConfig("开始升级设备!", Color.Black), 1)
                Dim li As List(Of (number As Integer, Cmdconfig)) = New List(Of (number As Integer, Cmdconfig))
                For i = CmdType.SearchCommand To CmdType.CheckCommand
                    d_Cmdconfig = New Cmdconfig({i, 1, startaddr, stopaddr， vsendTimeout}) '命令 SN 重发次数 重发间隔 超时时间
                    Select Case i
                        Case CmdType.SearchCommand '搜索
                            d_Cmdconfig.CmdArgs.Add(BootTimeout)
                            d_Cmdconfig.CmdArgs.Add(EffTimeTime)
                        Case CmdType.skipCommand '跳转Boot
                            d_Cmdconfig.CmdArgs.Add(1)
                        Case CmdType.SetUpParameters 's设置波特率
                            d_Cmdconfig.CmdArgs.AddRange({UpBaud, BootTimeout})
                        Case CmdType.WriteFlashData '写入Flash
                            d_Cmdconfig.CmdArgs.Add(resultli)
                            d_Cmdconfig.CmdReceiveTimeout = 3
                        Case CmdType.EraseFlashData '擦除
                            d_Cmdconfig.CmdArgs.AddRange({2, resultli.SendAddr, resultli.SendLen})
                        Case CmdType.CheckCommand '校验
                            d_Cmdconfig.CmdArgs.Add(resultli)
                        Case Else
                            Continue For

                    End Select


                    d_Cmdconfig.SetProtocol(m_CommunicationFlow.m_Receiver)
                    li.Add((i, d_Cmdconfig))

                Next

                Dim addtypeli As List(Of (Integer, Integer)) = New List(Of (Integer, Integer))
                Dim radd, rtype As Integer
                For i = 0 To DataGridView1.Rows.Count - 1
                    If DataGridView1.Rows(i).Cells(1).Value = 1 Then
                        If Not Integer.TryParse(DataGridView1.Rows(i).Cells(2).Value, radd) Then
                            MsgBox("未输入正确的发送地址！")
                            Btn_Upgrade.PerformClick()
                            Return
                        End If
                        If Not Integer.TryParse(DataGridView1.Rows(i).Cells(3).Value, rtype) Then
                            MsgBox("未输入正确的发送地址！")
                            Btn_Upgrade.PerformClick()
                            Return
                        End If

                        Dim bootVersions As Integer = 0
                        Integer.TryParse(DataGridView1.Rows(i).Cells(8).Value, bootVersions)
                        If resultli.VersionsNumber >= bootVersions Then
                            addtypeli.Add((radd, rtype))
                        Else
                            '弹框询问是否继续升级
                            If MsgBox("设备版本低于当前固件版本，是否继续升级？", MsgBoxStyle.YesNo, "提示") = MsgBoxResult.Yes Then
                                addtypeli.Add((radd, rtype))
                            Else
                                MsgBox("已取消升级！")
                                Btn_Upgrade.PerformClick()
                                Return
                            End If
                        End If



                    End If
                    'Console.WriteLine(DataGridView1.Rows(i).Cells(2).Value)
                    'Console.WriteLine(DataGridView1.Rows(i).Cells(1).Value)
                Next
                If addtypeli.Count = 0 Then
                    MsgBox("未选择升级设备！")
                    Btn_Upgrade.PerformClick()
                    Return
                End If




                If mtest(CmdType.SearchCommand, WorkflowType.FlashWrite, li, Btn_Upgrade, addtypeli) Then

                Else
                    OutputLogsToTheControl(RText_OutputText, New RuningLogConfig("参数异常,搜索结束!", Color.Red), 1)
                    'Button1_Click(Nothing, Nothing)
                End If


            Else
                MsgBox("请先选择通信协议")
                Btn_Upgrade.PerformClick()
                Return
            End If



        Else
            Btn_Upgrade.Text = "升级设备"
            If Not IsNothing(m_CommunicationFlow.m_Receiver) Then
                'Dim mReceiver As BLV_Bootloader = m_CommunicationFlow.m_Receiver
                'm_CommunicationFlow.m_Receiver.SetSearchEquipmentProcessSwitch(False)
                m_CommunicationFlow.SetThreadFlag(False)
            End If
            If IsNothing(sender) Then Return
            'Btn_Search.Text = "Search"
            OutputLogsToTheControl(RText_OutputText, New RuningLogConfig("停止升级设备!", Color.Black), 1)
        End If



    End Sub

    Public Function EnterTheUpgradeProcess(resultli As SendFileconig) As Boolean
        Dim result As Boolean = False
        Dim BootTimeout, Myaddr, startaddr, stopaddr, Appbaud, UpBaud, EffTimeTime, DeviceType As Integer
        If Not GetinputTextToint(EffTime.Text, EffTimeTime) Then
            MsgBox("未输入正确的有效时间！")
            Btn_Upgrade.PerformClick()
            Return result
        End If
        If IsNothing(m_CommunicationFlow.m_Transmitter) OrElse m_CommunicationFlow.m_Transmitter.IsTransmitter = False Then
            MsgBox("发送器未打开，请先打开发送器！")
            Btn_Upgrade.PerformClick()
            Return result
        End If
        If Not GetinputTextToint(txt_BootTimeout.Text, BootTimeout) Then
            MsgBox("未输入正确的超时时间！")
            Btn_Upgrade.PerformClick()
            Return result

        End If
        If IsNothing(m_CommunicationFlow.m_Receiver) Then
            MsgBox("请先选择通信协议")
            Btn_Upgrade.PerformClick()
            Return result
        Else
            'Cbo_Baud
            'c_UpBaud
            If Not Integer.TryParse(Cbo_Baud.Text, Appbaud) Then
                MsgBox("未输入正确的波特率！")
                Btn_Upgrade.PerformClick()
                Return result
            End If
            If Not Integer.TryParse(c_UpBaud.Text, UpBaud) Then
                MsgBox("未输入正确的波特率！")
                Btn_Upgrade.PerformClick()
                Return result
            End If
            If Not GetinputTextToint(Txt_Myaddr.Text, Myaddr) Then
                MsgBox("未输入正确的发送地址！")
                Btn_Upgrade.PerformClick()
                Return result
            End If
            If Not GetinputTextToint(l_DeviceType.Text, DeviceType) Then
                MsgBox("设备类型输入错误！")
                Btn_Upgrade.PerformClick()
                Return Nothing
            End If

            If m_CommunicationFlow.IsCreateProtocol Then
                ' DataGridView1.Rows.Clear()

                ''判断协议类对象是否是实例化
                ' If m_CommunicationFlow.m_Receiver.IsCreateProtocol Then
                Dim d_Cmdconfig As Cmdconfig
                OutputLogsToTheControl(RText_OutputText, New RuningLogConfig("开始升级设备!", Color.Black), 1)
                Dim li As List(Of (number As Integer, Cmdconfig)) = New List(Of (number As Integer, Cmdconfig))
                For i = CmdType.SearchCommand To CmdType.CheckCommand
                    d_Cmdconfig = New Cmdconfig({i, 1, 0, 10， 2}) '命令 SN 重发次数 重发间隔 超时时间
                    Select Case i
                        Case CmdType.SearchCommand '搜索
                            d_Cmdconfig.CmdArgs.Add(BootTimeout)
                            d_Cmdconfig.CmdArgs.Add(EffTimeTime)

                        Case CmdType.skipCommand '跳转Boot
                            d_Cmdconfig.CmdArgs.Add(1)
                        Case CmdType.SetUpParameters 's设置波特率
                            d_Cmdconfig.CmdArgs.AddRange({UpBaud, 10})
                        Case CmdType.WriteFlashData '写入Flash
                            d_Cmdconfig.CmdArgs.Add(resultli)
                            d_Cmdconfig.CmdReceiveTimeout = 3
                        Case CmdType.EraseFlashData '擦除
                            d_Cmdconfig.CmdArgs.AddRange({2, resultli.SendAddr, resultli.SendLen})
                        Case CmdType.CheckCommand '校验
                            d_Cmdconfig.CmdArgs.Add(resultli)
                        Case Else
                            Continue For

                    End Select


                    d_Cmdconfig.SetProtocol(m_CommunicationFlow.m_Receiver)
                    li.Add((i, d_Cmdconfig))

                Next


                'Integer.TryParse(txt_BootTimeout.Text, BootTikdmeout)
                '    d_Cmdconfig.CmdArgs.Add(BootTimeout)
                '    d_Cmdconfig.SetProtocol(m_CommunicationFlow.m_Receiver)
                '    li.Add((CmdType.SearchCommand, d_Cmdconfig))
                '    m_CommunicationFlow.m_Transmitter.ClearSendData()
                Dim cont As Integer = 0
                For i = 0 To DataGridView1.Rows.Count - 1
                    If DataGridView1.Rows(i).Cells(1).Value = 1 Then
                        If Not Integer.TryParse(DataGridView1.Rows(i).Cells(2).Value, startaddr) Then
                            MsgBox("未输入正确的发送地址！")
                            Btn_Upgrade.PerformClick()
                            Return result
                        End If
                        If Not Integer.TryParse(DataGridView1.Rows(i).Cells(2).Value, startaddr) Then
                            MsgBox("未输入正确的发送地址！")
                            Btn_Upgrade.PerformClick()
                            Return result
                        End If
                        m_CommunicationFlow.m_Receiver.MainProcess(WorkflowType.FlashWrite, li, RText_OutputText, Myaddr, startaddr, Appbaud, UpBaud, Btn_Upgrade, DeviceType)
                        cont += 1
                    End If
                    'Console.WriteLine(DataGridView1.Rows(i).Cells(2).Value)
                    'Console.WriteLine(DataGridView1.Rows(i).Cells(1).Value)
                Next
                If cont = 0 Then
                    MsgBox("未选择升级设备！！")
                End If

            Else
                MsgBox("请先选择通信协议")
                Btn_Upgrade.PerformClick()
                Return result
            End If


        End If
    End Function

    Private Sub Form1_FormClosed(sender As Object, e As FormClosedEventArgs) Handles MyBase.FormClosed
        m_CommunicationFlow.StopThread()
        SaveSettings()
    End Sub



    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        If Button1.Text.Equals("群组升级") Then
            Button1.Text = "停止升级"
            '获取文件信息()
            Dim resultli As SendFileconig = ParsSelectedUpgradeFile(Tb_HexFilePath.Text)
            If IsNothing(resultli) Then
                MsgBox("文件解析失败")
                Button1.PerformClick()
                Return
            End If
            If Not resultli.IsFileAnalysis Then
                MsgBox(resultli.Analysis)
                Button1.PerformClick()
                Return
            End If
            'EnterTheUpgradeProcess(resultli)
            'OutputLogsToTheControl(RText_OutputText, New RuningLogConfig("结束升级!", Color.Black), 1)
            Dim BootTimeout, Myaddr, startaddr, stopaddr, Appbaud, UpBaud, EffTimeTime, DeviceType, vsendTimeout As Integer
            If Not Integer.TryParse(Sendtimeout.Text, vsendTimeout) Then
                MsgBox("未输入正确的超时时间！")
                Button1.PerformClick()
                Return
            End If

            If Not GetinputTextToint(EffTime.Text, EffTimeTime) Then
                MsgBox("未输入正确的有效时间！")
                Button1.PerformClick()
                Return
            End If
            If IsNothing(m_CommunicationFlow.m_Transmitter) OrElse m_CommunicationFlow.m_Transmitter.IsTransmitter = False Then
                MsgBox("发送器未打开，请先打开发送器！")
                Button1.PerformClick()
                Return
            End If
            If Not GetinputTextToint(txt_BootTimeout.Text, BootTimeout) Then
                MsgBox("未输入正确的超时时间！")
                Button1.PerformClick()
                Return

            End If
            If Not Integer.TryParse(c_UpBaud.Text, UpBaud) Then
                MsgBox("未输入正确的波特率！")
                Button1.PerformClick()
                Return
            End If
            If Not Integer.TryParse(ResendNumber.Text, startaddr) Then
                MsgBox("未输入正确的重发次数！")
                Button1.PerformClick()
                Return
            End If
            If Not Integer.TryParse(ResendIntervalr.Text, stopaddr) Then
                MsgBox("未输入正确的发送间隔！")
                Button1.PerformClick()
                Return
            End If
            If IsNothing(m_CommunicationFlow.m_Receiver) Then
                MsgBox("请先选择通信协议")
                Button1.PerformClick()
                Return
            End If

            If m_CommunicationFlow.IsCreateProtocol Then
                ' DataGridView1.Rows.Clear()

                ''判断协议类对象是否是实例化
                ' If m_CommunicationFlow.m_Receiver.IsCreateProtocol Then
                Dim d_Cmdconfig As Cmdconfig
                OutputLogsToTheControl(RText_OutputText, New RuningLogConfig("开始群发升级设备!", Color.Black), 1)
                Dim li As List(Of (number As Integer, Cmdconfig)) = New List(Of (number As Integer, Cmdconfig))
                For i = CmdType.SearchCommand To CmdType.CheckCommand
                    d_Cmdconfig = New Cmdconfig({i, 1, startaddr, stopaddr， vsendTimeout}) '命令 SN 重发次数 重发间隔 超时时间
                    Select Case i
                        Case CmdType.SearchCommand '搜索
                            d_Cmdconfig.CmdArgs.Add(BootTimeout)
                            d_Cmdconfig.CmdArgs.Add(EffTimeTime)

                        Case CmdType.skipCommand '跳转Boot
                            d_Cmdconfig.CmdArgs.Add(1)
                        Case CmdType.SetUpParameters 's设置波特率
                            d_Cmdconfig.CmdArgs.AddRange({UpBaud, BootTimeout})
                        Case CmdType.WriteFlashData '写入Flash
                            d_Cmdconfig.CmdArgs.Add(resultli)
                            d_Cmdconfig.CmdReceiveTimeout = 3
                        Case CmdType.EraseFlashData '擦除
                            d_Cmdconfig.CmdArgs.AddRange({2, resultli.SendAddr, resultli.SendLen})
                        Case CmdType.CheckCommand '校验
                            d_Cmdconfig.CmdArgs.Add(resultli)
                        Case Else
                            Continue For

                    End Select


                    d_Cmdconfig.SetProtocol(m_CommunicationFlow.m_Receiver)
                    li.Add((i, d_Cmdconfig))

                Next

                If mtest(CmdType.SearchCommand, WorkflowType.FlashGroupUpgrade, li, Button1) Then

                Else
                    OutputLogsToTheControl(RText_OutputText, New RuningLogConfig("参数异常,搜索结束!", Color.Red), 1)
                    'Button1_Click(Nothing, Nothing)
                End If


            Else
                MsgBox("请先选择通信协议")
                Button1.PerformClick()
                Return
            End If









        Else
            Button1.Text = "群组升级"
            If Not IsNothing(m_CommunicationFlow.m_Receiver) Then
                'Dim mReceiver As BLV_Bootloader = m_CommunicationFlow.m_Receiver
                'm_CommunicationFlow.m_Receiver.SetSearchEquipmentProcessSwitch(False)
                m_CommunicationFlow.SetThreadFlag(False)
            End If
            If IsNothing(sender) Then Return
            'Btn_Search.Text = "Search"
            OutputLogsToTheControl(RText_OutputText, New RuningLogConfig("停止升级群组设备!", Color.Black), 1)
        End If
    End Sub

    Private Sub btn_Reload_Click(sender As Object, e As EventArgs) Handles btn_Reload.Click
        If btn_Reload.Text = "停止Boot搜索" Then
            If Not IsNothing(m_CommunicationFlow.m_Receiver) Then
                Dim mReceiver As BLV_Bootloader = m_CommunicationFlow.m_Receiver
                m_CommunicationFlow.m_Receiver.SetSearchEquipmentProcessSwitch(False)
                m_CommunicationFlow.SetThreadFlag(False)
            End If

            If IsNothing(sender) Then Return
            btn_Reload.Text = "Boot搜索"
            OutputLogsToTheControl(RText_OutputText, New RuningLogConfig("停止搜索设备!", Color.Black), 1)
        Else
            btn_Reload.Text = "停止Boot搜索"
            If IsNothing(m_CommunicationFlow.m_Transmitter) OrElse m_CommunicationFlow.m_Transmitter.IsTransmitter = False Then
                MsgBox("发送器未打开，请先打开发送器！")
                btn_Reload.PerformClick()
                Return
            End If
            If IsNothing(m_CommunicationFlow.m_Receiver) Then
                MsgBox("请先选择通信协议")
                btn_Reload.PerformClick()
                Return
            Else
                Dim BootTimeout, Myaddr, startaddr, stopaddr, EffTimeTime, vsendTimeout, UpBaud As Integer
                If Not GetinputTextToint(txt_BootTimeout.Text, BootTimeout) Then
                    MsgBox("未输入正确的超时时间！")
                    btn_Reload.PerformClick()
                    Return
                End If
                If Not GetinputTextToint(EffTime.Text, EffTimeTime) Then
                    MsgBox("未输入正确的有效时间！")
                    btn_Reload.PerformClick()
                    Return
                End If
                'If Not Integer.TryParse(Txt_Myaddr.Text, Myaddr) Then
                '    MsgBox("未输入正确的本机地址！")
                '    btn_Reload.PerformClick()
                '    Return
                'End If
                'If Not Integer.TryParse(Txt_startaddr.Text, startaddr) OrElse Not Integer.TryParse(Txt_stopaddr.Text, startaddr) Then
                '    MsgBox("未输入正确的起始地址或结束地址！")
                '    btn_Reload.PerformClick()
                '    Return
                'End If
                If Not Integer.TryParse(Sendtimeout.Text, vsendTimeout) Then
                    MsgBox("未输入正确的超时时间！")
                    btn_Reload.PerformClick()
                    Return
                End If
                DataGridView1.Rows.Clear()

                '判断协议类对象是否是实例化
                If m_CommunicationFlow.IsCreateProtocol Then

                    OutputLogsToTheControl(RText_OutputText, New RuningLogConfig("开始搜索设备!", Color.Black), 1)
                    Dim li As List(Of (number As Integer, Cmdconfig)) = New List(Of (number As Integer, Cmdconfig))

                    Dim d_Cmdconfig As Cmdconfig = New Cmdconfig({CmdType.SearchCommand, 1, 0, 10， vsendTimeout})


                    'Integer.TryParse(txt_BootTimeout.Text, BootTimeout)
                    d_Cmdconfig.CmdArgs.Add(BootTimeout)
                    d_Cmdconfig.CmdArgs.Add(EffTimeTime)
                    d_Cmdconfig.SetProtocol(m_CommunicationFlow.m_Receiver)
                    d_Cmdconfig.setCmdSendcontinueTime(60)
                    li.Add((CmdType.SearchCommand, d_Cmdconfig))
                    m_CommunicationFlow.m_Transmitter.ClearSendData()
                    'm_CommunicationFlow.m_Receiver.MainProcess(WorkflowType.SearchEquipment, li, 60, DataGridView1, RText_OutputText, CInt(Txt_Myaddr.Text), CInt(Txt_startaddr.Text), CInt(Txt_stopaddr.Text), CInt(Cbo_Baud.Text), Btn_Search)

                    If mtest(CmdType.SearchCommand, WorkflowType.BootSearchEquipment, li, btn_Reload) Then

                    Else
                        OutputLogsToTheControl(RText_OutputText, New RuningLogConfig("参数异常,搜索结束!", Color.Red), 1)
                        'btn_Reload_Click(Nothing, Nothing)
                    End If
                Else
                    MsgBox("请先选择通信协议")

                End If
            End If
            ' OutputLogsToTheControl(RText_OutputText, New RuningLogConfig("结束搜索设备!", Color.Black), 1)
            'btn_Reload(Nothing, Nothing)


        End If
    End Sub

    Private Sub Chk_UpgradeAllSel_CheckedChanged(sender As Object, e As EventArgs) Handles Chk_UpgradeAllSel.CheckedChanged
        If IsUpgradeAllSel Then Return
        For i = 0 To DataGridView1.Rows.Count - 1
            DataGridView1.Rows(i).Cells(1).Value = Chk_UpgradeAllSel.Checked
        Next
    End Sub

    Private Sub CboLocalIp_TextChanged(sender As Object, e As EventArgs) Handles CboLongIP.TextChanged, CboLocalIp.TextChanged
        'If IsNothing(m_CommunicationFlow.m_Transmitter) Then
        '    Tab_SerialSettings_SelectedIndexChanged(Nothing, Nothing)
        'End If
        'Dim cb As ComboBox = sender
        'If String.IsNullOrEmpty(cb.Text) Then
        '    If cb.Name = "CboLocalIp" Then
        '        MsgBox("请选择本地IP地址!")
        '    ElseIf cb.Name = "CboLongIP" Then
        '        MsgBox("请选择远程IP地址!")
        '    End If
        '    Return
        'End If
        'm_CommunicationFlow.m_Transmitter.SetTransmitterParameter(CboLocalIp.Text, NudLocalPort.Value, CboLongIP.Text, NudRemotePort.Value)
    End Sub

    Private Sub NudLocalPort_ValueChanged(sender As Object, e As EventArgs) Handles NudLocalPort.ValueChanged, NudRemotePort.ValueChanged
        'Dim cb As ComboBox = sender
        'If String.IsNullOrEmpty(cb.Text) Then
        '    If cb.Name = "CboLocalIp" Then
        '        MsgBox("请选择本地IP地址!")
        '    ElseIf cb.Name = "CboLongIP" Then
        '        MsgBox("请选择远程IP地址!")
        '    End If
        '    Return
        'End If
        'm_CommunicationFlow.m_Transmitter.SetTransmitterParameter(CboLocalIp.Text, NudLocalPort.Value, CboLongIP.Text, NudRemotePort.Value)
    End Sub

    Private Sub txt_cdataleng_KeyPress(sender As Object, e As KeyPressEventArgs) Handles txt_cdataleng.KeyPress, txt_BlockLength.KeyPress
        e.Handled = Not $"0123456789{vbBack}".Contains(e.KeyChar) '如果要只允许输入数字，
    End Sub







    Private Sub ReadDevbtn_Click(sender As Object, e As EventArgs) Handles ReadDevbtn.Click

        If IsNothing(m_CommunicationFlow.m_Transmitter) OrElse m_CommunicationFlow.m_Transmitter.IsTransmitter = False Then
            MsgBox("发送器未打开，请先打开发送器！")
            Return
        End If
        If IsNothing(m_CommunicationFlow.m_Receiver) Then
            MsgBox("请先选择通信协议")

            Return
        End If
        Dim BootTimeout, Myaddr, startaddr, stopaddr, EffTimeTime, vsendTimeout, UpBaud As Integer
        If Not GetinputTextToint(TextBox1.Text, BootTimeout) Then
            MsgBox("未输入正确的读取地址！")

            Return
        End If
        If Not Integer.TryParse(TextBox2.Text, EffTimeTime) Then
            MsgBox("未输入正确的读取长度！")
            Return
        End If

        If Not Integer.TryParse(Sendtimeout.Text, vsendTimeout) Then
            MsgBox("未输入正确的超时时间！")
            Return
        End If



        'DataGridView1.Rows.Clear()

        '判断协议类对象是否是实例化
        If m_CommunicationFlow.IsCreateProtocol Then

            'OutputLogsToTheControl(RText_OutputText, New RuningLogConfig("开始读取设备!", Color.Black), 1)


            Dim li As List(Of (number As Integer, Cmdconfig)) = New List(Of (number As Integer, Cmdconfig))
            '这里要增加一个跳转命令
            Dim d_Cmdconfig As Cmdconfig = New Cmdconfig({CmdType.ReadingFlashData, 1, 0, 10， vsendTimeout}) '命令 SN 重发次数 重发间隔 超时时间

            d_Cmdconfig.CmdArgs.Add(BootTimeout)
            d_Cmdconfig.CmdArgs.Add(EffTimeTime)

            d_Cmdconfig.SetProtocol(m_CommunicationFlow.m_Receiver)
            li.Add((CmdType.ReadingFlashData, d_Cmdconfig))


            m_CommunicationFlow.m_Transmitter.ClearSendData()
            'm_CommunicationFlow.m_Receiver.MainProcess(WorkflowType.SearchEquipment, li, 60, DataGridView1, RText_OutputText, CInt(Txt_Myaddr.Text), CInt(Txt_startaddr.Text), CInt(Txt_stopaddr.Text), CInt(Cbo_Baud.Text), Btn_Search)

            If mtest(CmdType.ReadingFlashData, WorkflowType.none, li, ReadDevbtn) Then

            Else
                OutputLogsToTheControl(RText_OutputText, New RuningLogConfig("参数异常,结束!", Color.Red), 1)
                'Btn_Search_Click_1(Nothing, Nothing)
            End If
        Else
            MsgBox("请先选择通信协议")
            ReadDevbtn.PerformClick()
            Return
        End If

    End Sub

    Private Sub Button7_Click(sender As Object, e As EventArgs) Handles Button7.Click
        If IsNothing(m_CommunicationFlow.m_Transmitter) OrElse m_CommunicationFlow.m_Transmitter.IsTransmitter = False Then
            MsgBox("发送器未打开，请先打开发送器！")
            Return
        End If
        If IsNothing(m_CommunicationFlow.m_Receiver) Then
            MsgBox("请先选择通信协议")
            Return
        End If
        Dim BootTimeout, Myaddr, startaddr, stopaddr, EffTimeTime, vsendTimeout, UpBaud As Integer
        If Not GetinputTextToint(TextBox4.Text, BootTimeout) Then
            MsgBox("未输入正确的校验起始地址！")
            Return
        End If
        If Not GetinputTextToint(TextBox5.Text, EffTimeTime) Then
            MsgBox("未输入正确的校验结束地址！")
            Return
        End If
        If Not GetinputTextToint(TextBox6.Text, UpBaud) Then
            MsgBox("未输入正确的校验值！")
            Return
        End If

        If Not GetinputTextToint(Sendtimeout.Text, vsendTimeout) Then
            MsgBox("未输入正确的超时时间！")
            Return
        End If
        'If TextBox3.Text.Trim.Equals("1") Then
        '    Myaddr = 1
        'ElseIf TextBox3.Text.Trim.Equals("2") Then
        '    Myaddr = 2
        'Else
        '    MsgBox("未输入正确的地址！")
        '    Return
        'End If

        'DataGridView1.Rows.Clear()

        '判断协议类对象是否是实例化
        If m_CommunicationFlow.IsCreateProtocol Then

            'OutputLogsToTheControl(RText_OutputText, New RuningLogConfig("开始读取设备!", Color.Black), 1)


            Dim li As List(Of (number As Integer, Cmdconfig)) = New List(Of (number As Integer, Cmdconfig))
            '这里要增加一个跳转命令
            Dim d_Cmdconfig As Cmdconfig = New Cmdconfig({CmdType.SetUpParameters, 1, 0, 10, vsendTimeout}) '命令 SN 重发次数 重发间隔 超时时间
            d_Cmdconfig.CmdArgs.Add(BootTimeout)
            d_Cmdconfig.CmdArgs.Add(EffTimeTime)
            d_Cmdconfig.CmdArgs.Add(UpBaud)
            d_Cmdconfig.SetProtocol(m_CommunicationFlow.m_Receiver)
            li.Add((CmdType.SetUpParameters, d_Cmdconfig))




            m_CommunicationFlow.m_Transmitter.ClearSendData()
            'm_CommunicationFlow.m_Receiver.MainProcess(WorkflowType.SearchEquipment, li, 60, DataGridView1, RText_OutputText, CInt(Txt_Myaddr.Text), CInt(Txt_startaddr.Text), CInt(Txt_stopaddr.Text), CInt(Cbo_Baud.Text), Btn_Search)

            If mtest(CmdType.SetUpParameters, WorkflowType.none, li, ReadDevbtn) Then

            Else
                OutputLogsToTheControl(RText_OutputText, New RuningLogConfig("参数异常,结束!", Color.Red), 1)
                'Btn_Search_Click_1(Nothing, Nothing)
            End If
        Else
            MsgBox("请先选择通信协议")
            ReadDevbtn.PerformClick()
            Return
        End If

    End Sub

    Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
        If IsNothing(m_CommunicationFlow.m_Transmitter) OrElse m_CommunicationFlow.m_Transmitter.IsTransmitter = False Then
            MsgBox("发送器未打开，请先打开发送器！")
            Return
        End If
        If IsNothing(m_CommunicationFlow.m_Receiver) Then
            MsgBox("请先选择通信协议")

            Return
        End If
        Dim BootTimeout, Myaddr, startaddr, stopaddr, EffTimeTime, vsendTimeout, UpBaud As Integer
        'If Not GetinputTextToint(TextBox1.Text, BootTimeout) Then
        '    MsgBox("未输入正确的读取地址！")

        'Return
        'End If
        If Not Integer.TryParse(Cbo_Baud.Text, EffTimeTime) Then
            MsgBox("未输入正确的APP波特率！")

            Return
        End If

        If Not Integer.TryParse(Sendtimeout.Text, vsendTimeout) Then
            MsgBox("未输入正确的超时时间！")

            Return
        End If
        'If TextBox3.Text.Trim.Equals("1") Then
        '    Myaddr = 1
        'ElseIf TextBox3.Text.Trim.Equals("2") Then
        '    Myaddr = 2
        'Else
        '    MsgBox("未输入正确的地址！")
        '    Return
        'End If

        'DataGridView1.Rows.Clear()

        '判断协议类对象是否是实例化
        If m_CommunicationFlow.IsCreateProtocol Then

            'OutputLogsToTheControl(RText_OutputText, New RuningLogConfig("开始读取设备!", Color.Black), 1)


            Dim li As List(Of (number As Integer, Cmdconfig)) = New List(Of (number As Integer, Cmdconfig))
            '这里要增加一个跳转命令
            Dim d_Cmdconfig As Cmdconfig = New Cmdconfig({CmdType.SetUpParameters, 1, 0, 10, vsendTimeout}) '命令 SN 重发次数 重发间隔 超时时间
            d_Cmdconfig.CmdArgs.Add(EffTimeTime)
            d_Cmdconfig.SetProtocol(m_CommunicationFlow.m_Receiver)
            li.Add((CmdType.SetUpParameters, d_Cmdconfig))




            m_CommunicationFlow.m_Transmitter.ClearSendData()
            'm_CommunicationFlow.m_Receiver.MainProcess(WorkflowType.SearchEquipment, li, 60, DataGridView1, RText_OutputText, CInt(Txt_Myaddr.Text), CInt(Txt_startaddr.Text), CInt(Txt_stopaddr.Text), CInt(Cbo_Baud.Text), Btn_Search)

            If mtest(CmdType.SetUpParameters, WorkflowType.none, li, ReadDevbtn) Then

            Else
                OutputLogsToTheControl(RText_OutputText, New RuningLogConfig("参数异常,结束!", Color.Red), 1)
                'Btn_Search_Click_1(Nothing, Nothing)
            End If
        Else
            MsgBox("请先选择通信协议")
            ReadDevbtn.PerformClick()
            Return
        End If


    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        If IsNothing(m_CommunicationFlow.m_Transmitter) OrElse m_CommunicationFlow.m_Transmitter.IsTransmitter = False Then
            MsgBox("发送器未打开，请先打开发送器！")
            Return
        End If
        If IsNothing(m_CommunicationFlow.m_Receiver) Then
            MsgBox("请先选择通信协议")

            Return
        End If
        Dim BootTimeout, Myaddr, startaddr, stopaddr, EffTimeTime, vsendTimeout, UpBaud As Integer
        'If Not GetinputTextToint(TextBox1.Text, BootTimeout) Then
        '    MsgBox("未输入正确的读取地址！")

        'Return
        'End If
        'If Not Integer.TryParse(TextBox2.Text, EffTimeTime) Then
        '    MsgBox("未输入正确的读取长度！")

        'Return
        'End If

        If Not Integer.TryParse(Sendtimeout.Text, vsendTimeout) Then
            MsgBox("未输入正确的超时时间！")

            Return
        End If
        If TextBox3.Text.Trim.Equals("1") Then
            Myaddr = 1
        ElseIf TextBox3.Text.Trim.Equals("2") Then
            Myaddr = 2
        Else
            MsgBox("未输入正确的地址！")
            Return
        End If

        'DataGridView1.Rows.Clear()

        '判断协议类对象是否是实例化
        If m_CommunicationFlow.IsCreateProtocol Then

            'OutputLogsToTheControl(RText_OutputText, New RuningLogConfig("开始读取设备!", Color.Black), 1)


            Dim li As List(Of (number As Integer, Cmdconfig)) = New List(Of (number As Integer, Cmdconfig))
            '这里要增加一个跳转命令
            Dim d_Cmdconfig As Cmdconfig = New Cmdconfig({CmdType.skipCommand, 1, 0, 10， vsendTimeout}) '命令 SN 重发次数 重发间隔 超时时间
            d_Cmdconfig.CmdArgs.Add(Myaddr)
            d_Cmdconfig.SetProtocol(m_CommunicationFlow.m_Receiver)
            li.Add((CmdType.skipCommand, d_Cmdconfig))




            m_CommunicationFlow.m_Transmitter.ClearSendData()
            'm_CommunicationFlow.m_Receiver.MainProcess(WorkflowType.SearchEquipment, li, 60, DataGridView1, RText_OutputText, CInt(Txt_Myaddr.Text), CInt(Txt_startaddr.Text), CInt(Txt_stopaddr.Text), CInt(Cbo_Baud.Text), Btn_Search)

            If mtest(CmdType.skipCommand, WorkflowType.none, li, ReadDevbtn) Then

            Else
                OutputLogsToTheControl(RText_OutputText, New RuningLogConfig("参数异常,结束!", Color.Red), 1)
                'Btn_Search_Click_1(Nothing, Nothing)
            End If
        Else
            MsgBox("请先选择通信协议")
            ReadDevbtn.PerformClick()
            Return
        End If



    End Sub

    Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
        If IsNothing(m_CommunicationFlow.m_Transmitter) OrElse m_CommunicationFlow.m_Transmitter.IsTransmitter = False Then
            MsgBox("发送器未打开，请先打开发送器！")
            Return
        End If
        If IsNothing(m_CommunicationFlow.m_Receiver) Then
            MsgBox("请先选择通信协议")

            Return
        End If
        Dim BootTimeout, Myaddr, startaddr, stopaddr, EffTimeTime, vsendTimeout, UpBaud As Integer
        'If Not GetinputTextToint(TextBox1.Text, BootTimeout) Then
        '    MsgBox("未输入正确的读取地址！")

        'Return
        'End If
        'If Not Integer.TryParse(TextBox2.Text, EffTimeTime) Then
        '    MsgBox("未输入正确的读取长度！")

        'Return
        'End If

        'If Not Integer.TryParse(Sendtimeout.Text, vsendTimeout) Then
        '    MsgBox("未输入正确的超时时间！")

        '    Return
        'End If
        'If TextBox3.Text.Trim.Equals("1") Then
        '    Myaddr = 1
        'ElseIf TextBox3.Text.Trim.Equals("2") Then
        '    Myaddr = 2
        'Else
        '    MsgBox("未输入正确的地址！")
        '    Return
        'End If

        'DataGridView1.Rows.Clear()

        '判断协议类对象是否是实例化
        If m_CommunicationFlow.IsCreateProtocol Then

            'OutputLogsToTheControl(RText_OutputText, New RuningLogConfig("开始读取设备!", Color.Black), 1)


            Dim li As List(Of (number As Integer, Cmdconfig)) = New List(Of (number As Integer, Cmdconfig))
            '这里要增加一个跳转命令
            Dim d_Cmdconfig As Cmdconfig = New Cmdconfig({CmdType.EraseFlashData, 1, 0, 10， vsendTimeout}) '命令 SN 重发次数 重发间隔 超时时间
            d_Cmdconfig.CmdArgs.Add(2)
            d_Cmdconfig.CmdArgs.Add(0)
            d_Cmdconfig.CmdArgs.Add(0)
            d_Cmdconfig.SetProtocol(m_CommunicationFlow.m_Receiver)
            li.Add((CmdType.EraseFlashData, d_Cmdconfig))




            m_CommunicationFlow.m_Transmitter.ClearSendData()
            'm_CommunicationFlow.m_Receiver.MainProcess(WorkflowType.SearchEquipment, li, 60, DataGridView1, RText_OutputText, CInt(Txt_Myaddr.Text), CInt(Txt_startaddr.Text), CInt(Txt_stopaddr.Text), CInt(Cbo_Baud.Text), Btn_Search)

            If mtest(CmdType.EraseFlashData, WorkflowType.none, li, ReadDevbtn) Then

            Else
                OutputLogsToTheControl(RText_OutputText, New RuningLogConfig("参数异常,结束!", Color.Red), 1)
                'Btn_Search_Click_1(Nothing, Nothing)
            End If
        Else
            MsgBox("请先选择通信协议")
            ReadDevbtn.PerformClick()
            Return
        End If
    End Sub

    Private Sub Button8_Click(sender As Object, e As EventArgs) Handles Button8.Click

        If IsNothing(m_CommunicationFlow.m_Transmitter) OrElse m_CommunicationFlow.m_Transmitter.IsTransmitter = False Then
            MsgBox("发送器未打开，请先打开发送器！")
            Return
        End If
        If IsNothing(m_CommunicationFlow.m_Receiver) Then
            MsgBox("请先选择通信协议")

            Return
        End If
        Dim BootTimeout, Myaddr, startaddr, stopaddr, EffTimeTime, vsendTimeout, UpBaud As Integer
        If Not GetinputTextToint(TextBox1.Text, BootTimeout) Then
            MsgBox("未输入正确的读取地址！")

            Return
        End If
        If Not Integer.TryParse(TextBox2.Text, EffTimeTime) Then
            MsgBox("未输入正确的读取长度！")
            Return
        End If

        If Not Integer.TryParse(Sendtimeout.Text, vsendTimeout) Then
            MsgBox("未输入正确的超时时间！")
            Return
        End If



        'DataGridView1.Rows.Clear()

        '判断协议类对象是否是实例化
        If m_CommunicationFlow.IsCreateProtocol Then

            'OutputLogsToTheControl(RText_OutputText, New RuningLogConfig("开始读取设备!", Color.Black), 1)


            Dim li As List(Of (number As Integer, Cmdconfig)) = New List(Of (number As Integer, Cmdconfig))
            '这里要增加一个跳转命令
            Dim d_Cmdconfig As Cmdconfig = New Cmdconfig({CmdType.ReadingEEPROMData, 1, 0, 10， vsendTimeout}) '命令 SN 重发次数 重发间隔 超时时间

            d_Cmdconfig.CmdArgs.Add(BootTimeout)
            d_Cmdconfig.CmdArgs.Add(EffTimeTime)

            d_Cmdconfig.SetProtocol(m_CommunicationFlow.m_Receiver)
            li.Add((CmdType.ReadingEEPROMData, d_Cmdconfig))


            m_CommunicationFlow.m_Transmitter.ClearSendData()
            'm_CommunicationFlow.m_Receiver.MainProcess(WorkflowType.SearchEquipment, li, 60, DataGridView1, RText_OutputText, CInt(Txt_Myaddr.Text), CInt(Txt_startaddr.Text), CInt(Txt_stopaddr.Text), CInt(Cbo_Baud.Text), Btn_Search)

            If mtest(CmdType.ReadingEEPROMData, WorkflowType.none, li, ReadDevbtn) Then

            Else
                OutputLogsToTheControl(RText_OutputText, New RuningLogConfig("参数异常,结束!", Color.Red), 1)
                'Btn_Search_Click_1(Nothing, Nothing)
            End If
        Else
            MsgBox("请先选择通信协议")
            ReadDevbtn.PerformClick()
            Return
        End If
    End Sub

    Private Sub Button6_Click(sender As Object, e As EventArgs) Handles Button6.Click
        If IsNothing(m_CommunicationFlow.m_Transmitter) OrElse m_CommunicationFlow.m_Transmitter.IsTransmitter = False Then
            MsgBox("发送器未打开，请先打开发送器！")
            Return
        End If
        If IsNothing(m_CommunicationFlow.m_Receiver) Then
            MsgBox("请先选择通信协议")

            Return
        End If
        Dim BootTimeout, Myaddr, startaddr, stopaddr, EffTimeTime, vsendTimeout, UpBaud As Integer
        'If Not GetinputTextToint(TextBox1.Text, BootTimeout) Then
        '    MsgBox("未输入正确的读取地址！")

        'Return
        'End If
        'If Not Integer.TryParse(TextBox2.Text, EffTimeTime) Then
        '    MsgBox("未输入正确的读取长度！")

        'Return
        'End If

        'If Not Integer.TryParse(Sendtimeout.Text, vsendTimeout) Then
        '    MsgBox("未输入正确的超时时间！")

        '    Return
        'End If
        'If TextBox3.Text.Trim.Equals("1") Then
        '    Myaddr = 1
        'ElseIf TextBox3.Text.Trim.Equals("2") Then
        '    Myaddr = 2
        'Else
        '    MsgBox("未输入正确的地址！")
        '    Return
        'End If

        'DataGridView1.Rows.Clear()

        '判断协议类对象是否是实例化
        If m_CommunicationFlow.IsCreateProtocol Then

            'OutputLogsToTheControl(RText_OutputText, New RuningLogConfig("开始读取设备!", Color.Black), 1)


            Dim li As List(Of (number As Integer, Cmdconfig)) = New List(Of (number As Integer, Cmdconfig))
            '这里要增加一个跳转命令
            Dim d_Cmdconfig As Cmdconfig = New Cmdconfig({CmdType.EraseEEPROMData, 1, 0, 10， vsendTimeout}) '命令 SN 重发次数 重发间隔 超时时间
            d_Cmdconfig.CmdArgs.Add(2)
            d_Cmdconfig.CmdArgs.Add(0)
            d_Cmdconfig.CmdArgs.Add(0)
            d_Cmdconfig.SetProtocol(m_CommunicationFlow.m_Receiver)
            li.Add((CmdType.EraseEEPROMData, d_Cmdconfig))




            m_CommunicationFlow.m_Transmitter.ClearSendData()
            'm_CommunicationFlow.m_Receiver.MainProcess(WorkflowType.SearchEquipment, li, 60, DataGridView1, RText_OutputText, CInt(Txt_Myaddr.Text), CInt(Txt_startaddr.Text), CInt(Txt_stopaddr.Text), CInt(Cbo_Baud.Text), Btn_Search)

            If mtest(CmdType.EraseEEPROMData, WorkflowType.none, li, ReadDevbtn) Then

            Else
                OutputLogsToTheControl(RText_OutputText, New RuningLogConfig("参数异常,结束!", Color.Red), 1)
                'Btn_Search_Click_1(Nothing, Nothing)
            End If
        Else
            MsgBox("请先选择通信协议")
            ReadDevbtn.PerformClick()
            Return
        End If
    End Sub

    Private Sub CheckBox1_CheckedChanged(sender As Object, e As EventArgs) Handles CheckBox1.CheckedChanged
        If CheckBox1.Checked Then
            RuningLog.SetLevel(0)
        Else
            RuningLog.SetLevel(1)
        End If
    End Sub


End Class

Public Class SendFileconig
    '解析文件成功标志
    Public Property IsFileAnalysis As Boolean
    '解析消息
    Public Property Analysis As String

    '发送地址
    Public Property SendAddr As UInt32
    '发送长度
    Public Property SendLen As UInt32
    '结束地址
    Public Property EndAddr As UInt32
    '发送数据
    Public Property Sendlist As List(Of (number As Integer, List(Of Byte)))
    '分块
    Public Property BlockLength As Integer
    '版本名称
    Public VersionsName As String
    '版本分组
    Public VersionsGroup As String
    '版本号
    Public VersionsNumber As Integer
    Public NVersions As String


    Sub New()
        Sendlist = New List(Of (number As Integer, List(Of Byte)))
        BlockLength = 512
    End Sub

    '设置版本信息
    Public Function SetVersionsInfo(Versions As String) As Boolean
        '判断首尾是否是***
        If Versions.StartsWith("***") AndAlso Versions.EndsWith("***") Then
            Versions = Versions.Trim("***")
            '判断以_切割能否分出3个
            Dim VersionsArr() As String = Versions.Split("_")
            If VersionsArr.Length = 3 Then
                '判断第2个是否为Bootloader
                If VersionsArr(1).ToLower = "bootloader" Then
                    Dim cv As Integer = 0
                    VersionsName = VersionsArr(0)
                    VersionsGroup = VersionsArr(1)
                    VersionsNumber = Integer.TryParse((VersionsArr(2).Replace("V", "").Replace("v", "")), cv)
                    NVersions = Versions
                    Return True
                End If
            End If
        End If
        Return False
    End Function


End Class
