Android Question UDP socket help

Meganoodle

New Member
Licensed User
Longtime User
Hi there
I've just returned to B4x after a couple of years so I'm a little out of practice.
I created program on my raspberry pi to read telemetry data from a game to create a dashboard with speed lap times etc.
It works quite well so I want to adapt the code to B4a and im struggling with the first two hurdles (not a great start I know).

Firstly: I need to read the data stream so obviously I need to initialize the socket, Ive tried a few examples and adapted them to the port (5060), doesnt matter whjat piece of code I try i get the error (Addresses already in use)

Second: I need to breakdown and decode the packet from binaray into individual variables ranging through ints, floats and strings ,it then needs to be decoded from binary.

Each variable ranges in size, I have the locations of where I can find each variable and I know what data types they need to be converted to, Im just not sure how to break it down in B4a.

this is a snippet of code that works in python which reads the data decodes the best lap time and prints it in the debug window.

project cars udp socket reader:
import socket
import struct
import time
personalbestlap=0.0
package_type=-1
UDP_IP_ADDRESS = "0.0.0.0"
UDP_PORT_NO = 5606
running=True

serverSock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
serverSock.bind((UDP_IP_ADDRESS, UDP_PORT_NO))

def check_package_type(package):
    return (struct.unpack('B', package[2:3])[0] & 0x3)

while running:
    data, addr = serverSock.recvfrom(10000)
    if data is not None:
        package_type=check_package_type(data)
        if (package_type==0):
            print(package_type)
            sd=struct.unpack('f', data[40:44])[0]
            if (sd>=1.0):
                personalbestlap=sd
                print(personalbestlap)


Im looking for any insight or examples I might be able to adapt for my project.

Thanks for your consideration
 

Erel

B4X founder
Staff member
Licensed User
Longtime User
Firstly: I need to read the data stream so obviously I need to initialize the socket, Ive tried a few examples and adapted them to the port (5060), doesnt matter whjat piece of code I try i get the error (Addresses already in use)
Lets start with this. Please post the relevant code. It should be in the starter service.
 
Upvote 0

Meganoodle

New Member
Licensed User
Longtime User
Thanks for the reply.
Well here is what Ive done so far, it doesnt compile now , I gave up on it last night was up late trying to make something work.
It worked (somewhat unreliably) but i found sometimes it took up to 20 minutes to even connect if at all, regardless i thought i would plod on to trying to decode the data into their relevant types, but my understanding of decoding binary strings to other datatypes is pretty limited , even in python I had help.
I know the script is scruffy and needs to be adjusted , i just want to get a working model I can expand upon and play with.


My b4a attempt:
Sub process_globals
    Dim UDPSocket1 As UDPSocket
    Dim su As StringUtils
    Dim bc As ByteConverter
    
    
End Sub

Sub Globals
    Dim pw As PhoneWakeState
    Private INFO As EditText
End Sub
Sub Activity_Create(FirstTime As Boolean)
    pw.KeepAlive(True)
    Activity.LoadLayout("test")
    If FirstTime Then
        UDPSocket1.Initialize("UDP", 5606, 1367)
    End If
    

End Sub
Sub UDP_PacketArrived (Packet As UDPPacket)
    Dim packet_type As Int
    Dim rdata As String
    INFO.Text="reading"
    rdata = "text="& BytesToString(Packet.Data, 2, 1, "UTF8")
    packet_type=bc.IntsFromBytes(rdata)
    INFO.Text=packet_type
End Sub
 
Upvote 0

Meganoodle

New Member
Licensed User
Longtime User
Thanks thats a great help!
This is what Ive got so far , and it works most of the time , while adding new code and restarting the program it stops recieving data altogether , and then after a few stops and restarts it works again, not sure why , any suggestions?


B4X:
Sub Process_Globals
    'These global variables will be declared once when the application starts.
    'These variables can be accessed from all modules.
    Dim us As UDPSocket
    
End Sub

Sub Globals
    'These global variables will be redeclared each time the activity is created.
    'These variables can only be accessed from this module.
    Dim pw As PhoneWakeState

End Sub

Sub Activity_Create(FirstTime As Boolean)
    'Do not forget to load the layout file created with the visual designer. For example:
    'Activity.LoadLayout("Layout1")
    pw.KeepAlive(True)
    If FirstTime Then
        us.Initialize("usocket", 5606, 1367)
        If us.IsInitialized Then
            Log("Initialised")
        End If
    End If

End Sub

Sub Activity_Resume

End Sub

Sub Activity_Pause (UserClosed As Boolean)
    us.Close
    Log ("closing port")
    
End Sub

Private Sub usocket_PacketArrived (Packet As UDPPacket)
    Dim raf As RandomAccessFile
    Dim personal_best As Float
    Dim session_best As Float
    Dim previous As Float
    Dim current As Float
    Dim rpm As Int
    Dim speed As Float
    Log("recieving data")
    raf.Initialize3(Packet.Data, True)
    
    Log($"packet Length: $1{Packet.length}"$)
    If Packet.Length>=1367 Then
        session_best=raf.ReadFloat(12)
        previous=raf.ReadFloat(16)
        current=raf.ReadFloat(20)
        personal_best=raf.ReadFloat(40)
        speed=raf.ReadFloat(120)
        rpm=raf.ReadInt(124)
        Log($"Session Best: $1{session_best}"$)
        Log($"Previous Lap: $1{previous}"$)
        Log($"Current Lap: $1{current}"$)
        Log($"personal best: $1{personal_best}"$)
        Log($"Speed:$1.0{speed}"$)
        Log($"RPM: $1.0{rpm}"$)
    End If
            
    If Packet.Length=1347 Then
        Log("packet 2")
    End If
    Return

End Sub
 
Upvote 0

Meganoodle

New Member
Licensed User
Longtime User
ok, so I need to move both the 'initialize code and the 'packet arrived' code into the starter module?
I had it working again briefly today but then it stopped and wouldnt recieve anything, despite the raspberry pi sitting on my desk is still ticking away nicley.
Sorry to keep bothering you with this.
 
Upvote 0

Erel

B4X founder
Staff member
Licensed User
Longtime User
Upvote 0
Top