LapTux
LapTux

Reputation: 21

Hex Formatting in Python

I've been stuck on this one for a while now. I need to send a serial command to a device in python. Here's an example of the format:

ser = serial.Serial('/dev/ttyO1',baudrate=115200)
ser.write('\xAA\x04\x05\x00\x00\x00')

I'm able to communicate just fine if I communicate using the format .write(~hex bytes~)

However, when I need to receive larger chunks of data, the device's communication protocol splits things into packets and I have to confirm receiving each packet. To avoid getting carpal tunnel syndrome while typing out individual ser.write() commands for each packet I want to write a loop that does the packet counting/confirmation for me. here's what I have:

for n in range(0,num_packets,1):

    x = '\\x'"%0.2x"%(n)    
    print('Picture Ready Host Ack')
    ser.write('\xAA\x0E\x00\x00' + x + '\x00')
    time.sleep(.1)
    response = ser.read(ser.inWaiting())
    image_write(response,base_path, filename)        

However, the double slashes ('\x'..) gives me two slashes:

'\xaa\x0e\x00\x00\\x05\x00'

While a single slash ('\x'...) returns a problem when I define the variable x:

ValueError: invalid \x escape

...Help?

Upvotes: 1

Views: 2588

Answers (2)

Senthil Kumaran
Senthil Kumaran

Reputation: 56841

\xij just expands to the character chr(int(ij, 16)) Since you are anyway sending bytes, I would say in a loop, send your first chunk. Do not add anything to it, then send your delimiter by chr(int(n),16) and subsequently the next chunks. This should solve your problem.

Upvotes: 0

Jonathan Callen
Jonathan Callen

Reputation: 11571

If instead of defining x as '\\x'"%0.2x"%(n), you do x = chr(n), everything should work.

Upvotes: 2

Related Questions