Пример #1
0
 def _log(self,
          file_path,
          data_str,
          e=None,
          put_timestamp=True,
          prefix=None,
          mode='a'):
     if prefix is not None:
         print(data_str)
     if self.isInitialized():
         try:
             fn = Logger.PARTITION + "/" + file_path  # 'logdev.txt'
             with open(fn, mode) as f:
                 if prefix is not None:
                     f.write("%s: " % prefix)
                 if put_timestamp:
                     f.write(_time.now())
                 f.write(data_str)
                 f.write("\r\n")
                 if e is not None:
                     print_exception(e, f)
             sleep(0.2)
         except Exception as e:
             print(repr(e))
Пример #2
0
def readandpublish(timer, uart, uart2, i2c, spi, logger, hpma_pin, pms_pin,
                   publishers, atrpub):
    # Inicia sensores
    sensors = sensorpool.startSensors(uart=uart,
                                      uart2=uart2,
                                      i2c=i2c,
                                      spi=spi,
                                      logger=logger,
                                      hpma_pin=hpma_pin,
                                      pms_pin=pms_pin)
    print('Flujo de aire forzado por %d segundos...' % TAIRF)
    sleep(TAIRF)
    print('Realizando medicion...')
    measures = sensorpool.readsensors(sensors, logger)

    # Apaga sensores de material particulado
    hpma_pin.value(0)
    pms_pin.value(0)

    ## **************** PREPARACIÓN DE PAQUETES DE TELEMETRÍA ****************
    tstp = (time() + TSTAMP) * 1000
    fecha = _time.now()

    print("PM2.5: %.2f %.2f %.2f ug/m3 [H-P-S]" %
          (measures["HPM2_5"], measures["PPM2_5"], measures["SPM2_5"]))
    print("PM10:  %.2f %.2f %.2f ug/m3 [H-P-S]" %
          (measures["HPM10"], measures["PPM10"], measures["SPM10"]))
    print("Temperatura: %.2f ºC" % (measures["Temp"]))
    print("Humedad Rel: %.2f %%" % (measures["HR"]))

    # Finaliza ina219
    sensors["ina219"].stop()
    sensors["ina219"].join()

    simple_tel = {}
    simple_tel["tiempo"] = fecha
    simple_tel["tesp"] = (raw_temperature() - 32) * 0.5555556
    simple_tel["hmok"] = int("hpma115s0" in sensors)
    simple_tel["pmok"] = int("pms7003" in sensors)
    simple_tel["amok"] = int("am2315" in sensors or "am2302" in sensors)
    simple_tel["spok"] = int("sps30" in sensors)

    complete_tel = config.measurements()
    complete_tel["tesp"]["medicion:otro:temperatura"] = (raw_temperature() -
                                                         32) * 0.5555556
    #	complete_tel["tesp"]["tipo"]								= "meteorologia:temperatura:\xbaC"
    complete_tel["tesp"]["fecha:otro:temperatura"] = tstp

    pub_tel = {}
    pub_tel["tesp"] = complete_tel["tesp"]

    if "hpma115s0" in sensors:
        pub_tel["hm2_5"] = complete_tel["hm2_5"]
        pub_tel["hm10"] = complete_tel["hm10"]
        simple_tel["HPM2.5"] = measures["HPM2_5"]
        simple_tel["HPM10"] = measures["HPM10"]
        complete_tel["hm10"]["medicion:contaminante:mp10"] = measures["HPM10"]
        complete_tel["hm10"]["fecha:contaminante:mp10"] = tstp
        complete_tel["hm2_5"]["medicion:contaminante:mp2_5"] = measures[
            "HPM2_5"]
        complete_tel["hm2_5"]["fecha:contaminante:mp2_5"] = tstp

    if "pms7003" in sensors:
        pub_tel["pm2_5"] = complete_tel["pm2_5"]
        pub_tel["pm10"] = complete_tel["pm10"]
        simple_tel["PPM2.5"] = measures["PPM2_5"]
        simple_tel["PPM10"] = measures["PPM10"]
        complete_tel["pm10"]["medicion:contaminante:mp10"] = measures["PPM10"]
        complete_tel["pm10"]["fecha:contaminante:mp10"] = tstp
        complete_tel["pm2_5"]["medicion:contaminante:mp2_5"] = measures[
            "PPM2_5"]
        complete_tel["pm2_5"]["fecha:contaminante:mp2_5"] = tstp

    if "am2315" in sensors or "am2302" in sensors:
        pub_tel["temp"] = complete_tel["temp"]
        pub_tel["hur"] = complete_tel["hur"]
        simple_tel["Temp"] = measures["Temp"]
        simple_tel["HR"] = measures["HR"]
        complete_tel["temp"]["medicion:meteorologia:temperatura"] = measures[
            "Temp"]
        complete_tel["temp"]["fecha:meteorologia:temperatura"] = tstp
        #		complete_tel["temp"]["tipo"]								= "meteorologia:temperatura:\xbaC"
        complete_tel["hur"]["medicion:meteorologia:humedad"] = measures["HR"]
        complete_tel["hur"]["fecha:meteorologia:humedad"] = tstp

    if "sps30" in sensors:
        pub_tel["sm2_5"] = complete_tel["sm2_5"]
        pub_tel["sm10"] = complete_tel["sm10"]
        simple_tel["SPM2_5"] = measures["SPM2_5"]
        simple_tel["SPM10"] = measures["SPM10"]
        complete_tel["sm10"]["medicion:contaminante:mp10"] = measures["SPM10"]
        complete_tel["sm10"]["fecha:contaminante:mp10"] = tstp
        complete_tel["sm2_5"]["medicion:contaminante:mp2_5"] = measures[
            "SPM2_5"]
        complete_tel["sm2_5"]["fecha:contaminante:mp2_5"] = tstp

    if "ina219" in sensors and sensors["ina219"].voltage is not None:
        simple_tel["voltage"] = sensors["ina219"].voltage
        simple_tel["current"] = sensors["ina219"].current
        simple_tel["power"] = sensors["ina219"].power
        complete_tel["voltage"]["medicion:otro:voltaje"] = sensors[
            "ina219"].voltage
        complete_tel["voltage"]["fecha:otro:voltaje"] = tstp
        complete_tel["current"]["medicion:otro:corriente"] = sensors[
            "ina219"].current
        complete_tel["current"]["fecha:otro:corriente"] = tstp
        complete_tel["power"]["medicion:otro:potencia"] = sensors[
            "ina219"].power
        complete_tel["power"]["fecha:otro:potencia"] = tstp
        pub_tel["voltage"] = complete_tel["voltage"]
        pub_tel["current"] = complete_tel["current"]
        pub_tel["power"] = complete_tel["power"]

    simple_tel = {"ts": tstp, "values": simple_tel}

    ## **************** PUBLICACIÓN DE TELEMETRIAS ****************

    for pub in publishers:
        try:
            if pub.format == "simple":
                print("\nPublica simple: %s" % dumps(simple_tel))
                pub.publish(dumps(simple_tel), atrpub)
            elif pub.format == "complete":
                for meas in pub_tel:
                    print("\nPublica completo: %s" % dumps(pub_tel[meas]))
                    pub.publish(dumps(pub_tel[meas]), atrpub)

        except Exception as e:
            print_exception(e)
            print(repr(e))
            logger.debug("Error en la publicación")
            logger.debug(print_exception(e))

    logger.data(LOGDAT, dumps(simple_tel))
Пример #3
0
    def run(self):
        #Activa flag para saber que el hilo se está ejecutando
        self.startSensor()

        while True:
            #Marca tiempo de inicio
            st = time.time()
            while True and not self.isStopping():
                #Inicializa buffers
                ## Buffer de mediciones de voltaje en V.
                self.voltBuff   = []
                ## Buffer de mediciones de corriente en mA.
                self.currBuff   = []
                ## Buffer de mediciones de potencia en mW.
                self.powBuff    = []
                
                for i in range(self.buffLen):

                    if time.time()-st > self.period*self.buffLen + self.maxTimeOffset:
                        #Salta timeout por finalización de tiempo estipulado para muestreo
                        break

                    #Duerme hasta que sea necesario muestrear
                    if time.time()-st <self.period*(i+1):
                        time.sleep(self.period*(i+1)-(time.time()-st))
                    
                    self.startCritical()

                    #Pide recurso I2C
                    self.startI2CCritical()

                    #Vuelve a crear objeto. Al parecer debe hacerse luego de encenderlo.
                    for attempt in range(3):
                        try:
                            ## Objeto INA219 de la librería Adafruit.
                            # self.ina219         = INA219(INA219_.SHUNT_OHMS, INA219_.MAX_EXPECTED_AMPS)
                            # self.ina219.configure(bus_adc = INA219.ADC_64SAMP, shunt_adc = INA219.ADC_64SAMP)
                            self.ina219 = INA219(INA219_.SHUNT_OHMS, I2C(-1, Pin(22), Pin(21)))
                            self.ina219.configure()
                            break
                        except Exception as e:
                            print("Error al crear objeto INA219")
                            time.sleep(0.1)

                    #Inicializa cantidad de intentos realizados
                    attempt = 1

                    while attempt <= self.nattempts:
                        try:
                            #Realiza lectura de corriente, voltaje y potencia
                            self.voltBuff.append(self.ina219.voltage())
                            self.currBuff.append(self.ina219.current())
                            self.powBuff.append(self.ina219.power())
                            break
                        except:
                            print("Error al leer sensor ina219")

                            #Actualiza contador de intentos
                            attempt += 1

                            #Duerme un segundo hasta el siguiente intento
                            time.sleep(1)

                    #Libera recurso I2C
                    self.stopI2CCritical()

                    #Libera control del hilo
                    self.stopCritical()

                    #Muestra por pantalla los valores obbtenidos
                    if len(self.voltBuff)>0 and len(self.currBuff)>0 and len(self.powBuff)>0:
                        print("INA219 %s: Voltaje: %.2f. Corriente: %.2f. Potencia: %.2f"%(_time.now(), self.voltBuff[-1], self.currBuff[-1], self.powBuff[-1]))
                
                #Adquiere control del hilo
                self.startCritical()

                #Actualiza última medición de corriente
                if len(self.currBuff)>0:
                    ## Último valor de corriente extraido de la mediana del último buffer de mediciones de corriente.
                    self.current    = stats.median(list(sorted(self.currBuff)))
                
                #Actualiza última medición de voltaje
                if len(self.voltBuff)>0:
                    ## Último valor de voltaje extraido de la mediana del último buffer de mediciones de voltaje.
                    self.voltage    = stats.median(list(sorted(self.voltBuff)))

                #Actualiza última medición de potencia
                if len(self.powBuff)>0:
                    ## Último valor de potencia extraido de la mediana del último buffer de mediciones de potencia.
                    self.power      = stats.median(list(sorted(self.powBuff)))

                if not self.on_read is None:
                    #Llama callback para procesamiento de los datos
                    self.on_read(self, **self.kwargs)
                
                #Libera control del hilo
                self.stopCritical()

                #Actualiza tiempo inicial
                st = st + self.buffLen*self.period

                #Espera a siguiente período de muestreo
                if(time.time() < st):
                    time.sleep(st-time.time())
            #Avisa que ha terminado de ejecutarse el hilo
            self.endSensor()

            #Espera a que se requiera nuevamente la ejecución del hilo
            self.waitForActivation()