import config import logging import mqtt 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 mqtt_inst = mqtt.mqtt_client(config.APP_NAME, config.MQTT_SERVER, username=config.MQTT_USER, password=config.MQTT_PASS) dht_meaner = meaner() bmp_meaner = meaner() def send_data_to_mqtt(data): for key in data: topic = config.MQTT_TOPIC + "/" + key logger.info("Sending Ambient Information to mqtt %s=%s", topic, str(data[key])) mqtt_inst.send(topic, data[key]) 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)