Convert hexadecimal string to bytes in Zerynth

I need to pass a hexadecimal string “0A FF CC 10 FE” from a JSON value, process it and forward it to a serial port.

The most popular way of doing it in python using bytes.fromhex("0A FF CC 10 FE") does not work in Zerynth.

Suggest a work around ?

hi @kanishka
According to the docs, the bytes() method can take string as an argument.
Would this work in your project?

Hi @karimhamdy1

Can you share a sample implementation code. I am relatively new to python and finding it difficult implementing it. Below is my function that prints the serial data.

Note: The value field in the JSON contains a string with hexadecimal values in an ASCII format.

Input String: “02 05 FF CC 10 FE”

> def print_sample(client,data):
>     message = data['message']
>     print(message.payload,stream=s0)
>     payLoadSplit=message.payload.split('"')[1::2]
>     print("SerialIn: " + payLoadSplit[1],stream=s0)  #print on debug terminal
>     ????????
>     s2.write(?????)  #Byes to be sent to serial port

??? -> How do I transform string with Hexadecimal values represented in ASCII form and send true hexadecimal values <0x02><0x05><0xFF><0xCC><0x10><0xFE> to serial port

Thank you or the support.

I think this fits your question, we are taking string of hex bytes and converting them to bytes and making a string of bytes so the MCU can send them one by one.

# import the streams module, it is needed to send data around
import streams

# open the default serial port, the output will be visible in the serial console
s1 = streams.serial()  

#for more information

def HexToByte( hexStr ):
    Convert a string hex byte values into a byte string. The Hex Byte values may
    or may not be space separated.
    bytes = []

    hexStr = ''.join( hexStr.split(" ") )

    for i in range(0, len(hexStr), 2):
        bytes.append( chr( int (hexStr[i:i+2], 16 ) ) )

    return ''.join( bytes )

__hexStr1  = "02 05 FF CC 10 FE"
# loop forever
while True:
    #print("Hello Zerynth!")   # print automatically knows where to print!
    buf = HexToByte( __hexStr1 )

To view the serial terminal please use putty or minicom and make sure you switch on the Hex display.

Thank you a lot. It works as expected. :+1: