123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293 |
- import config
- import logging
- import paho.mqtt.client as paho
- import socket
- import report
- import time
-
- from rpi_envsens.dht import dht_22
- from rpi_envsens.bmp import bmp_180
-
- try:
- from config import APP_NAME as ROOT_LOGGER_NAME
- except ImportError:
- ROOT_LOGGER_NAME = 'root'
- logger = logging.getLogger(ROOT_LOGGER_NAME).getChild('main')
-
-
- class meaner(dict):
- def __init__(self):
- super().__init__(self)
- self.stop_adding = False
- self.start_time = time.time()
-
- def add_data(self, **kwargs):
- while self.stop_adding:
- time.sleep(0.1)
- for key in kwargs:
- if key not in self:
- self[key] = kwargs[key]
- self['__' + key + '_n__'] = 1
- else:
- self[key] += kwargs[key]
- self['__' + key + '_n__'] += 1
-
- def pop(self):
- self.stop_adding = True
- rv = {}
- for key in self:
- if not key.startswith('__'):
- rv[key] = self[key] / self['__' + key + '_n__']
- self.clear()
- self.start_time = time.time()
- self.stop_adding = False
- return rv
-
- def meaning_time(self):
- return time.time() - self.start_time
-
-
- dht_meaner = meaner()
- bmp_meaner = meaner()
-
- def send_data_to_mqtt(data):
- client = paho.Client("temp_sens")
- client.username_pw_set(config.MQTT_USER, config.MQTT_PASS)
- try:
- client.connect(config.MQTT_SERVER, 1883)
- for key in data:
- topic = config.MQTT_TOPIC + "/" + key
- logger.info("Sending Ambient Information to mqtt %s=%s", topic, str(data[key]))
- client.publish(topic, data[key])
- except (socket.timeout, OSError) as e:
- logger.warning("Erro while sending ambient information")
-
-
- def dht_callback(**data):
- dht_meaner.add_data(**data)
- if dht_meaner.meaning_time() > 2 * 60:
- sd = dht_meaner.pop()
- del (sd["time"])
- send_data_to_mqtt(sd)
-
-
- def bmp_callback(**data):
- bmp_meaner.add_data(**data)
- if bmp_meaner.meaning_time() > 2 * 30:
- sd = bmp_meaner.pop()
- del (sd["time"])
- del (sd["temperature"])
- send_data_to_mqtt(sd)
-
-
- if __name__ == '__main__':
- report.appLoggingConfigure(config.__BASEPATH__, config.LOGTARGET, ((config.APP_NAME, config.LOGLVL), ),
- fmt=config.formatter, host=config.LOGHOST, port=config.LOGPORT)
-
- #
- # Initialise data collectors
- d = dht_22(config.DHT_22_PORT, dht_callback)
- b = bmp_180(bmp_callback)
-
- while True:
- time.sleep(1)
|