Publishs ambient information to mqtt server
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

ambient_info.py 2.5KB

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