fix(mhz19): gestion d'erreurs JSON pour le capteur CO2

Le script get_data.py retourne maintenant toujours du JSON, meme en cas
d'erreur (port serie, absence de donnees). Cote web, les erreurs sont
affichees proprement dans la carte capteur.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
PaulVua
2026-02-17 11:08:36 +01:00
parent 30bc04b89e
commit 8106af624f
2 changed files with 47 additions and 36 deletions

View File

@@ -12,47 +12,42 @@ import time
parameter = sys.argv[1:]
port = '/dev/' + parameter[0]
ser = serial.Serial(
port=port,
baudrate=9600,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS,
timeout=1
)
READ_CO2_COMMAND = b'\xFF\x01\x86\x00\x00\x00\x00\x00\x79'
def read_co2():
ser.write(READ_CO2_COMMAND)
time.sleep(2)
response = ser.read(9)
if len(response) < 9:
print("Error: No data or incomplete data received.")
return None
if response[0] == 0xFF:
co2_concentration = response[2] * 256 + response[3]
return co2_concentration
else:
print("Error reading data from sensor.")
return None
def main():
try:
co2 = read_co2()
if co2 is not None:
data = {"CO2": co2}
json_data = json.dumps(data)
print(json_data)
ser = serial.Serial(
port=port,
baudrate=9600,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS,
timeout=1
)
except serial.SerialException as e:
print(json.dumps({"error": f"Serial port error: {e}"}))
return
READ_CO2_COMMAND = b'\xFF\x01\x86\x00\x00\x00\x00\x00\x79'
try:
ser.write(READ_CO2_COMMAND)
time.sleep(2)
response = ser.read(9)
if len(response) < 9:
print(json.dumps({"error": "No data or incomplete data received from sensor"}))
return
if response[0] == 0xFF:
co2_concentration = response[2] * 256 + response[3]
print(json.dumps({"CO2": co2_concentration}))
else:
print("Failed to get CO2 data.")
except KeyboardInterrupt:
print("Program terminated.")
print(json.dumps({"error": "Invalid response from sensor"}))
except Exception as e:
print(json.dumps({"error": str(e)}))
finally:
ser.close()
if __name__ == '__main__':
main()
read_co2()