Skip to content

Commit

Permalink
Retry when DHT temp sensor read fails
Browse files Browse the repository at this point in the history
  • Loading branch information
markleary committed Dec 15, 2021
1 parent 2ebcc4f commit 7b4b208
Showing 1 changed file with 26 additions and 8 deletions.
34 changes: 26 additions & 8 deletions octoprint_enclosure/getDHTTemp.py
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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)

0 comments on commit 7b4b208

Please sign in to comment.