'https://msdn.microsoft.com/en-us/library/7ya7y41k.aspx?f=255&MSPPError=-2147217396
Imports System.Math
Imports System.Threading
Imports System.IO.Ports
Imports System.Drawing


Module modIF_Hero

    '================================  Hero Serial IF  =========================================
    Private comBot As New SerialPort
    Dim boolMoveInProgress As Boolean = False

    Public Function ftnHeroConfig() As Boolean
        ' returns true if comBot is successfully opened
        Try
            ftnHeroConfig = False
            If Not boolBotConnected Then
                Dim availableSerialPorts As System.Collections.ObjectModel.ReadOnlyCollection(Of String) = My.Computer.Ports.SerialPortNames
                If Not boolShutDown And (comBot.PortName <> "None") And availableSerialPorts.Contains(comBot.PortName) Then
                    With comBot
                        .PortName = comBot.PortName
                        .BaudRate = 9600
                        .DataBits = 7
                        .Parity = Parity.None
                        .StopBits = StopBits.One
                        .Handshake = Handshake.None
                    End With
                    comBot.Open()
                    If Not comBot.IsOpen Then
                        ftnSendCommand("play phrase Beep")
                        MsgBox(" ERROR:  Hero Robot not detected.")
                    Else
                        ftnHero_Communicate(" ", ">", 1000) ' Empty Hero's interface buffer
                        If Not CBool(InStr(ftnHero_Communicate("GV", ">", 1000), "GotAHero")) Then
                            ftnSendCommand("play phrase Beep")
                            MsgBox(" Download Hero's interface program by" & vbCrLf & _
                                   "   1. Press 'Reset' then Enter '3A' on Hero" & vbCrLf & _
                                   "   2. Press 'OK' below" & vbCrLf & _
                                   "   3. Wait for download to complete" & vbCrLf & _
                                    vbCrLf & _
                                   " (Hero will say 'Ready' if download is sucessful)")
                            subHeroS19Download()
                            ftnSendCommand("play phrase Beep")
                            MsgBox(" Start Hero's interface program by" & vbCrLf & _
                                   "   1. Enter 'AD0200' on Hero" & vbCrLf & _
                                   " (Hero will display 'GH-100.' if sucessful)" & _
                                     vbCrLf & _
                                  "   2. Press 'OK' below" & vbCrLf & _
                                   " (Hero will display '-HEro-.' if sucessful)")
                            ftnHero_Communicate(" ", ">", 1000) ' Empty Hero's interface buffer
                            If Not CBool(InStr(ftnHero_Communicate("GV", ">", 1000), "GotAHero")) Then
                                ftnSendCommand("play phrase Beep")
                                MsgBox(" Download Failed")
                            Else
                                ftnHeroConfig = True
                                ftnHero_Communicate("GD08374F051D88", ">", 1000) ' Write "-Hero-" to robot's display
                                'ftnHero_Communicate("GU0", ">", 3000) ' Disable Ultrasonic Ranging
                            End If
                        Else
                            ftnHeroConfig = True
                        End If
                    End If
                End If
            End If
        Catch ex As Exception
            strStatusDriving = "ERROR: Hero Robot not detected."
            ftnSendCommand("play phrase Beep")
            MsgBox(" ERROR:  Hero Robot not detected.")
            ftnHeroConfig = False
            frmDebug.subWriteLogs(" EXCEPTION in ftnHeroConfig :  " & ex.ToString)
            frmDebug.subWriteLogs("    ERROR:  " & ex.Message)
        End Try
    End Function

    Dim boolHeroComInProgress As Boolean = False
    Public Function ftnHero_Communicate(ByRef strCommand As String, ByRef strResponse As String, ByRef intTimeOut As Integer) As String
        ftnHero_Communicate = ""
        Try
            Dim timeOut As DateTime = Now().AddMilliseconds(7000)
            While boolHeroComInProgress And (Now() < timeOut)
                Thread.Sleep(50)
                If boolDebugHero Then frmDebug.subWriteLogs(" ftnHero_Communicate:  Com In Progress")
            End While
            If Not boolShutDown And Not boolHeroComInProgress Then
                boolHeroComInProgress = True
                If (comBot Is Nothing) Or Not comBot.IsOpen Then ftnHeroConfig()
                If (comBot IsNot Nothing) Then
                    If comBot.IsOpen Then
                        boolBotConnected = True
                        subSendSerialData(strCommand)
                        If (strResponse <> "") And (intTimeOut <> 0) Then ftnHero_Communicate = ftnWaitForExpectedResponse(strResponse, intTimeOut, strCommand)
                    End If
                End If
                boolHeroComInProgress = False
            End If
        Catch ex As Exception
            boolHeroComInProgress = False
            frmDebug.subWriteLogs(" EXCEPTION in ftnHero_Communicate :  " & ex.ToString)
        End Try
    End Function

    Function ftnWaitForExpectedResponse(ByRef strTextToWaitFor As String, ByRef intTimeOut As Integer, ByRef strCommand As String) As String  '
        ftnWaitForExpectedResponse = ""
        Try
            ftnReceiveSerialData() ' Clear receiveddata buffer - Hero is slow so this should occur before the Hero replies
            comBot.ReadTimeout = Max(1000, intTimeOut)
            Dim timeOut As DateTime = Now().AddMilliseconds(intTimeOut)
            Do
                ftnWaitForExpectedResponse &= ftnReceiveSerialData()
                Thread.Sleep(25)
            Loop Until (Now() > timeOut) Or CBool(InStr(ftnWaitForExpectedResponse, strTextToWaitFor)) Or boolShutDown
            If (Now() > timeOut) Then
                frmDebug.subWriteLogs(ftnElapsedTimeS() & "  WARNING: Bot Communication Timeout while waiting for response: " & strTextToWaitFor & " /// Actual Response = " & ftnWaitForExpectedResponse)
                ftnWaitForExpectedResponse &= " com timeout"
            End If
            If boolDebugHero Then
                frmDebug.subWriteLogs(Now() & " }}}}}}}}}}====     Received From Bot:    " & ftnWaitForExpectedResponse)
                frmDebug.subWriteLogs(Now() & " }}}}}}}}}}====     Expected From Bot:    " & strTextToWaitFor)
                frmDebug.subWriteLogs(Now() & " }}}}}}}}}}==== ")
            End If
            ftnWaitForExpectedResponse = Replace(ftnWaitForExpectedResponse, strCommand, "", 1, -1)
            ftnWaitForExpectedResponse = Replace(ftnWaitForExpectedResponse, vbCr, "", 1, -1)
            ftnWaitForExpectedResponse = Replace(ftnWaitForExpectedResponse, vbLf, "", 1, -1)
            ftnWaitForExpectedResponse = Replace(ftnWaitForExpectedResponse, " ", "", 1, -1)
            ftnWaitForExpectedResponse = Replace(ftnWaitForExpectedResponse, strTextToWaitFor, "", 1, -1)
        Catch ex As Exception
            ftnWaitForExpectedResponse &= " COM ERROR"
            frmDebug.subWriteLogs(" EXCEPTION in ftnWaitForExpectedResponse :  " & ex.ToString)
        End Try
    End Function


    Function ftnReceiveSerialData() As String
        ' Receive strings from a serial port. 
        Try
            ftnReceiveSerialData = comBot.ReadExisting()
            comBot.DiscardInBuffer()
        Catch ex As TimeoutException
            ftnReceiveSerialData = ""
            frmDebug.subWriteLogs(" EXCEPTION in ftnReceiveSerialData = :  " & ex.ToString)
        End Try
    End Function

    Sub subSendSerialData(ByVal strData As String)
        ' Send strings to a serial port. 
        Try
            If boolDebugHero Then frmDebug.subWriteLogs(Now() & " }}}}}}}}}}====     Sent to Bot:    " & strData)
            Dim strLetter As String = ""
            For i As Integer = 1 To Len(strData)
                strLetter = Mid(strData, i, 1)
                comBot.Write(strLetter)
                Thread.Sleep(5)
            Next
            comBot.Write(vbCrLf)
        Catch ex As Exception
            frmDebug.subWriteLogs(" EXCEPTION in subSendSerialData :  " & ex.ToString)
        End Try
    End Sub

    Public Sub subCloseComBot()
        Try
            If comBot IsNot Nothing Then
                If comBot.IsOpen Then comBot.Close()
                comBot = Nothing
            End If
            boolBotConnected = False
        Catch ex As Exception
            frmDebug.subWriteLogs(" EXCEPTION in subCloseComBot :  " & ex.ToString)
        End Try
    End Sub







End Module
