Imports System.ComponentModel
Imports _485_BurningTool.CommunicationFlow
Imports _485_BurningTool.RuningLog

Public MustInherit Class BLV_Bootloader
    Inherits CommunicationProtocol
    Public m_config As BLV_Bootloaderconfig
    Private SN As Integer
    Public m_flowdic As Dictionary(Of String, List(Of (Integer, Cmdconfig)))
    Enum CmdType
        <Description("等待回复")>
        WaitReply = 0
        <Description("处理回复")>
        ProcessReply = 1
        <Description("搜索命令")>
        SearchCommand = 192 'C0
        <Description("跳转命令")>
        skipCommand = 193
        <Description("设置参数")>
        SetUpParameters = 194
        <Description("写入Flash数据")>
        WriteFlashData = 195
        <Description("读取Flash数据")>
        ReadingFlashData = 196
        <Description("擦除Flash数据")>
        EraseFlashData = 197
        <Description("写入EEPROM数据")>
        WriteEEPROMData = 198
        <Description("读取EEPROM数据")>
        ReadingEEPROMData = 199
        <Description("擦除EEPROM数据")>
        EraseEEPROMData = 200
        <Description("校验命令")>
        CheckCommand = 201

    End Enum

    Enum WorkflowType
        none = 0
        <Description("搜索设备")>
        SearchEquipment = 192
        <Description("写入Flash"）>
        FlashWrite = 195
        <Description("写入EEPROM"）>
        EEPROMWrite = 198
        <Description("群写入Flash"）>
        FlashGroupUpgrade

        <Description("Boot搜索"）>
        BootSearchEquipment

        <Description("Boot搜索"）>
        ReadingFlashData


    End Enum
    '自增SN号
    Public Function GetSN() As Integer
        If SN < 15 Then
            SN += 1
        Else
            SN = 0
        End If
        Console.WriteLine("SN:" & SN)
        Return SN
    End Function


    '创建协议类对象
    Public Shared Function CreateProtocol(communicationType As CommunicationType) As Object
        Select Case communicationType
            Case CommunicationType.SerialPort
                Return New SerialPort_BLV_Bootloader()
            Case CommunicationType.Udp
                Return New SerialPort_BLV_Bootloader()
            Case Else
                Return Nothing
        End Select
    End Function


    Public MustOverride Function PacketDataSearchCommand(ParamArray args() As String) As Byte()



    Public MustOverride Function PacketDataSkipCommand(ParamArray args() As String) As Byte()



    Public MustOverride Function PacketDataSetUpParameters(ParamArray args() As String) As Byte()



    Public MustOverride Function PacketDataWriteFlashData(ParamArray args() As String) As Byte()



    Public MustOverride Function PacketDataReadingFlashData(ParamArray args() As String) As Byte()


    Public MustOverride Function PacketDataEraseFlashData(ParamArray args() As String) As Byte()



    Public MustOverride Function PacketDataWriteEEPROMData(ParamArray args() As String) As Byte()



    Public MustOverride Function PacketDataReadingEEPROMData(ParamArray args() As String) As Byte()



    Public MustOverride Function PacketDataEraseEEPROMData(ParamArray args() As String) As Byte()



    Public MustOverride Function PacketDataCheckCommand(ParamArray args() As String) As Byte()
    Public MustOverride Sub SetUpgradeProgressProgressbar(gTable As DataGridView, addr As String, devtype As String, val As String, bcolor As Color, Optional RText_OutputText As RichTextBox = Nothing)
    Public MustOverride Sub NewSearchEquipmentProcess(Parameterlist As Parameterlist)
    Public MustOverride Sub NewBootSearchEquipmentProcess(Parameterlist As Parameterlist)
    Public MustOverride Sub OrdinaryOccurrenceCommand(Parameterlist As Parameterlist)

    Public MustOverride Sub WorkflowTypeNone(Parameterlist As Parameterlist, ByRef isRuning As Boolean)
    Public MustOverride Sub NewUpgradeProcess(Parameterlist As Parameterlist)
    Public MustOverride Sub NewFlashGroupUpgrade(Parameterlist As Parameterlist)

    Public MustOverride Sub NewSearchEquipmentProcess2(Parameterlist As Parameterlist)
    Public MustOverride Sub NewBootSearchEquipmentProcess2(Parameterlist As Parameterlist)
    Public MustOverride Sub NewUpgradeProcess2(Parameterlist As Parameterlist)
    Public MustOverride Sub NewFlashGroupUpgrade2(Parameterlist As Parameterlist)
    '获取固定流程
    Public Function GetImmobilizationWorkflow(g_WorkflowType As WorkflowType) As Boolean
        Dim li As New List(Of (number As Integer, Cmdconfig))
        Dim WorkflowName As String = DataProcessing.GetEnumDescription(g_WorkflowType)
        If Not m_flowdic.ContainsKey(WorkflowName) Then
            Select Case g_WorkflowType
                Case WorkflowType.SearchEquipment
                    li.Add((0, New Cmdconfig({CmdType.SearchCommand, GetSN()， 0, 0, 10， 1})))
                Case WorkflowType.FlashWrite， WorkflowType.EEPROMWrite
                    li.Add((0, New Cmdconfig({CmdType.SearchCommand, GetSN()， 0, 0, 10， 1})))
                    li.Add((1, New Cmdconfig({CmdType.SearchCommand, GetSN()， 0, 0, 10， 1})))
                    li.Add((2, New Cmdconfig({CmdType.SearchCommand, GetSN()， 0, 0, 10， 1})))
                    li.Add((3, New Cmdconfig({CmdType.SearchCommand, GetSN()， 0, 0, 10， 1})))
                    li.Add((4, New Cmdconfig({CmdType.SearchCommand, GetSN()， 0, 0, 10， 1})))
                    li.Add((5, New Cmdconfig({CmdType.SearchCommand, GetSN()， 0, 0, 10， 1})))
                    li.Add((6, New Cmdconfig({CmdType.SearchCommand, GetSN()， 0, 0, 10， 1})))
                    'Case WorkflowType.EEPROMWrite
                    '    li.Add((0, New Cmdconfig({CmdType.SearchCommand, GetSN()， 0, 0, 10， 1})))
                    '    li.Add((0, New Cmdconfig({CmdType.SearchCommand, GetSN()， 0, 0, 10， 1})))
            End Select
        End If

    End Function
    '创建Cmdconfig 节点




    '升级流程
    Public MustOverride Function UpgradeProcess(g_Cmdconfig As List(Of (number As Integer, Cmdconfig)), ParamArray args() As Object) As String

    '搜索流程 
    ''' <summary>
    '''  搜索设备流程
    ''' </summary>
    ''' <param name="args">超时时间、表格控件、打印控件 </param>
    ''' <returns></returns>
    Public MustOverride Function SearchEquipmentProcess(g_Cmdconfig As Cmdconfig, ParamArray args() As Object) As Boolean
    '开始时间

    '写入Flash流程

    Public Function FlashWriteProcess(ParamArray args() As String) As Boolean

    End Function
    '写入EEPROM流程
    Public Function EEPROMWriteProcess(ParamArray args() As String) As Boolean

    End Function

    Public Overrides Function Runing(Parameterlist As Parameterlist, ByRef isRuning As Boolean) As Boolean
        Try
            m_Transmitter.mCommunicationFlow = Me
            If Parameterlist.CommunicationTypeIndex = 1 Then
                Select Case Parameterlist.Action
                    Case WorkflowType.SearchEquipment
                        NewSearchEquipmentProcess(Parameterlist) '搜索设备流程  False
                    Case WorkflowType.FlashWrite
                        NewUpgradeProcess(Parameterlist)           '群组升级流程
                    Case WorkflowType.EEPROMWrite
                    Case WorkflowType.FlashGroupUpgrade
                        'Console.WriteLine(Parameterlist)
                        NewFlashGroupUpgrade(Parameterlist) 'flash组升级流程
                    Case WorkflowType.BootSearchEquipment
                        NewBootSearchEquipmentProcess(Parameterlist) 'boot搜索流程 true
                    Case WorkflowType.ReadingFlashData
                        OrdinaryOccurrenceCommand(Parameterlist)
                    Case WorkflowType.none
                        WorkflowTypeNone(Parameterlist, isRuning)

                End Select
            ElseIf Parameterlist.CommunicationTypeIndex = 2 Then
                Select Case Parameterlist.Action
                    Case WorkflowType.SearchEquipment
                        NewSearchEquipmentProcess2(Parameterlist)
                    Case WorkflowType.FlashWrite
                        NewUpgradeProcess2(Parameterlist)
                    Case WorkflowType.EEPROMWrite
                    Case WorkflowType.FlashGroupUpgrade
                        'Console.WriteLine(Parameterlist)
                        NewFlashGroupUpgrade2(Parameterlist)
                    Case WorkflowType.BootSearchEquipment
                        NewBootSearchEquipmentProcess2(Parameterlist)
                    Case WorkflowType.none
                        WorkflowTypeNone(Parameterlist, isRuning)
                End Select
            End If

        Catch ex As Exception

            AddQueue(Parameterlist.RText_OutputText, New RuningLogConfig($"线程运行错误：{ ex.Message }", Color.Red))
            Return False
            'OutputLogsToTheControl(Parameterlist.RText_OutputText, New RuningLogConfig($"线程运行错误：{ ex.Message }", Color.Red), 1)
        End Try


    End Function

End Class

Public Class BLV_Bootloaderconfig
    '搜索设备流程开关
    Public SearchEquipmentProcessSwitch As Boolean = False
    '升级流程开关
    Public UpgradeProcessSwitch As Boolean = False

    '己方地址
    Public MyAddress As Byte = 0
    ''接受者类型
    Public ReceiverType As Byte = 0

    '设备类型
    Public DeviceType As Byte = 0
    '对方地址
    Public ReceiverAddress As Byte = 0
    '单发开关
    Public SingleSwitch As Boolean = False
    '重发开关
    Public ResendSwitch As Boolean = False

    '校验和
    Sub New()
        MyAddress = 0
        ReceiverType = 96
        DeviceType = 0
    End Sub

    ''' <summary>
    ''' 
    ''' </summary>
    ''' <param name="args"></param>
    ''' <returns></returns>
    Public Function SetProtocolParam(ParamArray args() As String) As String
        Dim msgstr As String = ""
        Try
            MyAddress = CByte(args(0))
            Dim nbuf() As String = args(1).Split(",")
            If nbuf.Length < 3 OrElse Not SetReceiverType(nbuf(0), nbuf(1), nbuf(2)， msgstr) Then Return False
            DeviceType = CByte(args(2))
            ReceiverAddress = CByte(args(3))

        Catch ex As Exception
            msgstr = " set protocol parameters fail "
        End Try
        Return msgstr
    End Function
    '


    '设置接受者类型数据
    'addr：1群发，0单发
    'resend：1重发，0不重发
    Public Function SetReceiverType(addr As Boolean, resend As Boolean, SN As Integer, ByRef Optional msgstr As String = "") As Boolean
        Dim nReceiverType As Byte = 0
        If SN > 15 AndAlso SN < 0 Then
            msgstr = "The communication protocol SN of the BLV_Bootloader is incorrect：SN=" & SN
            Return False
        End If
        If addr Then
            nReceiverType = nReceiverType Or (1 << 7)
        End If
        If resend Then
            'SN = ReceiverType
            nReceiverType = nReceiverType Or (1 << 6)
        Else
            ResendSwitch = True
        End If
        nReceiverType = nReceiverType Or SN
        ReceiverType = nReceiverType
        Return True
    End Function
    '设置接受者类型数据
    'addr：1群发，0单发
    'resend：1重发，0不重发
    Public Function SetReceiverType1(addr As Boolean, resend As Boolean, SN As Integer, ByRef Optional msgstr As String = "") As Boolean
        Dim nReceiverType As Byte = 0
        If SN > 15 AndAlso SN < 0 Then
            msgstr = "The communication protocol SN of the BLV_Bootloader is incorrect：SN=" & SN
            Return False
        End If
        If addr Then
            nReceiverType = nReceiverType Or (1 << 7)
        End If
        If resend Then
            SN = ReceiverType '
            nReceiverType = nReceiverType Or (1 << 6)
        Else
            ResendSwitch = True
        End If
        nReceiverType = nReceiverType Or SN
        ReceiverType = nReceiverType
        Return True
    End Function
End Class
