⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 mainform.vb

📁 usb mass storage固件代码usbwiz_demo
💻 VB
📖 第 1 页 / 共 2 页
字号:
        Try

            selectedPort.PortName = myComPorts(selectedPortIndex).PortName
            selectedPort.BaudRate = myComPorts(selectedPortIndex).BitRate
            selectedPort.Parity = myComPorts(selectedPortIndex).Parity
            selectedPort.DataBits = myComPorts(selectedPortIndex).DataBits
            selectedPort.StopBits = myComPorts(selectedPortIndex).StopBits

            selectedPort.Open()

            selectedPort.Handshake = Handshake.RequestToSend
            'SelectedPort.Handshake = Handshake.None

            ' Timeouts are in milliseconds.
            selectedPort.ReadTimeout = 5000
            selectedPort.WriteTimeout = 5000

            ' The USBwiz expects to see just a CR (no LF) after commands and data.
            selectedPort.NewLine = vbCr

            txtMonitor.AppendText("Using " + selectedPort.PortName + " at " + CStr(selectedPort.BaudRate) + " bps." + vbCrLf)

        Catch ex As InvalidOperationException
            HandleException(ModuleName, ex)
            PortSettings.Show()
            PortSettings.lbxStatus.Text = "The selected port is already open."
            transferInProgress = False
        Catch ex As UnauthorizedAccessException
            HandleException(ModuleName, ex)
            PortSettings.Show()
            PortSettings.lbxStatus.Text = "The selected port isn't available."
            transferInProgress = False
        Catch ex As System.IO.IOException
            HandleException(ModuleName, ex)
            PortSettings.Show()
            PortSettings.lbxStatus.Text = "The port is in an invalid state or an attempt to set the state of the port failed."
            transferInProgress = False

        End Try
    End Sub

    Private Sub PortToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PortToolStripMenuItem.Click

        PortSettings.DisplayComPorts()
        MyPortSettings.Show()

    End Sub

    Private Function ReadDataFromUsbwiz(ByRef receivedData As String) As String

        ' Purpose    :  Get a line of data (up to a carriage return) and a response code
        '               from the COM port..  

        ' Accepts    :  receivedData - a string to hold the data.

        ' Returns    :  USBwiz response code

        Dim incomingData As String = ""
        Dim response As String = ""

             ' Read a line of data sent by the USBwiz.
        receivedData = selectedPort.ReadLine

        ' Get the response code. 
        response = ReadResponseFromUsbwiz()

        Return response

    End Function

    Private Sub ReadFromFile()

        ' Purpose    : find a file and read and display the contents.

        Dim bytesRead As String = ""
        Dim bytesToRead As Integer = 0
        Dim command As String = ""
        Dim dataToSend As String = ""
        Dim dataToSendLength As String = ""
        Dim fileInformation As String = ""
        Dim fileSize As Integer = 0
        Dim receivedData As String = ""
        Dim response As String = ""
        Dim strBytesToRead As String = ""
        Dim strFileSize As String = ""

        txtMonitor.Clear()

        Try
            ' If a transfer is in progress, do nothing.
            If Not (transferInProgress) Then

                transferInProgress = True

                If ((enumerated = False) Or (portChange = True)) Then
                    InitializeDriveCommunications()
                End If

                If enumerated Then
                    command = "IF " + fileName
                    txtMonitor.AppendText("Finding the file: " + command + vbCrLf)

                    response = SendCommandToUsbwiz(command)
                    If (response = Success) Then

                        response = ReadDataFromUsbwiz(fileInformation)

                        ' Get the file size from the returned file information structure.
                        ' Remove the leading "$".
                        strFileSize = fileInformation.TrimStart("$"c)

                        ' Remove everything starting with the first remaining "$".
                        If strFileSize.Contains("$") Then
                            strFileSize = strFileSize.Substring(0, strFileSize.IndexOf("$"c))
                        End If

                        ' Remove trailing space. What's left is the file size expressed in ASCII hex.
                        strFileSize = strFileSize.Trim

                        ' Convert the file size from ASCII Hex to an integer.
                        fileSize = CInt(Val("&H" + strFileSize))

                        ' If the file is larger than 512 bytes, we'll read just the first 512 bytes.
                        If fileSize < 512 Then
                            bytesToRead = fileSize
                            strBytesToRead = strFileSize
                        Else
                            bytesToRead = 512
                            strBytesToRead = "200"
                        End If

                        command = "OF " + fileHandle + "R>" + fileName
                        txtMonitor.AppendText("Opening the file " + fileName + " for reading: " + command + vbCrLf)

                        response = SendCommandToUsbwiz(command)
                        If (response = Success) Then

                            command = "RF " + fileHandle + fillerSymbol + ">" + strBytesToRead
                            response = SendCommandToUsbwiz(command)

                            If (response = Success) Then
                                txtMonitor.AppendText("Reading the file: " + command + vbCrLf)

                                ' Read the file.
                                response = ReadFileContents(receivedData, CInt(Val(bytesRead)), bytesToRead)

                                If (response = Success) Then
                                    txtMonitor.AppendText("File contents:" + vbCrLf)
                                    txtMonitor.AppendText(receivedData + vbCrLf)
                                Else
                                    DisplayFailureMessage(command, response)
                                    CloseDeviceHandle()
                                End If
                            Else
                                DisplayFailureMessage(command, response)
                                CloseDeviceHandle()
                            End If
                        Else
                            DisplayFailureMessage(command, response)
                            CloseDeviceHandle()
                        End If
                    Else
                        DisplayFailureMessage(command, response)
                        CloseDeviceHandle()
                    End If

                    command = "CF " + fileHandle
                    txtMonitor.AppendText("Closing the file: " + command + vbCrLf)

                    response = SendCommandToUsbwiz(command)
                    If (response = Success) Then
                    Else
                        DisplayFailureMessage(command, response)
                    End If
                Else
                    txtMonitor.AppendText("Unable to enumerate the device.")
                End If
            Else
                txtMonitor.AppendText("A previous transfer is in progress.")
            End If
        Catch ex As TimeoutException
            txtMonitor.AppendText("Timeout" + vbCrLf)
            CloseDeviceHandle()

        Catch ex As InvalidOperationException
            txtMonitor.AppendText("Invalid operation" + vbCrLf)
            CloseDeviceHandle()

        Finally
            transferInProgress = False
        End Try
    End Sub

    Private Function ReadResponseFromUsbwiz() As String

        ' Purpose    : read a response code from the USBwiz.

        ' Returns    : USBwiz response code

        Dim incomingData As String = ""
        Dim response As String = ""

        'Read a line of text from the USBwiz.
        response = selectedPort.ReadLine

        Return response

    End Function

    Private Function SendCommandToUsbwiz(ByVal command As String) As String

        ' Purpose    : send a command to the USBwiz and read a response.

        ' Accepts    : command - a command.

        ' Returns    : USBwiz response code

        Dim response As String = ""

        receiveBuffer = ""

        ' Send the command followed by a carriage return.
        selectedPort.WriteLine(command)

        ' Read a returned line of text.
        response = ReadResponseFromUsbwiz()

        Return response

    End Function

    Private Function SendDataToUsbwiz(ByVal dataToSend As String) As String

        ' Purpose    : send data and a carriage return to the USBwiz,
        '              read a returned line of text and a response code.          

        ' Accepts    : dataToSend - the data to send.

        Dim byteArray() As Byte
        Dim receivedData As String = ""
        Dim response As String = ""

        receiveBuffer = ""

        ' Convert the data to send from a string to a byte array.
        byteArray = Encoding.Default.GetBytes(dataToSend)

        ' Send the contents of the byte array.
        selectedPort.Write(byteArray, 0, byteArray.GetLength(0))

        ' Read a returned line of text and the response code.
        response = ReadDataFromUsbwiz(receivedData)

        Return response
    End Function

    Private Sub WriteToFile()

        ' Purpose    : write text to a file on a drive attached to the USBwiz.
        '              Creates the file if it doesn't exist.        

        Dim command As String = ""
        Dim response As String = ""
        Dim dataToSend As String = ""
        Dim dataToSendLength As String = ""

        txtMonitor.Clear()

        Try
            ' If a transfer is in progress, do nothing.
            If Not transferInProgress Then

                transferInProgress = True

                If ((Not enumerated) Or portChange) Then
                    InitializeDriveCommunications()
                End If

                If enumerated Then
                    dataToSend = DisplayDateAndTime() + vbCrLf

                    ' Uncomment to send this line of text:
                    'dataToSend = "hello, world"

                    dataToSendLength = Hex$(dataToSend.Length)

                    ' Use either append or overwrite:

                    ' Open for append:
                    command = "OF " + fileHandle + "A>" + fileName

                    ' Open for overwrite:
                    'command = "OF " + fileHandle + "W>" + fileName

                    txtMonitor.AppendText _
                    ("Opening the file " + fileName + " for writing: " + command + vbCrLf)

                    response = SendCommandToUsbwiz(command)
                    If (response = Success) Then
                        command = "WF " + fileHandle + ">" + dataToSendLength
                        txtMonitor.AppendText("Writing to the drive: " + command + vbCrLf)
                        txtMonitor.AppendText(dataToSend + vbCrLf)

                        response = SendCommandToUsbwiz(command)
                        If (response = Success) Then

                            ' Write to the file
                            If (SendDataToUsbwiz(dataToSend) = Success) Then
                                command = "CF " + fileHandle
                                txtMonitor.AppendText("Closing the file: " + command + vbCrLf)

                                response = SendCommandToUsbwiz(command)
                                If (response = Success) Then
                                    txtMonitor.AppendText _
                                    ("Write operation completed successfully." + vbCrLf)
                                Else
                                    DisplayFailureMessage(command, response)
                                    CloseDeviceHandle()
                                End If
                            Else
                                DisplayFailureMessage(command, response)
                                CloseDeviceHandle()
                            End If
                        Else
                            DisplayFailureMessage(command, response)
                            CloseDeviceHandle()
                        End If
                    Else
                        DisplayFailureMessage(command, response)
                        CloseDeviceHandle()
                    End If
                    transferInProgress = False
                End If
            End If

        Catch ex As TimeoutException

            txtMonitor.AppendText("Timeout" + vbCrLf)
            CloseDeviceHandle()

        Catch ex As InvalidOperationException

            txtMonitor.AppendText("Invalid operation" + vbCrLf)
            CloseDeviceHandle()

        End Try
    End Sub

    Shared Sub HandleException(ByVal moduleName As String, ByVal e As Exception)

        ' Purpose    : Provide a central mechanism for exception handling.
        '            : Display a message box that describes the exception.

        ' Accepts    : moduleName - the module where the exception occurred.
        '            : e - the exception

        Dim Message As String
        Dim Caption As String

        Try
            'Create an error message.
            Message = "Exception: " & e.Message & ControlChars.CrLf & _
            "Module: " & moduleName & ControlChars.CrLf & _
            "Method: " & e.TargetSite.Name

            'Specify a caption.
            Caption = "Unexpected Exception"

            'Display the message in a message box.
            MessageBox.Show(Message, Caption, MessageBoxButtons.OK)
            Debug.Write(Message)
        Finally
        End Try
    End Sub

End Class

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -