Exemple #1
0
def measurement():
    try:
        # load settings
        settings = get_settings()
        # read configured sensors from settings.json
        ds18b20Sensors = get_sensors(settings, 0)
        bme680Sensors = get_sensors(settings, 1)
        weightSensors = get_sensors(settings, 2)
        dhtSensors = get_sensors(settings, 3)

        # if bme680 is configured
        if bme680Sensors and len(bme680Sensors) == 1:
            gas_baseline = None
            if initBME680FromMain():
                # bme680 sensor must be burned in before use
                gas_baseline = burn_in_bme680(10)

                # if burning was canceled => exit
                if gas_baseline is None:
                    print("gas_baseline can't be None")

        # dict with all fields and values which will be tranfered to ThingSpeak later
        ts_fields = {}

        # measure every sensor with type 0
        for (sensorIndex, sensor) in enumerate(ds18b20Sensors):
            if 'ts_field' in sensor and 'device_id' in sensor:
                ts_field_ds18b20 = sensor["ts_field"]
                ds18b20_temperature = measure_temperature(sensor["device_id"])
                ts_fields.update({ts_field_ds18b20: ds18b20_temperature})
            else:
                print("DS18b20 missing param: ts_field or device_id")

        # measure BME680 (can only be once) [type 1]
        if bme680Sensors and len(bme680Sensors) == 1 and gas_baseline:
            bme680_values = measure_bme680(gas_baseline, bme680Sensors[0])
            ts_fields.update(bme680_values)

        # disable warnings for HX711
        GPIO.setwarnings(False)
        
        # measure every sensor with type 2 [HX711]
        for (i, sensor) in enumerate(weightSensors):
            weight = measure_weight(sensor)
            ts_fields.update(weight)

        # measure every sensor with type 3 [DHT11/DHT22]
        for (i, sensor) in enumerate(dhtSensors):
            tempAndHum = measure_dht(sensor)
            ts_fields.update(tempAndHum)

        return json.dumps(ts_fields)
           
    except Exception as e:
        print("Measurement: " + str(e))
Exemple #2
0
def start_measurement(measurement_stop):
    try:
        global burn_in_time
        start_time = time.time()

        # load settings
        settings = get_settings()
        ts_channels = settings[
            "ts_channels"]  # ThingSpeak data (ts_channel_id, ts_write_key)
        ts_server_url = settings["ts_server_url"]
        debuglevel = settings["debuglevel"]
        if debuglevel <= 10:
            debug = True  # flag to enable debug mode (HDMI output enabled and no rebooting)
        else:
            debug = False  # flag to enable debug mode (HDMI output enabled and no rebooting)

        wittyPi = settings["wittyPi"]
        offline = settings["offline"]  # flag to enable offline csv storage

        isLowVoltage = getStateFromStorage('isLowVoltage', False)
        if isLowVoltage == True:
            interval = wittyPi["low"]["interval"]
            shutdownAfterTransfer = wittyPi["low"]["shutdownAfterTransfer"]
        else:
            interval = wittyPi["normal"]["interval"]
            shutdownAfterTransfer = wittyPi["normal"]["shutdownAfterTransfer"]

        if debug:
            logger.info("The measurements have started.")

        # with process shared variables
        connectionErrors = Value('i', 0)
        measurementIsRunning = Value('i', 0)

        if interval and not isinstance(interval, int) or interval == 0:
            interval = 0
            logger.info("Stop measurement because interval is null.")
            measurement_stop.set()

        # read configured sensors from settings.json
        ds18b20Sensors = get_sensors(settings, 0)
        bme680Sensors = get_sensors(settings, 1)
        weightSensors = get_sensors(settings, 2)
        dhtSensors = get_sensors(settings, 3)
        tcSensors = get_sensors(settings, 4)
        bme280Sensors = get_sensors(settings, 5)
        pcf8591Sensors = get_sensors(settings, 6)
        ee895Sensors = get_sensors(settings, 7)
        aht10Sensors = get_sensors(settings, 8)
        sht31Sensors = get_sensors(settings, 9)
        hdc1008Sensors = get_sensors(settings, 10)
        bme680Inits = []

        # -- Run Pre Configuration --
        # if bme680 is configured
        for (sensorIndex, bme680Sensor) in enumerate(bme680Sensors):
            bme680Init = {}
            if 'burn_in_time' in bme680Sensor:
                burn_in_time = bme680Sensor["burn_in_time"]
            sensor = initBME680FromMain(bme680Sensor)
            gas_baseline = burn_in_bme680(sensor, burn_in_time)
            bme680Init['sensor'] = sensor
            bme680Init['gas_baseline'] = gas_baseline
            bme680Inits.append(bme680Init)

        # if hx711 is set
        hxInits = []
        for (i, sensor) in enumerate(weightSensors):
            _hx = init_hx711(sensor)
            hxInits.append(_hx)

        # PCF8591
        if pcf8591Sensors and len(pcf8591Sensors) == 1:
            voltage = get_raw_voltage(
                pcf8591Sensors[0]
            )  # initial measurement as first measurement is always wrong

        # -- End Pre Configuration --

        # start at -6 because we want to get 6 values before we can filter some out
        counter = -6
        time_measured = 0
        time_measured_Voltage = 0

        # Main loop which checks every second
        while not measurement_stop.is_set():
            counter += 1
            time_now = time.time()

            for (sensorIndex, sensor) in enumerate(ds18b20Sensors):
                checkIfSensorExistsInArray(sensorIndex)
                if 'device_id' in sensor:
                    read_unfiltered_temperatur_values(sensorIndex, sensor)

            time_measured_Voltage, interval, shutdownAfterTransfer, isLowVoltage = check_wittypi_voltage(
                time_measured_Voltage, wittyPi, pcf8591Sensors, isLowVoltage,
                interval, shutdownAfterTransfer)

            # wait seconds of interval before next check
            # free ThingSpeak account has an upload limit of 15 seconds
            isTimeToMeasure = ((time_now - time_measured >= interval) or
                               (interval == 1)) and counter > 0
            if isTimeToMeasure:
                now = time.strftime("%H:%M", time.localtime(time_now))
                lastMeasurement = time.strftime("%H:%M",
                                                time.localtime(time_measured))
                if time_measured == 0:
                    print("First time measurement. Now: " + str(now))
                else:
                    print("Last measurement was at " + str(lastMeasurement))
                    print("Time over for a new measurement. Time is now: " +
                          str(now))
                time_measured = time.time()

                check_undervoltage('0x7')

                if measurementIsRunning.value == 0:
                    q = Queue()
                    p = Process(target=measure,
                                args=(q, offline, debug, ts_channels,
                                      ts_server_url, filtered_temperature,
                                      ds18b20Sensors, bme680Sensors,
                                      bme680Inits, dhtSensors, aht10Sensors,
                                      sht31Sensors, hdc1008Sensors, tcSensors,
                                      bme280Sensors, pcf8591Sensors,
                                      ee895Sensors, weightSensors, hxInits,
                                      connectionErrors, measurementIsRunning))
                    p.start()
                    p.join()

                else:
                    logger.warning(
                        "Forerun measurement is not finished yet. Consider increasing interval."
                    )

                # stop measurements after uploading once
                if interval == 1:
                    print("Only one measurement was set => stop measurements.")
                    measurement_stop.set()

                    if shutdownAfterTransfer:
                        isMaintenanceActive = getStateFromStorage(
                            'isMaintenanceActive', False)
                        print("Wert isMaintenanceActive: " +
                              str(isMaintenanceActive))
                        while isMaintenanceActive:
                            isMaintenanceActive = getStateFromStorage(
                                'isMaintenanceActive', False)
                            print(
                                "Shutting down was set but Maintenance mode is active, delaying shutdown!"
                            )
                            print("Wert isMaintenanceActive: " +
                                  str(isMaintenanceActive))
                            time.sleep(10)
                        print(
                            "Shutting down was set => Waiting 10seconds and then shutdown."
                        )
                        tblink = threading.Thread(target=blink_led,
                                                  args=(settings["led_pin"],
                                                        0.25))
                        tblink.start()
                        time.sleep(10)
                        shutdown()

            time.sleep(6)  # wait 6 seconds before next measurement check

        end_time = time.time()
        time_taken = end_time - start_time  # time_taken is in seconds
        time_taken_s = float(
            "{0:.2f}".format(time_taken))  # remove microseconds
        print("Measurement-Script runtime was " + str(time_taken_s) +
              " seconds.")

    except Exception as ex:
        logger.exception("Unhandled Exception in start_measurement")
        if not debug:
            time.sleep(10)
            reboot()
def start_measurement(measurement_stop):
    try:
        print("The measurements have started.")
        start_time = time.time()

        # load settings
        settings = get_settings()
        # ThingSpeak data
        channel_id = settings["ts_channel_id"]
        write_key = settings["ts_write_key"]
        interval = settings["interval"]

        if interval and not isinstance(
                interval,
                int) or interval == 0 or not channel_id or not write_key:
            print("ThingSpeak settings are not complete or interval is 0")
            measurement_stop.set()

        # read configured sensors from settings.json
        ds18b20Sensors = get_sensors(settings, 0)
        bme680Sensors = get_sensors(settings, 1)
        weightSensors = get_sensors(settings, 2)
        dhtSensors = get_sensors(settings, 3)

        # if bme680 is configured
        if bme680Sensors and len(bme680Sensors) == 1:
            gas_baseline = None
            if initBME680FromMain():
                # bme680 sensor must be burned in before use
                gas_baseline = burn_in_bme680(30)

                # if burning was canceled => exit
                if gas_baseline is None:
                    print("gas_baseline can't be None")

        # ThingSpeak channel
        channel = thingspeak.Channel(id=channel_id, write_key=write_key)

        # counting connection Errors
        connectionErros = 0

        # start at -6 because we want to get 6 values before we can filter some out
        counter = -6
        while not measurement_stop.is_set():

            # read values from sensors every second
            for (sensorIndex, sensor) in enumerate(ds18b20Sensors):
                checkIfSensorExistsInArray(sensorIndex)
                if 'device_id' in sensor:
                    read_unfiltered_temperatur_values(sensorIndex,
                                                      sensor['device_id'])

            # for testing:
            #try:
            #    weight = measure_weight(weightSensors[0])
            #    print("weight: " + str(list(weight.values())[0]))
            #except IOError:
            #    print "IOError occurred"
            #except TypeError:
            #    print "TypeError occurred"
            #except IndexError:
            #    print "IndexError occurred"

            # wait seconds of interval before next check
            # free ThingSpeak account has an upload limit of 15 seconds
            if counter % interval == 0:
                print("Time over for a new measurement.")

                # filter the values out
                for (sensorIndex, sensor) in enumerate(ds18b20Sensors):
                    filter_temperatur_values(sensorIndex)

                # dict with all fields and values which will be tranfered to ThingSpeak later
                ts_fields = {}

                # measure every sensor with type 0
                for (sensorIndex, sensor) in enumerate(ds18b20Sensors):
                    # if we have at leat one filtered value we can upload
                    if len(filtered_temperature[sensorIndex]
                           ) > 0 and 'ts_field' in sensor:
                        ds18b20_temperature = filtered_temperature[
                            sensorIndex].pop()  # get last value from array
                        ts_field_ds18b20 = sensor["ts_field"]
                        if ts_field_ds18b20:
                            ts_fields.update(
                                {ts_field_ds18b20: ds18b20_temperature})

                # measure BME680 (can only be once) [type 1]
                if bme680Sensors and len(bme680Sensors) == 1 and gas_baseline:
                    bme680_values = measure_bme680(gas_baseline,
                                                   bme680Sensors[0])
                    ts_fields.update(bme680_values)

                # measure every sensor with type 2 [HX711]
                for (i, sensor) in enumerate(weightSensors):
                    weight = measure_weight(sensor)
                    ts_fields.update(weight)

                # measure every sensor with type 3 [DHT11/DHT22]
                for (i, sensor) in enumerate(dhtSensors):
                    tempAndHum = measure_dht(sensor)
                    ts_fields.update(tempAndHum)

                # print measurement values for debug reasons
                for key, value in ts_fields.iteritems():
                    print key + ": " + str(value)

                try:
                    # update ThingSpeak / transfer values
                    if len(ts_fields) > 0:
                        channel.update(ts_fields)
                        # reset connectionErros because transfer succeded
                        connectionErros = 0
                except requests.exceptions.HTTPError as errh:
                    error_log(errh, "Http Error")
                except requests.exceptions.ConnectionError as errc:
                    error_log(errc, "Error Connecting")
                    connectionErros += 1
                    # multiple connectionErrors in a row => Exception
                    if connectionErros > 4:
                        raise MyRebootException
                except requests.exceptions.Timeout as errt:
                    error_log(errt, "Timeout Error")
                except requests.exceptions.RequestException as err:
                    error_log(err, "Something Else")

            counter += 1
            sleep(0.96)

        end_time = time.time()
        time_taken = end_time - start_time  # time_taken is in seconds
        time_taken_s = float(
            "{0:.2f}".format(time_taken))  # remove microseconds
        print("Measurement-Script runtime was " + str(time_taken_s) +
              " seconds.")

    except MyRebootException as re:
        error_log(re, "Too many ConnectionErrors in a row => Rebooting")
        time.sleep(1)
        reboot()
    except Exception as e:
        error_log(e, "Unhandled Exception while Measurement")
        time.sleep(60)
        reboot()
Exemple #4
0
def measurement():
    # dict with all fields and values which will be tranfered to ThingSpeak later
    ts_fields = {}
    global burn_in_time
    try:

        # read settings
        settings = get_settings()

        debuglevel = int(settings["debuglevel"])
        debuglevel_logfile = int(settings["debuglevel_logfile"])

        logger = logging.getLogger('HoneyPi.measurement')
        logger.setLevel(logging.DEBUG)
        fh = logging.FileHandler(logfile)
        fh.setLevel(logging.getLevelName(debuglevel_logfile))
        # create console handler with a higher log level
        ch = logging.StreamHandler()
        ch.setLevel(logging.getLevelName(debuglevel))
        # create formatter and add it to the handlers
        formatter = logging.Formatter(
            '%(asctime)s | %(levelname)s | %(name)s | %(message)s')
        fh.setFormatter(formatter)
        ch.setFormatter(formatter)
        # add the handlers to the logger
        logger.addHandler(fh)
        logger.addHandler(ch)

        logger.info('Direct measurement started from webinterface.')

        # read configured sensors from settings.json
        ds18b20Sensors = get_sensors(settings, 0)
        bme680Sensors = get_sensors(settings, 1)
        weightSensors = get_sensors(settings, 2)
        dhtSensors = get_sensors(settings, 3)
        tcSensors = get_sensors(settings, 4)
        bme280Sensors = get_sensors(settings, 5)
        pcf8591Sensors = get_sensors(settings, 6)
        ee895Sensors = get_sensors(settings, 7)
        aht10Sensors = get_sensors(settings, 8)
        sht31Sensors = get_sensors(settings, 9)
        hdc1008Sensors = get_sensors(settings, 10)
        bme680Inits = []

        # if bme680 is configured
        for (sensorIndex, bme680Sensor) in enumerate(bme680Sensors):
            bme680Init = {}
            if 'burn_in_time' in bme680Sensor:
                burn_in_time = bme680Sensor["burn_in_time"]
            sensor = initBME680FromMain(bme680Sensor)
            gas_baseline = burn_in_bme680(sensor, burn_in_time)
            bme680Init['sensor'] = sensor
            bme680Init['gas_baseline'] = gas_baseline
            bme680Inits.append(bme680Init)

        ts_fields, bme680Inits = measure_all_sensors(
            False, None, ds18b20Sensors, bme680Sensors, bme680Inits,
            dhtSensors, aht10Sensors, sht31Sensors, hdc1008Sensors, tcSensors,
            bme280Sensors, pcf8591Sensors, ee895Sensors, weightSensors, None)

    except Exception as ex:
        logger.exception("Unhandled Exception in direct measurement")

    return json.dumps(ts_fields)
def start_read_and_upload_all(measurement_stop):
    print("Messungen beginnen")
    # reset event flag in case thread is started again
    measurement_stop.clear()
    event.clear()
    
    # bme680 sensor must be burned in before use
    gas_baseline = burn_in_bme680()
    
    # if burning was canceled=> exit
    if gas_baseline is None:
        print "gas_baseline can't be None"
        stop_read_and_upload_all()

    # here we start the thread
    # we use a thread in order to gather/process the data separately from the printing process
    data_collector = threading.Thread(target=read_values)
    data_collector.start()

    # ThingSpeak channel
    channel = thingspeak.Channel(id=channel_id, write_key=write_key)

    counter = 0
    while not event.is_set() and not measurement_stop.is_set():
        # wait seconds of interval before next check
        # free ThingSpeak account has an upload limit of 15 seconds
        if counter%interval == 0:
            if len(filtered_temperature) > 0:  # or we could have used filtered_humidity instead
                lock.acquire()

                # dict with all fields and values with will be tranfered later to ThingSpeak
                ts_fields = {}

                # here you can do whatever you want with the variables: print them, file them out, anything
                
                # measure sensor with type 0
                ds18b20_temperature = filtered_temperature.pop()
                ts_field_ds18b20 = get_sensors(0)[0]["ts_field"]
                ts_fields.update({ts_field_ds18b20: ds18b20_temperature})

                # measure BME680 (can only be once)
                bme680_values = measure_bme680(gas_baseline, get_sensors(1)[0])
                ts_fields.update(bme680_values)

                # measure every sensor with type 2
                for (i, sensor) in enumerate(get_sensors(2)):
                    weight = measure_weight(sensor)
                    ts_fields.update(weight)

                # print measurement values for debug reasons
                for key, value in ts_fields.iteritems():
                    print key + ": " + str(value)
                
                try:
                    # update ThingSpeak / transfer values
                    channel.update(ts_fields)
                except HTTPError:
                    print "HTTPError occurred"  

                lock.release()

            counter++
        sleep(1)

    # wait until the thread is finished
	data_collector.join()