Search code examples
pythonuart

how to send apacket from python file to my uart?


I want to make communication between laptop and UART via Python file by sending some packet: My packet contains=

   2 bytes for Star of frames+
   2 bytes for command types+ 
   1 byte for the size of my data+ 
   16 bytes for my data+
   1 byte for my CRC.

I have a file.txt file which contains an example of data That I want to send:

0xccddeeff0x8899aabb0x445566770x00112233

By using my python file I want to read data from file.txt ( which I already did), then I want add all the rest of field in order to send all the packet for the uart.

import string
import serial
import time
from array import array

#Plaintxt.txt File
with open('C:\\Users\\user\\Win_My_Scripts\\test.txt') as f:
    content = f.readlines()
#serial port   
ser = serial.Serial(
                    port='COM4',\
                    baudrate=230400,\
                    parity=serial.PARITY_NONE,\
                    stopbits=serial.STOPBITS_ONE,\
                    bytesize=serial.EIGHTBITS,\
                    timeout=0)  
#enter inputs plaintext & key 
print ('Plaintext=')
SOF= '0x124'
ENCRYPT_PLAINTEXT= '0x7772'
SEND_CYPHERTEXT  ='0x7773'
SIZE_OF_FRAME= '0x10'
CRC8= '0x00'
for a in range (0,4):
    line_array=content[a]
    plaintxt_16b=line_array[0:16]
    input_plaintext= SOF+ENCRYPT_PLAINTEXT+SIZE_OF_FRAME+plaintxt_16b+CRC8

    print(plaintxt_16b)

    ser.write (input_plaintext.encode())


    time.sleep(0.4)
#closing the serial port
ser.close()

So my questions are: 1/ How to concat those variables in order to have such packet?

     0x1240x77720x100xccddeeff0x8899aabb0x445566770x001122330x00

2/ My UART then will read that packet from cmd.exe, do you thik that is the best solution to send data from python to UART? I would be very grateful if you have any other proposition?

Thanks in advance.


Solution

  • struct.pack is what you want. It packs data similar to a C structure. Your example has two 16-bit values, a byte length, four 32-bit values, and an 8-bit CRC. Given something like the following:

    SOF = 0x124
    CMD = 0x7772
    data = [0xccddeeff,0x8899aabb,0x44556677,0x00112233]
    CRC8 = 0
    

    This will pack it little-endian (send the lowest byte of the multi-byte integers first), or big-endian. hexlify is just for display so you can see the hexadecimal values of the bytes in the order generated.

    import struct
    from binascii import hexlify
    packet = struct.pack('<HHBLLLLB',SOF,CMD,4*len(data),data[0],data[1],data[2],data[3],CRC8)
    print(hexlify(packet))
    packet = struct.pack('>HHBLLLLB',SOF,CMD,4*len(data),data[0],data[1],data[2],data[3],CRC8)
    print(hexlify(packet))
    

    Output:

    b'2401727710ffeeddccbbaa9988776655443322110000'
    b'0124777210ccddeeff8899aabb445566770011223300'