0

I have a somewhat similar question here that I can't solve. In another instance of my code, I face similar encoding errors. Do assist!

My code:

port = serial.Serial("/dev/ttyUSB0", baudrate=9600, timeout=10,     bytesize=8)
f_w = open('/home/ryan/python_serial_output.txt','r+')
f_o = open('/home/ryan/python_serial_parse.txt','w')

port.send_break()
sys_reply = port.read(100000)
sys_reply_str = sys_reply.decode('utf-8')
print(sys_reply_str)
sys_reply_str_haha = sys_reply_str.replace("\r","")
sys_reply_str_haha = sys_reply_str_haha.replace("\n","")
i = list(sys_reply_str_haha)
if str(i[-1]) == '>':
    ip = 'CR1'
    ip_en = ip.encode('utf-8')
    port.write(ip_en)
    read_syscheck = port.read(100000)
    read_syscheck_str = read_syscheck.decode('utf-8')
    print(read_syscheck_str)

Yes, it's inefficient, but I'm writing it step by step to avoid errors as a start.

With this code, this is the result I get.

myname@Toshiba:~$ python3 serial_test.py 

Explorer (c) 2009
All rights reserved.
Firmware Version: 34.11  

>
Traceback (most recent call last):
  File "serial_test.py", line 25, in <module>
    read_syscheck_str = read_syscheck.decode('utf-8')
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xd3 in position 7: invalid continuation byte

It seems I am encoding 'CR1' wrongly, that's why the error has been prompted. CR1 is supposed to reset my sensor to factory default settings, and meant to reply a confirmation of that.

Thank you very much in advance for any assistance.

JosefZ
  • 28,460
  • 5
  • 44
  • 83
Ryan Lee
  • 361
  • 1
  • 3
  • 10
  • Out of curiosity, what does `print(read_syscheck)` after reading the port yield? – AetherUnbound May 26 '17 at 06:03
  • it has the same result as print(read_syscheck_str) – Ryan Lee May 26 '17 at 06:11
  • My apologies, I wasn't thinking straight earlier and did not comment out the decoding line, hence it hit an error. this is the reply from print(read_syscheck_str): b'CR1\r\n\x7f\x7f\xd3\x00\x00\x03\x0c\x82\x00\x00........ I'm on linux so using GTKTerm to talk to the sensor as a guide. This is the output I am expecting. .... All rights reserved. Firmware Version: 34.11 >CR1 [Parameters set to FACTORY defaults] > – Ryan Lee May 26 '17 at 08:44
  • Sorry, I'm new to stack overflow. @AetherUnbound – Ryan Lee May 26 '17 at 17:41

1 Answers1

0

Wrong encoding method.

Correct one was 'cp437'

Unsure why UTF-8 worked after the break, but not after writing a command

Ryan Lee
  • 361
  • 1
  • 3
  • 10