dht22mqtt.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. #!/usr/bin/python3
  2. from datetime import datetime
  3. import time
  4. import os
  5. import statistics
  6. import csv
  7. import adafruit_dht
  8. # import RPi.GPIO as GPIO
  9. from gpiomapping import gpiomapping
  10. import paho.mqtt.client as mqtt
  11. # Begin
  12. dht22mqtt_start_ts = datetime.now()
  13. ###############
  14. # MQTT Params
  15. ###############
  16. mqtt_topic = os.getenv('topic', 'zigbee2mqtt/')
  17. mqtt_device_id = os.getenv('device_id', 'dht22')
  18. mqtt_brokeraddr = os.getenv('broker', '192.168.1.10')
  19. if not mqtt_topic.endswith('/'):
  20. mqtt_topic = mqtt_topic + "/"
  21. mqtt_topic = mqtt_topic + mqtt_device_id + '/'
  22. ###############
  23. # GPIO params
  24. ###############
  25. # TODO check if we can use the GPIO test https://github.com/kgbplus/gpiotest to autodetect pin
  26. # Problems with multiple sensors on the same device
  27. dht22mqtt_refresh = int(os.getenv('poll', '2'))
  28. dht22mqtt_pin = int(os.getenv('pin', '4'))
  29. dht22mqtt_device_type = str(os.getenv('device_type', 'dht22')).lower()
  30. dht22mqtt_temp_unit = os.getenv('unit', 'C')
  31. ###############
  32. # MQTT & Logging params
  33. ###############
  34. dht22mqtt_mqtt_chatter = str(os.getenv('mqtt_chatter', 'essential|ha|full')).lower()
  35. dht22mqtt_logging_mode = str(os.getenv('logging', 'None')).lower()
  36. dht22mqtt_sensor_tally = dict()
  37. ###############
  38. # Filtering & Sampling Params
  39. ###############
  40. dht22mqtt_filtering_enabled = str(os.getenv('filtering', 'enabled')).lower()
  41. dht22_temp_stack = []
  42. dht22_temp_stack_errors = 0
  43. dht22_hum_stack = []
  44. dht22_hum_stack_errors = 0
  45. dht22_stack_size = 10
  46. dht22_std_deviation = 3
  47. dht22_error_count_stack_flush = 3
  48. ###############
  49. # Logging functions
  50. ###############
  51. def log2file(filename, params):
  52. if('log2file' in dht22mqtt_logging_mode):
  53. ts_filename = dht22mqtt_start_ts.strftime('%Y-%m-%dT%H-%M-%SZ')+'_'+filename+".csv"
  54. with open("/log/"+ts_filename, "a+") as file:
  55. w = csv.DictWriter(file, delimiter=',', lineterminator='\n', fieldnames=params.keys())
  56. if file.tell() == 0:
  57. w.writeheader()
  58. w.writerow(params)
  59. def log2stdout(timestamp, msg):
  60. if('log2stdout' in dht22mqtt_logging_mode):
  61. print(datetime.fromtimestamp(timestamp).strftime('%Y-%m-%dT%H:%M:%SZ'), str(msg))
  62. ###############
  63. # Polling functions
  64. ###############
  65. def getTemperatureJitter(temperature):
  66. return getTemperature(temperature-0.3), getTemperature(temperature+0.3)
  67. def getTemperature(temperature):
  68. if(dht22mqtt_temp_unit == 'F'):
  69. temperature = temperature * (9 / 5) + 32
  70. return temperature
  71. def getHumidity(humidity):
  72. return humidity
  73. ###############
  74. # Processing function
  75. ###############
  76. def processSensorValue(stack, error, value, value_type):
  77. # flush stack on accumulation of errors
  78. if(error >= dht22_error_count_stack_flush):
  79. stack = []
  80. error = 0
  81. # init stack
  82. if(len(stack) <= dht22_error_count_stack_flush):
  83. if(value not in stack):
  84. stack.append(value)
  85. # use jitter for bootstrap temperature stack
  86. if(value_type == 'temperature'):
  87. low, high = getTemperatureJitter(value)
  88. stack.append(low)
  89. stack.append(high)
  90. return stack, error, None
  91. # get statistics
  92. std = statistics.pstdev(stack)
  93. mean = statistics.mean(stack)
  94. # compute if outlier or not
  95. if(mean-std*dht22_std_deviation < value < mean+std*dht22_std_deviation):
  96. outlier = False
  97. if(value not in stack):
  98. stack.append(value)
  99. error = 0
  100. else:
  101. outlier = True
  102. error += 1
  103. # remove last element from stack
  104. if(len(stack) > 10):
  105. stack.pop(0)
  106. return stack, error, outlier
  107. ###############
  108. # MQTT update functions
  109. ###############
  110. def updateEssentialMqtt(temperature, humidity, detected):
  111. if('essential' in dht22mqtt_mqtt_chatter):
  112. if(detected == 'accurate'):
  113. payload = '{ "temperature": '+str(temperature)+', "humidity": '+str(humidity)+' }'
  114. client.publish(mqtt_topic + 'value', payload, qos=1, retain=True)
  115. client.publish(mqtt_topic + "detected", str(detected), qos=1, retain=True)
  116. elif(detected == 'bypass'):
  117. payload = '{ "temperature": '+str(temperature)+', "humidity": '+str(humidity)+' }'
  118. client.publish(mqtt_topic + 'value', payload, qos=1, retain=True)
  119. client.publish(mqtt_topic + "detected", str(detected), qos=1, retain=True)
  120. else:
  121. client.publish(mqtt_topic + "detected", str(detected), qos=1, retain=True)
  122. client.publish(mqtt_topic + "updated", str(datetime.now()), qos=1, retain=True)
  123. def registerWithHomeAssitant():
  124. if('ha' in dht22mqtt_mqtt_chatter):
  125. ha_temperature_config = '{"device_class": "temperature",' + \
  126. ' "name": "'+mqtt_device_id+'_temperature",' + \
  127. ' "state_topic": "'+mqtt_topic+'value",' + \
  128. ' "unit_of_measurement": "°'+dht22mqtt_temp_unit+'",' + \
  129. ' "value_template": "{{ value_json.temperature}}" }'
  130. ha_humidity_config = '{"device_class": "humidity",' + \
  131. ' "name": "'+mqtt_device_id+'_humidity",' + \
  132. ' "state_topic": "'+mqtt_topic+'value",' + \
  133. ' "unit_of_measurement": "%",' + \
  134. ' "value_template": "{{ value_json.humidity}}" }'
  135. client.publish('homeassistant/sensor/'+mqtt_device_id+'Temperature/config', ha_temperature_config, qos=1, retain=True)
  136. client.publish('homeassistant/sensor/'+mqtt_device_id+'Humidity/config', ha_humidity_config, qos=1, retain=True)
  137. log2stdout(datetime.now().timestamp(), 'Registering sensor with home assistant success...')
  138. def updateFullSysInternalsMqtt(key):
  139. if('full' in dht22mqtt_mqtt_chatter):
  140. client.publish(mqtt_topic + "sys/temperature_stack_size", len(dht22_temp_stack), qos=1, retain=True)
  141. client.publish(mqtt_topic + "sys/temperature_error_count", dht22_temp_stack_errors, qos=1, retain=True)
  142. client.publish(mqtt_topic + "sys/humidity_stack_size", len(dht22_hum_stack), qos=1, retain=True)
  143. client.publish(mqtt_topic + "sys/humidity_error_count", dht22_hum_stack_errors, qos=1, retain=True)
  144. client.publish(mqtt_topic + "updated", str(datetime.now()), qos=1, retain=True)
  145. if key in dht22mqtt_sensor_tally:
  146. dht22mqtt_sensor_tally[key] += 1
  147. else:
  148. dht22mqtt_sensor_tally[key] = 1
  149. client.publish(mqtt_topic + "sys/tally/" + key, dht22mqtt_sensor_tally[key], qos=1, retain=True)
  150. client.publish(mqtt_topic + "updated", str(datetime.now()), qos=1, retain=True)
  151. ###############
  152. # Setup dht22 sensor
  153. ###############
  154. log2stdout(dht22mqtt_start_ts.timestamp(), 'Starting dht22mqtt...')
  155. if(dht22mqtt_device_type == 'dht22' or dht22mqtt_device_type == 'am2302'):
  156. dhtDevice = adafruit_dht.DHT22(gpiomapping[dht22mqtt_pin], use_pulseio=False)
  157. elif(dht22mqtt_device_type == 'dht11'):
  158. dhtDevice = adafruit_dht.DHT11(gpiomapping[dht22mqtt_pin], use_pulseio=False)
  159. else:
  160. log2stdout(datetime.now().timestamp(), 'Unsupported device '+dht22mqtt_device_type+'...')
  161. log2stdout(datetime.now().timestamp(), 'Devices supported by this container are DHT11/DHT22/AM2302')
  162. log2stdout(datetime.now().timestamp(), 'Setup dht22 sensor success...')
  163. ###############
  164. # Setup mqtt client
  165. ###############
  166. if('essential' in dht22mqtt_mqtt_chatter):
  167. client = mqtt.Client('DHT22', clean_session=True, userdata=None)
  168. # set last will for an ungraceful exit
  169. client.will_set(mqtt_topic + "state", "OFFLINE", qos=1, retain=True)
  170. # keep alive for 60 times the refresh rate
  171. client.connect(mqtt_brokeraddr, keepalive=dht22mqtt_refresh*60)
  172. client.loop_start()
  173. client.publish(mqtt_topic + "type", "sensor", qos=1, retain=True)
  174. client.publish(mqtt_topic + "device", "dht22", qos=1, retain=True)
  175. if('full' in dht22mqtt_mqtt_chatter):
  176. client.publish(mqtt_topic + "env/pin", dht22mqtt_pin, qos=1, retain=True)
  177. client.publish(mqtt_topic + "env/brokeraddr", mqtt_brokeraddr, qos=1, retain=True)
  178. client.publish(mqtt_topic + "env/refresh", dht22mqtt_refresh, qos=1, retain=True)
  179. client.publish(mqtt_topic + "env/logging", dht22mqtt_logging_mode, qos=1, retain=True)
  180. client.publish(mqtt_topic + "env/mqtt_chatter", dht22mqtt_mqtt_chatter, qos=1, retain=True)
  181. client.publish(mqtt_topic + "sys/dht22_stack_size", dht22_stack_size, qos=1, retain=True)
  182. client.publish(mqtt_topic + "sys/dht22_std_deviation", dht22_std_deviation, qos=1, retain=True)
  183. client.publish(mqtt_topic + "sys/dht22_error_count_stack_flush", dht22_error_count_stack_flush, qos=1, retain=True)
  184. client.publish(mqtt_topic + "updated", str(datetime.now()), qos=1, retain=True)
  185. log2stdout(datetime.now().timestamp(), 'Setup mqtt client success...')
  186. client.publish(mqtt_topic + "state", "ONLINE", qos=1, retain=True)
  187. registerWithHomeAssitant()
  188. log2stdout(datetime.now().timestamp(), 'Begin capture...')
  189. while True:
  190. try:
  191. dht22_ts = datetime.now().timestamp()
  192. temperature = getTemperature(dhtDevice.temperature)
  193. humidity = getHumidity(dhtDevice.humidity)
  194. temp_data = processSensorValue(dht22_temp_stack,
  195. dht22_temp_stack_errors,
  196. temperature,
  197. 'temperature')
  198. dht22_temp_stack = temp_data[0]
  199. dht22_temp_stack_errors = temp_data[1]
  200. temperature_outlier = temp_data[2]
  201. hum_data = processSensorValue(dht22_hum_stack,
  202. dht22_hum_stack_errors,
  203. humidity,
  204. 'humidity')
  205. dht22_hum_stack = hum_data[0]
  206. dht22_hum_stack_errors = hum_data[1]
  207. humidity_outlier = hum_data[2]
  208. # Since the intuition here is that errors in humidity and temperature readings
  209. # are heavily correlated, we can skip mqtt if we detect either.
  210. detected = ''
  211. if(temperature_outlier is False and humidity_outlier is False):
  212. detected = 'accurate'
  213. else:
  214. detected = 'outlier'
  215. # Check if filtering enabled
  216. if('enabled' in dht22mqtt_filtering_enabled):
  217. updateEssentialMqtt(temperature, humidity, detected)
  218. else:
  219. updateEssentialMqtt(temperature, humidity, 'bypass')
  220. updateFullSysInternalsMqtt(detected)
  221. data = {'timestamp': dht22_ts,
  222. 'temperature': temperature,
  223. 'humidity': humidity,
  224. 'temperature_outlier': temperature_outlier,
  225. 'humidity_outlier': humidity_outlier}
  226. log2stdout(dht22_ts, data)
  227. log2file('recording', data)
  228. time.sleep(dht22mqtt_refresh)
  229. except RuntimeError as error:
  230. # DHT22 throws errors often. Keep reading.
  231. detected = 'error'
  232. updateEssentialMqtt(None, None, detected)
  233. updateFullSysInternalsMqtt(error.args[0])
  234. data = {'timestamp': dht22_ts, 'error_type': error.args[0]}
  235. log2stdout(dht22_ts, data)
  236. log2file('error', data)
  237. time.sleep(dht22mqtt_refresh)
  238. continue
  239. except Exception as error:
  240. if('essential' in dht22mqtt_mqtt_chatter):
  241. client.disconnect()
  242. dhtDevice.exit()
  243. raise error
  244. # Graceful exit
  245. if('essential' in dht22mqtt_mqtt_chatter):
  246. client.publish(mqtt_topic + "state", "OFFLINE", qos=2, retain=True)
  247. client.publish(mqtt_topic + "updated", str(datetime.now()), qos=2, retain=True)
  248. client.disconnect()
  249. dhtDevice.exit()