Publishs ambient information to mqtt server
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ambient_info.py 2.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. import config
  2. import logging
  3. import mqtt
  4. import paho.mqtt.client as paho
  5. import socket
  6. import report
  7. import time
  8. from rpi_envsens.dht import dht_22
  9. from rpi_envsens.bmp import bmp_180
  10. try:
  11. from config import APP_NAME as ROOT_LOGGER_NAME
  12. except ImportError:
  13. ROOT_LOGGER_NAME = 'root'
  14. logger = logging.getLogger(ROOT_LOGGER_NAME).getChild('main')
  15. class meaner(dict):
  16. def __init__(self):
  17. super().__init__(self)
  18. self.stop_adding = False
  19. self.start_time = time.time()
  20. def add_data(self, **kwargs):
  21. while self.stop_adding:
  22. time.sleep(0.1)
  23. for key in kwargs:
  24. if key not in self:
  25. self[key] = kwargs[key]
  26. self['__' + key + '_n__'] = 1
  27. else:
  28. self[key] += kwargs[key]
  29. self['__' + key + '_n__'] += 1
  30. def pop(self):
  31. self.stop_adding = True
  32. rv = {}
  33. for key in self:
  34. if not key.startswith('__'):
  35. rv[key] = self[key] / self['__' + key + '_n__']
  36. self.clear()
  37. self.start_time = time.time()
  38. self.stop_adding = False
  39. return rv
  40. def meaning_time(self):
  41. return time.time() - self.start_time
  42. mqtt_inst = mqtt.mqtt_client(config.APP_NAME, config.MQTT_SERVER, username=config.MQTT_USER, password=config.MQTT_PASS)
  43. dht_meaner = meaner()
  44. bmp_meaner = meaner()
  45. def send_data_to_mqtt(data):
  46. for key in data:
  47. topic = config.MQTT_TOPIC + "/" + key
  48. logger.info("Sending Ambient Information to mqtt %s=%s", topic, str(data[key]))
  49. mqtt_inst.send(topic, data[key])
  50. def dht_callback(**data):
  51. dht_meaner.add_data(**data)
  52. if dht_meaner.meaning_time() > 2 * 60:
  53. sd = dht_meaner.pop()
  54. del (sd["time"])
  55. send_data_to_mqtt(sd)
  56. def bmp_callback(**data):
  57. bmp_meaner.add_data(**data)
  58. if bmp_meaner.meaning_time() > 2 * 30:
  59. sd = bmp_meaner.pop()
  60. del (sd["time"])
  61. del (sd["temperature"])
  62. send_data_to_mqtt(sd)
  63. if __name__ == '__main__':
  64. report.appLoggingConfigure(config.__BASEPATH__, config.LOGTARGET, ((config.APP_NAME, config.LOGLVL), ),
  65. fmt=config.formatter, host=config.LOGHOST, port=config.LOGPORT)
  66. #
  67. # Initialise data collectors
  68. d = dht_22(config.DHT_22_PORT, dht_callback)
  69. b = bmp_180(bmp_callback)
  70. while True:
  71. time.sleep(1)