'Main module
Sub Process_Globals
    Private fx As JFX
    Private MainForm As Form
    
    'Socket used to connect to the NTRIP caster
    Private ntripSocket As Socket
    Private astream As AsyncStreams
    
    'Caster connection details
    Private ntripHost As String = "your-caster.com"
    Private ntripPort As Int = 2101
    Private mountPoint As String = "YourMountpoint"
    
    'User credentials for Basic Authentication
    Private ntripUser As String = "username"
    Private ntripPass As String = "password"
    
    'Flag to stop streaming
    Private stopStream As Boolean = False
End Sub

Sub AppStart (Form1 As Form, Args() As String)
    MainForm = Form1
    MainForm.Show
    
    'Initialize the socket and connect
    ntripSocket.Initialize("ntripSocket")
    ConnectToNTRIPCaster
End Sub

'-------------------------------------------------------------------------------------------
' ConnectToNTRIPCaster: Establishes a socket connection to the caster and performs handshake.
'-------------------------------------------------------------------------------------------
Sub ConnectToNTRIPCaster
    Log("Connecting to: " & ntripHost & ":" & ntripPort)
    ntripSocket.Connect(ntripHost, ntripPort, 10000) ' 10 second timeout
End Sub

'-------------------------------------------------------------------------------------------
' ntripSocket_Connected: Once the socket is connected, we send the NTRIP GET request.
'-------------------------------------------------------------------------------------------
Sub ntripSocket_Connected (Successful As Boolean)
    If Successful Then
        Log("Socket connected successfully!")
        astream.InitializePrefix(ntripSocket.InputStream, False, ntripSocket.OutputStream, "astream")
        
        'Prepare the HTTP-like request for NTRIP v2.0
        Dim request As StringBuilder
        request.Initialize
        request.Append("GET /").Append(mountPoint).Append(" HTTP/1.0").Append(CRLF)
        request.Append("User-Agent: NTRIP B4JClient/2.0").Append(CRLF)
        request.Append("Accept: */*").Append(CRLF)
        request.Append("Connection: keep-alive").Append(CRLF)
        
        'Add basic auth header
        Dim credentials As String = ntripUser & ":" & ntripPass
        Dim authEncoded As String = bc.EncodeBase64(credentials.GetBytes("UTF8"))
        request.Append("Authorization: Basic ").Append(authEncoded).Append(CRLF)
        
        'End headers
        request.Append(CRLF)
        
        'Send request
        astream.Write(request.ToString.GetBytes("UTF8"))
    Else
        Log("Failed to connect to the NTRIP caster.")
    End If
End Sub

'-------------------------------------------------------------------------------------------
' astream_NewData: Called whenever the caster sends data. This is typically RTCM correction data.
'-------------------------------------------------------------------------------------------
Sub astream_NewData (Buffer() As Byte)
    'In a real-world scenario, you would forward this raw data to a GNSS receiver (e.g., over serial).
    'Here, we'll just log the size to show we are receiving data.
    
    Log("Received " & Buffer.Length & " bytes of data from NTRIP caster.")
    
    'Example: Forward to GNSS hardware or parse the RTCM messages if needed.
    'YourGNSSForwardMethod(Buffer)
    
    'If you want to stop streaming for any reason:
    If stopStream Then
        astream.Close
        ntripSocket.Close
    End If
End Sub

'-------------------------------------------------------------------------------------------
' astream_Terminated and astream_Error: Clean up the connection on termination or error.
'-------------------------------------------------------------------------------------------
Sub astream_Terminated
    Log("Connection terminated.")
    astream.Close
    ntripSocket.Close
End Sub

Sub astream_Error (Buffer() As Byte, Success As Boolean)
    Log("Error in astream. Success = " & Success)
    astream.Close
    ntripSocket.Close
End Sub

'-------------------------------------------------------------------------------------------
' bc: A ByteConverter instance for Base64 encoding the username and password.
'-------------------------------------------------------------------------------------------
Sub bc As ByteConverter
    Static bc1 As ByteConverter
    Return bc1
End Sub
