Search code examples
pythongpsudpteltonika

Python format UDP messages format hexadecimal


Hello friends I have a socket server in python that is based on the UDP protocol when receiving the messages sent by a gps device, teltonika shows me the following:

'\ x00b \ xca \ xfe \ x01 \ x16 \ x00 \ x0f359632103146970 \ x08 \ x01 \ x00 \ x00 \ x01t \ xd6 \ x16 \ xab` \ x00 \ xd2 $ \ xe1J \ xf8 \ xc9 ^ - \ x01B \ x01B \ t \ x00 \ x00 \ x00 \ x0f \ x05 \ xef \ x01 \ xf0 \ x01 \ x15 \ x04 \ xc8 \ x00E \ x01 \ x08 \ xb5 \ x00 \ x06 \ xb6 \ x00 \ x05B0 \ xff \ x18 \ x00 \ x00 \ xcdiX \ xce \ x04eC \ x0f \ x8eD \ x00 \ x00 \ x02 \ xf1 \ x00 \ x01 \ x17 \ xb6 \ x10 \ x00 \ x006 \ x10 \ x00 \ x01 '

but the correct information should be:

00 62 CA FE 01 16 00 0F 33 35 39 36 33 32 31 30 33 31 34 36 39 37 30 08 01 00 00 01 74 D6 16 AB 60 00 D2 24 E1 4A F8 C9 5E 2D 01 42 01 42 09 00 00 00 0F 05 EF 01 F0 01 15 04 C8 00 45 01 08 B5 00 06 B6 00 05 42 30 FF 18 00 00 CD 69 58 CE 04 65 43 0F 8E 44 00 00 02 F1 00 01 17 B6 10 00 00 36 10 00 01

How could I receive in this format, this is my code:

import socket
from ast import literal_eval
 

localIP     = "192.168.0.30"

localPort   = 12560

bufferSize  = 1024

 

msgFromServer       = "1"

bytesToSend         = str.encode(msgFromServer)

 

# Create a datagram socket

UDPServerSocket = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)

 

# Bind to address and ip

UDPServerSocket.bind((localIP, localPort))

 

print("UDP server up and listening")

 

# Listen for incoming datagrams

while(True):

    bytesAddressPair = UDPServerSocket.recvfrom(bufferSize)

    message = bytesAddressPair[0]

    address = bytesAddressPair[1]

    clientMsg = "Message from Client:{}".format(message)
    clientIP  = "Client IP Address:{}".format(address)
    
    #messajes= Encoding.ASCII.GetString(message)
    
    print(clientMsg)
    print(clientIP)
    print(bytesAddressPair)
   

    # Sending a reply to client

    UDPServerSocket.sendto(bytesToSend, address)

thanks for your help


Solution

  • You are getting your data back as python bytes. You can convert them to a hex string representation using the .hex() method if that is what you are after. For example:

    data = b"\x00b \xca \fe \x01 \x0f359632103146970"
    data.hex()
    '006220ca200c652001200f333539363332313033313436393730'
    

    From the python 3 docs

    socket.recvfrom(bufsize[, flags])

    Receive data from the socket. The return value is a pair (bytes, address) where bytes is >a bytes object representing the data received and address is the address of the socket >sending the data. See the Unix manual page recv(2) for the meaning of the optional >argument flags; it defaults to zero. (The format of address depends on the address family >— see above.)"