From 7b4b208c8579ede963f2c4ecd2543ca0900e2210 Mon Sep 17 00:00:00 2001 From: Mark Leary Date: Wed, 15 Dec 2021 10:43:19 -0500 Subject: [PATCH] Retry when DHT temp sensor read fails --- octoprint_enclosure/getDHTTemp.py | 34 +++++++++++++++++++++++-------- 1 file changed, 26 insertions(+), 8 deletions(-) diff --git a/octoprint_enclosure/getDHTTemp.py b/octoprint_enclosure/getDHTTemp.py index cb9bfef..e898977 100644 --- a/octoprint_enclosure/getDHTTemp.py +++ b/octoprint_enclosure/getDHTTemp.py @@ -1,9 +1,10 @@ import sys +import time import adafruit_dht # Parse command line parameters. -sensor_args = { +sensor_args = { '11': adafruit_dht.DHT11, '22': adafruit_dht.DHT22, '2302': adafruit_dht.DHT22 @@ -16,12 +17,29 @@ sys.exit(1) dht_dev = sensor(pin) -humidity = dht_dev.humidity -temperature = dht_dev.temperature -if humidity is not None and temperature is not None: - print('{0:0.1f} | {1:0.1f}'.format(temperature, humidity)) -else: - print('-1 | -1') +# DHT sensor read fails quite often, causing enclosure plugin to report value of 0. +# If this happens, retry as suggested in the adafruit_dht docs. +max_retries = 3 +retry_count = 0 +while retry_count <= max_retries: + try: + humidity = dht_dev.humidity + temperature = dht_dev.temperature + + if humidity is not None and temperature is not None: + print('{0:0.1f} | {1:0.1f}'.format(temperature, humidity)) + sys.exit(1) + except RuntimeError as e: + time.sleep(2) + retry_count += 1 + continue + except Exception as e: + dht_dev.exit() + raise e + + time.sleep(1) + retry_count += 1 -sys.exit(1) +print('-1 | -1') +sys.exit(1) \ No newline at end of file