diff --git a/MH-Z19/get_data.py b/MH-Z19/get_data.py index b43fb86..c979b6e 100644 --- a/MH-Z19/get_data.py +++ b/MH-Z19/get_data.py @@ -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() diff --git a/html/sensors.html b/html/sensors.html index dc17c64..945bc56 100755 --- a/html/sensors.html +++ b/html/sensors.html @@ -299,7 +299,15 @@ function getMHZ19_values(){ tableBody.innerHTML = ""; $("#loading_mhz19").hide(); - if (response.CO2 !== undefined) { + if (response.error) { + $("#data-table-body_mhz19").append(` + + + ⚠ ${response.error} + + + `); + } else if (response.CO2 !== undefined) { $("#data-table-body_mhz19").append(` CO2 @@ -311,6 +319,14 @@ function getMHZ19_values(){ error: function(xhr, status, error) { console.error('AJAX request failed:', status, error); $("#loading_mhz19").hide(); + const tableBody = document.getElementById("data-table-body_mhz19"); + tableBody.innerHTML = ` + + + ⚠ Erreur de communication avec le capteur + + + `; } }); }