Search code examples
pythonpython-3.xbytepyserial

Python: How can I concatenate in a bytearray as I do with strings?


I would like to get part of a bytearray from a string or int but Python gives me an error.

I tried this calling sendfallblatt.self(1,02) as those code are selected in GUI with a combolist of texts linked to numbers.

    sendfallblatt(fallblattadresse, fallblattcode):

        # <BREAK> FF <COMMAND> <ADDR> < VALUE> 

        ComPort = serial.Serial('COM5')                 # open COM5
        ComPort.baudrate = 19200                # set Baud rate to 9600
        ComPort.bytesize = 8                    # Number of data bits = 8
        ComPort.parity   = 'N'                  # No parity
        ComPort.stopbits = 1                    # Number of Stop bits = 1
        
        data = bytearray(b'\xff\xc0\x0' + str(fallblattadresse) + '\x' + str(fallblattcode))
        print(data)
        
        ComPort.send_break(0.06)
        ComPort.write(data)
        ComPort.close()

And I was expecting to get :

data = bytearray(b'\xff\xc0\x01\x02')

fallblattadresse are from 0 to 7 and fallblattcode are from 0 to 61 so I know I will be having à problem after 9 but I will be solving that later...

Thanks for your help as I'm not finding anything useful on the internet and I'm probably missing some basic knowledge about bytes handling.


Solution

  • You're mixing up the representation of a byte array (which uses \x to show hex codes) and the actual byte values. You don't get a byte array by concatenating the string representations. You can use the bytes() function to create a byte array from a sequence of numeric byte values.

    fallblattadresse, fallblattcode = 1, 2
    data = bytearray(b'\xff\xc0' + bytes((fallblattadresse, fallblattcode)))
    print(data)
    

    prints

    bytearray(b'\xff\xc0\x01\x02')
    

    Unless you need to modify data after the concatenation, you don't need to convert it to a bytearray.