I need to send messages to my devices via MQTT. To view messages arriving from devices I have a function that transforms a binary into a string so that I can print the payload on the screen
payStr = 'B4 38 00 3C 61 05 02 56 AC AC 67 B2 FC FA FC 2A 0C 1B 0A 16 0D'
payload = b'\xb48\x00<a\x05\x02V\xac\xacg\xb2\xfc\xfa\xfc*\x0c\x1b\n\x16\r'
def payloadToStr(payload):
pay = ''
for x in payload:
pay += format(x, '02X')
pay += ' '
return pay
payloadToStr(payload)
>> 'B4 38 00 3C 61 05 02 56 AC AC 67 B2 FC FA FC 2A 0C 1B 0A 16 0D'
However, I would like to do it the other way around. By entering as a string I would like to convert to a binary corresponding to the request by MQTT and devices.
I tried to use encode('utf8') and encode('utf16') but without success:
s = 'B438003C61050256ACAC67B2FCFAFC2A0C1B0A160D'
s.encode('utf8')
>> b'B438003C61050256ACAC67B2FCFAFC2A0C1B0A160D'
s.encode('utf16')
>> b'\xff\xfeB\x004\x003\x008\x000\x000\x003\x00C\x006\x001\x000\x005\x000\x002\x005\x006\x00A\x00C\x00A\x00C\x006\x007\x00B\x002\x00F\x00C\x00F\x00A\x00F\x00C\x002\x00A\x000\x00C\x001\x00B\x000\x00A\x001\x006\x000\x00D\x00'
I also tried with struct but this one doesn't allow strings. Could anyone help?