Search code examples
python-3.xcharacter-encodinghexesp32micropython

how can I test if a line of data is hexadecimal?


I am working with GPS data and usually the GPS chip returns a line like this:

b'$GNGGA,200121.00,5135.19146,N,00523.30483,E,1,05,1.89,-18.7,M,46.2,M,,*55\r\n'

However, sometimes the chip returns "None" values or a string of hexadecimal values like this:

b'\x00\x00\xa6\x13I\x82b\x9a\x82b\xaa\xbab\x82\xb2\xc2b\x8a\xb2R\xba25\n'

I am not sure if this is intentional or not. I have created the following python code:

import machine
import time

mygps=machine.UART(1, baudrate=9600, rx=34, tx=12, timeout =10)
msg = mygps.readline()
index = 0
while index < 3:
    msg = mygps.readline()
    print(msg)
    if msg is not None:
        print(msg.decode('utf-8'))
        time.sleep(1)
        index +=1

I want the code to skip the hexadecimal lines returned by the GPS chip. My code deals with the None issue by means of the "is not none" conditional statement, but it does not seem to be able to handle the hexadecimal line that is returned by the GPS chip. Whenever the GPS chip returns a line of hex, it fails in the logical test "if message is not None" or the line right thereafter "print(msg.decode('utf-8'))"

The error only says: UnicodeError.

For me there are two possible solutions: Either make the python code able to deal with the line of Hex or do a logical test and skip both the None and Hex Lines. Both solutions will work for me but I don't have a clue how to solve it.

Probably someone who is acquainted with encoding decoding and hex can help me deal with this issue. Note that preferably python3/micropython native libraries are used to solve this as I am running the code on a very small microcontroller (ESP32)


Solution

  • All you need to do is wrap the call to print() in a try-except block:

    while index < 3:
        msg = mygps.readline()
        print(msg)
        if msg is not None:
            try:
                print(msg.decode('utf-8'))
            except UnicodeError:
                pass
            time.sleep(1)
            index += 1