简体   繁体   中英

Hex string notation in C# conversion to Python

I am writing a code to retrieve data from a physiological monitor through a bluetooth to serial port in Python. I need to send a Hex code to the monitor in order to receive the data. I have successfully connected to the port but I'm having trouble sending the hex code. The hex string was given to me but it is from C# and I don't know whether it needs to be converted so that Python can read it. When I execute the code below my error message states:

TypeError: fromhex() takes exactly one argument (61 given)

This is the string in C notation

{0x7E,0x00,0x3A,0x00,0x00,0x00,0x00,0x80,0xDE,0xFB,0x2C,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,#0x00,0x09,0x00,0x00,0x00,0x00,0xFF,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x05,0x00,0x0C,0x00,0x00,0x00,0x00,0x00,0x04,0x05,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xE2,0x7E}

below is my program in Python3

import serial

ser = serial.Serial(
    port='/dev/cu.PARANISERIAL-GenericSer',
    baudrate=9600,
    timeout= 10,
    parity=serial.PARITY_NONE,
    stopbits=serial.STOPBITS_ONE,
    bytesize=serial.EIGHTBITS
)

message_bytes = bytes.fromhex(0x7E0x00/0x3A/0x00/0x00/0x00/0x00/0x80/0xDE/0xFB/0x2C/0x00/0x00/0x00/0x00/0x00/0x00/0x00/0x00/0x00/0x09/0x00/0x00/0x00/0x00/0xFF/0x00/0x00/0x00/0x00/0x00/0x00/0x00/0x00/0x00/0x00/0x00/0x00/0x00/0x00/0x00/0x01/0x05/0x00/0x0C/0x00/0x00/0x00/0x00/0x00/0x04/0x05/0x00/0x00/0x00/0x00/0x00/0x00/0x00/0xE2/0x7E)

ser.write(message_bytes)

print (ser.is_open)  # True for opened
if ser.is_open:
    while True:
            data = ser.read(10)
            print(data)
            print(str(data.decode()))
    else:
        print('no data')
        time.sleep(1)
else:
    print('z1serial not open')
s = ser.read(100)
print(str(s.decode()))
ser.close()
print(ser.isOpen())

Any guidance would be greatly appreciated. Thank you

bytes.fromhex will convert the string if all the non-hex characters are removed:

>> h = '0x7E,0x00,0x3A,0x00,0x00,0x00,0x00,0x80,0xDE,0xFB,0x2C,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,#0x00,0x09,0x00,0x00,0x00,0x00,0xFF,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x05,0x00,0x0C,0x00,0x00,0x00,0x00,0x00,0x04,0x05,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xE2,0x7E'

>>> bytes.fromhex(h.replace('0x', '').replace(',', '').replace('#', ''))
b'~\x00:\x00\x00\x00\x00\x80\xde\xfb,\x00\x00\x00\x00\x00\x00\x00\x00\x00\t\x00\x00\x00\x00\xff\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x05\x00\x0c\x00\x00\x00\x00\x00\x04\x05\x00\x00\x00\x00\x00\x00\x00\xe2~'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM