adafruit / circuitpython

CircuitPython - a Python implementation for teaching coding with microcontrollers
https://circuitpython.org
Other
4.1k stars 1.22k forks source link

circuit python 8.2.9 SSL : (-8576, 'MBEDTLS_ERR_X509_INVALID_FORMAT') #8799

Open FranckyFroggy opened 9 months ago

FranckyFroggy commented 9 months ago

Erreur lors de l'envoi des données: (-8576, 'MBEDTLS_ERR_X509_INVALID_FORMAT')

This is the type of error i get with my program in circuitpython (8.2.9) using PI Pico W and SSL. SSL is used to secure communication between Pico W and a Flask server running on a Raspberry pi 4.

The certificate looks valid (no weird caracter), was put at the root of the pico W and was generated using this command : openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days 365 -nodes. I don't undertsand what's wrong with the format...

The code is as follows :

# Connexion au réseau WiFi en utilisant les variables d'environnement du fichier settings.toml
wifi.radio.connect(os.getenv('CIRCUITPY_WIFI_SSID'), os.getenv('CIRCUITPY_WIFI_PASSWORD'))
print("Connected to WiFi")

# Création d'une session de requête avec SSL context
ssl_context = ssl.create_default_context()
# Charger le certificat auto-signé
ssl_context.load_verify_locations('cert.pem')
# Création d'une session de requête en utilisant le pool de socket
pool = socketpool.SocketPool(wifi.radio)
http_session = requests.Session(pool, ssl_context)
# URL de l'API REST
url = 'https://*.*.*.*:*/insert_measurements' # i put stars bu ip is correct
....

# Envoi des données à l'API REST via une requête POST
    try:
        response = http_session.post(url, json=data)
        print("Données envoyées avec succès, réponse:", response.json())
    except Exception as e:
        print("Erreur lors de l'envoi des données:", e)

The error I get comes at this point.

Any idea ?

The program does eveything but could not send the data to Flask.

Hope someone can help me find what's wrong here ...

FranckyFroggy commented 9 months ago

it seems this let me pass to next step :

# Charger le certificat auto-signé
with open("cert.pem", "r") as cert_file:
    cert_data = cert_file.read()
ssl_context.load_verify_locations(cadata=cert_data)

but now i got this message :
Données JSON à envoyer : {'eCO2': 400}
Type d'erreur: RuntimeError
Message d'erreur: Sending request failed
with this 

 print("Données JSON à envoyer :", data)
    # Envoi des données à l'API REST via une requête POST
    try:
        response = http_session.post(url, json=data)
        print("Données envoyées avec succès, réponse:", response.json())
    except Exception as e:
        print("Type d'erreur:", type(e).__name__)
        print("Message d'erreur:", e)

    time.sleep(60)

and i really don't understand...

Hope someone could help. I'm really out of idea! thanks

anecdata commented 9 months ago

(edited code formatting, hope you don't mind)

Do you get Sending request failed consistently? If not, some retrying could help, or skip until the next loop.

You may want to use the traceback module to get the full exception trace, with the lines in the library where errors occur, something like:

import traceback

# ...

    try:
        # some stuff ...
    except Exception as ex:
        traceback.print_exception(ex, ex, ex.__traceback__)
FranckyFroggy commented 9 months ago

Thank you Anecdata ! Yes consistently. I thought of a timeout issue or something...

Pico work i can connect to network and send ping to google for exemple. It seems i have issue with this : response = http_session.post(url, json=data) in ssl context (https) I simplified the data check the format of the data. I will try your proposal. If I can't see clearer i will go to http to see if it works.

Thanks again

FranckyFroggy commented 9 months ago

here is the result of the traceback :

Connected to WiFi Type de temperature: <class 'float'> Température: 28.8 C Type de co2eq: <class 'int'> CO2eq: 400 ppm, TVOC: 0 ppb H2: 13815, Ethanol: 19668 Données JSON à envoyer : {'eCO2': 400} Type d'erreur: RuntimeError Message d'erreur: Sending request failed Traceback (appels les plus récents en dernier) : Fichier "adafruit_requests.py", ligne 515, dans _get_socket OSError: (-9984, 'MBEDTLS_ERR_X509_CERT_VERIFY_FAILED')

L'exception précédente est la cause directe de l'exception suivante:

Traceback (appels les plus récents en dernier) : Fichier "", ligne 97, dans Fichier "adafruit_requests.py", ligne 736, dans post Fichier "adafruit_requests.py", ligne 671, dans request Fichier "adafruit_requests.py", ligne 496, dans _get_socket RuntimeError: Sending request failed

Here we clearly have a certification verification issue...