Ejemplo n.º 1
0
def start_measurement(measurement_stop):
    try:
        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"]
        debug = settings[
            "debug"]  # flag to enable debug mode (HDMI output enabled and no rebooting)
        shutdownAfterTransfer = settings["shutdownAfterTransfer"]
        offline = settings["offline"]  # flag to enable offline csv storage

        if debug:
            print("Debug-Mode is enabled.")
            error_log("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 or not channel_id or not write_key:
            error_log(
                "Info: No measurement because ThingSpeak settings are not complete or measurement 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)

        # -- Run Pre Configuration --
        # if bme680 is configured
        if bme680Sensors and len(bme680Sensors) == 1:
            bme680IsInitialized = initBME680FromMain()
        else:
            bme680IsInitialized = 0

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

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

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

            # 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'])

            # wait seconds of interval before next check
            # free ThingSpeak account has an upload limit of 15 seconds
            time_now = time.time()
            isTimeToMeasure = (time_now - time_measured >= interval
                               ) and counter > 0  # old: counter%interval == 0
            if isTimeToMeasure or interval == 1:
                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()

                if measurementIsRunning.value == 0:
                    q = Queue()
                    p = Process(target=measure,
                                args=(offline, debug, channel,
                                      filtered_temperature, ds18b20Sensors,
                                      bme680Sensors, bme680IsInitialized,
                                      dhtSensors, tcSensors, bme280Sensors,
                                      weightSensors, hxInits, connectionErrors,
                                      measurementIsRunning))
                    p.start()
                    p.join()
                else:
                    error_log(
                        "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:
                        print(
                            "Shutting down was set => Waiting 10seconds and then shutdown."
                        )
                        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 e:
        error_log(e, "Unhandled Exception while Measurement")
        if not debug:
            time.sleep(10)
            reboot()
Ejemplo n.º 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()