Esempio n. 1
0
def button_pressed_falling(self):
    global time_rising, debug, GPIO_LED, LED_STATE
    time_falling = miliseconds()
    time_elapsed = time_falling - time_rising
    time_rising = 0  # reset to prevent multiple fallings from the same rising
    MIN_TIME_TO_ELAPSE = 500  # miliseconds
    MAX_TIME_TO_ELAPSE = 3000

    if debug:
        print("button_pressed_falling")
    if time_elapsed >= 0 and time_elapsed <= 30000:
        if time_elapsed >= MIN_TIME_TO_ELAPSE and time_elapsed <= MAX_TIME_TO_ELAPSE:
            # normal button press to switch between measurement and maintenance
            tmeasurement = threading.Thread(target=toggle_measurement)
            tmeasurement.start()
        elif time_elapsed >= 5000 and time_elapsed <= 10000:
            # shutdown raspberry
            tblink = threading.Thread(target=blink_led, args=(GPIO_LED, 0.1))
            tblink.start()
            shutdown()
        elif time_elapsed >= 10000 and time_elapsed <= 15000:
            # reset settings and shutdown
            tblink = threading.Thread(target=blink_led, args=(GPIO_LED, 0.1))
            tblink.start()
            delete_settings()
            update_wittypi_schedule("")
            logger.critical("Resettet settings because Button was pressed.")
            shutdown()
        elif debug:
            time_elapsed_s = float("{0:.2f}".format(time_elapsed /
                                                    1000))  # ms to s
            logger.warning(
                "Too short Button press, Too long Button press OR inteference occured: "
                + str(time_elapsed_s) + "s elapsed.")
Esempio n. 2
0
def button_pressed_falling():
    global time_start, debug
    time_end = miliseconds()
    time_elapsed = time_end - time_start
    MIN_TIME_TO_ELAPSE = 500  # miliseconds
    MAX_TIME_TO_ELAPSE = 3000
    if time_elapsed >= MIN_TIME_TO_ELAPSE and time_elapsed <= MAX_TIME_TO_ELAPSE:
        time_start = 0  # reset to prevent multiple fallings from the same rising
        toggle_measurement()
    elif time_elapsed >= 5000 and time_elapsed <= 10000:
        time_start = 0  # reset to prevent multiple fallings from the same rising
        shutdown()
    elif debug:
        error_log(
            "Info: Too short Button press, Too long Button press OR inteference occured."
        )
Esempio n. 3
0
def button_pressed_falling():
    global time_rising, debug
    time_falling = miliseconds()
    time_elapsed = time_falling - time_rising
    time_rising = 0  # reset to prevent multiple fallings from the same rising
    MIN_TIME_TO_ELAPSE = 500  # miliseconds
    MAX_TIME_TO_ELAPSE = 3000
    stop_led()
    if time_elapsed >= MIN_TIME_TO_ELAPSE and time_elapsed <= MAX_TIME_TO_ELAPSE:
        toggle_measurement()
    elif time_elapsed >= 5000 and time_elapsed <= 10000:
        shutdown()
    elif time_elapsed >= 10000 and time_elapsed <= 15000:
        delete_settings()
        shutdown()
    elif debug:
        error_log(
            "Info: Too short Button press, Too long Button press OR inteference occured: "
            + str(time_elapsed) + "ms elapsed.")
Esempio n. 4
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:
        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()
Esempio n. 6
0
            li = str.split()
            return li

        li = get_words(str)

        if "open" in li or "Open" in li or "close" in li or "back" in li or "organise" in li:
            ffo.opening(li)
        elif ("play" in li or "Play" in li) and ("music" in li
                                                 or "Music" in li):
            music.play_music(li[1])
        elif "switch" in li:
            utilities.tabs_switching_operation()
        elif "search" in li and "google" in li:
            google_surf.search()
        elif "run" in li:
            run_executables.run_executable(" ".join(li[1:]))
        elif "shutdown" in li:
            utilities.shutdown()
        elif "restart" in li:
            utilities.restart()
        elif "tell" in li and "me" in li and "looking" in li:
            Webcam.trigger()
        elif "bye" in li:
            break
    except sr.UnknownValueError:
        play_sound('sorry.wav')
    #print("Google Speech Recognition could not understand audio")
    except sr.RequestError as e:
        play_sound('sorry.wav')
#        print("Could not request results from Google Speech Recognition service; {0}".format(e))