def check_wittypi_voltage(time_measured_Voltage, wittyPi, pcf8591Sensors, isLowVoltage, interval, shutdownAfterTransfer, pcf8591Sensorforvoltagecheck=0):
    try:
        if wittyPi["voltagecheck_enabled"] and wittyPi["enabled"]:
            intervalVoltageCheck = 60
            time_now = time.time()
            isTimeToCheckVoltage = (time_now-time_measured_Voltage >= intervalVoltageCheck)
            if isTimeToCheckVoltage:
                if pcf8591Sensors and len(pcf8591Sensors) > 0:
                    print(str(pcf8591Sensors[pcf8591Sensorforvoltagecheck]))
                    voltage = get_raw_voltage(pcf8591Sensors[pcf8591Sensorforvoltagecheck])
                    if voltage is not None:
                        now = time.strftime("%H:%M", time.localtime(time_now))
                        logger.debug("Voltage Check at " + str(now) + ": " + str(voltage) + " Volt")
                        if voltage <= wittyPi["low"]["voltage"]:
                            logger.debug("Running on low voltage")
                            if (isLowVoltage == False) or (isLowVoltage is None):
                                if wittyPi["low"]["enabled"]:
                                    logger.info("Enable wittyPi low voltage settings!")
                                    update_wittypi_schedule(wittyPi["low"]["schedule"])
                                else:
                                    logger.warning("Low voltage but wittyPi disabled!")
                                    update_wittypi_schedule("")
                                interval = wittyPi["low"]["interval"]
                                shutdownAfterTransfer = wittyPi["low"]["shutdownAfterTransfer"]
                                isLowVoltage = setStateToStorage('isLowVoltage', True)
                                logger.info("New Interval: '" + str(interval) + "', Shutdown after transfer is '" + str(shutdownAfterTransfer)  +"'")
                        elif voltage < wittyPi["normal"]["voltage"]:
                            logger.info("No longer low voltage but recovery voltage not reached")
                        elif voltage >= wittyPi["normal"]["voltage"]:
                            logger.debug("Running on normal voltage")
                            if (isLowVoltage == True) or (isLowVoltage is None):
                                if wittyPi["normal"]["enabled"]:
                                    logger.info("Enable wittyPi normal voltage settings!")
                                    update_wittypi_schedule(wittyPi["normal"]["schedule"])
                                else:
                                    logger.info("Normal voltage but wittyPi disabled!")
                                    update_wittypi_schedule("")
                                    interval = wittyPi["normal"]["interval"]
                                    shutdownAfterTransfer = wittyPi["normal"]["shutdownAfterTransfer"]
                                isLowVoltage = setStateToStorage('isLowVoltage', False)
                                logger.info("New Interval: '" + str(interval) + "', Shutdown after transfer is '" + str(shutdownAfterTransfer)  +"'")
                        else:
                            logger.error("Choosen WittyPi Voltage settings irregular Voltage Normal should be higher than Undervoltage")
                    else:
                        logger.error("Voltagesensor did not return a value!")
                else:
                    logger.error("WittyPi Voltage checks enabled but no pcf8591Sensors configured")
                    time_measured_Voltage = time.time()
            else:
                logger.debug("No Voltage Check due")

        return (time_measured_Voltage, interval, shutdownAfterTransfer, isLowVoltage)
    except Exception as ex:
        logger.exception("Exception during check_wittypi_voltage")
        measurementIsRunning.value = 0 # clear flag
示例#2
0
def stop_ap():
    global isActive, GPIO_LED
    stop_led(GPIO_LED)
    t2 = threading.Thread(target=ap_to_client_mode)
    t2.start()
    t2.join()
    isActive = 0  # measurement shall stop next time
    isMaintenanceActive = setStateToStorage('isMaintenanceActive', False)
示例#3
0
def start_ap():
    global isActive, GPIO_LED
    start_led(GPIO_LED)
    t1 = threading.Thread(target=client_to_ap_mode)
    t1.start()
    t1.join()
    isActive = 1  # measurement shall start next time
    print(">>> Connect yourself to HoneyPi-AccessPoint Wifi")
    isMaintenanceActive = setStateToStorage('isMaintenanceActive', True)
示例#4
0
def main():
    try:
        global isActive, measurement_stop, measurement, debug, GPIO_BTN, GPIO_LED
        logger = logging.getLogger('HoneyPi')
        logger.setLevel(logging.DEBUG)
        fh = logging.FileHandler(logfile)
        fh.setLevel(logging.DEBUG)
        # create console handler with a higher log level
        ch = logging.StreamHandler()
        ch.setLevel(logging.INFO)
        # create formatter and add it to the handlers
        formatter = logging.Formatter(
            '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
        fh.setFormatter(formatter)
        ch.setFormatter(formatter)
        # add the handlers to the logger
        logger.addHandler(fh)
        logger.addHandler(ch)
        #logging.basicConfig(filename=logfile, format='%(asctime)s %(levelname)-8s %(message)s', level=logging.INFO)
        #logging.getLogger().addHandler(logging.StreamHandler(sys.stdout))
        logger.info('HoneyPi Started')

        # Zaehlweise der GPIO-PINS auf der Platine
        GPIO.setmode(GPIO.BCM)

        # read settings for number of GPIO pin
        settings = get_settings()
        debuglevel = settings["debuglevel"]

        print("Debuglevel: " + str(debuglevel))
        time.sleep(5)
        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)
        GPIO_BTN = settings["button_pin"]
        GPIO_LED = settings["led_pin"]

        # setup LED as output
        GPIO.setup(GPIO_LED, GPIO.OUT)

        # blink with LED on startup
        tblink = threading.Thread(target=blink_led, args=(GPIO_LED, ))
        tblink.start()

        # after start is AccessPoint down
        stop_ap()

        # Create virtual uap0 for WLAN
        create_ap()

        # Call wvdial for surfsticks
        start_wvdial()

        if not debuglevel <= 20:
            # stop HDMI power (save energy)
            print("Info: Shutting down HDMI to save energy.")
            stop_tv()
            stop_hdd_led()
        else:
            logger.info("Info: Raspberry Pi has been powered on.")
            start_hdd_led()

        logger.info("Default gateway used for Internet connection is: " +
                    str(get_default_gateway_linux()))
        logger.info("Interface eth0 is up: " +
                    str(get_interface_upstatus_linux('eth0')))
        logger.info("Interface wlan0 is up: " +
                    str(get_interface_upstatus_linux('wlan0')))

        # start as seperate background thread
        # because Taster pressing was not recognised
        isMaintenanceActive = setStateToStorage('isMaintenanceActive', False)
        measurement_stop = threading.Event(
        )  # create event to stop measurement
        measurement = threading.Thread(target=start_measurement,
                                       args=(measurement_stop, ))
        measurement.start()  # start measurement

        # setup Button
        GPIO.setup(
            GPIO_BTN, GPIO.IN, pull_up_down=GPIO.PUD_DOWN
        )  # Set pin 16 to be an input pin and set initial value to be pulled low (off)
        #GPIO.setup(GPIO_LED, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) # Set LED to be an input pin and set initial value to be pulled low (off)
        bouncetime = 100  # ignoring further edges for 100ms for switch bounce handling
        # register button press event
        GPIO.add_event_detect(GPIO_BTN,
                              GPIO.BOTH,
                              callback=button_pressed,
                              bouncetime=bouncetime)
        #GPIO.add_event_detect(GPIO_LED, GPIO.BOTH, callback=get_led_state)

        # Main Lopp: Cancel with STRG+C
        while True:
            time.sleep(
                0.2)  # wait 200 ms to give CPU chance to do other things
            pass

        print("This text will never be printed.")
    except Exception as e:
        logger.critical("Unhandled Exception in main " + repr(e))
        if not debug:
            time.sleep(60)
            reboot()
示例#5
0
def main():
    try:
        global isActive, measurement_stop, measurement, debug, GPIO_BTN, GPIO_LED

        # Zaehlweise der GPIO-PINS auf der Platine
        GPIO.setmode(GPIO.BCM)

        # read settings for number of GPIO pin
        settings = get_settings()
        debuglevel = int(settings["debuglevel"])
        debuglevel_logfile = int(settings["debuglevel_logfile"])

        logger = logging.getLogger('HoneyPi')
        logger.setLevel(logging.DEBUG)
        fh = RotatingFileHandler(logfile,
                                 maxBytes=5 * 1024 * 1024,
                                 backupCount=365)
        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)

        time.sleep(1)

        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)

        if debuglevel > 20:
            # stop HDMI power (save energy)
            logger.info('HoneyPi ' + get_rpiscripts_version() +
                        ' Started on ' + get_pi_model() + ', Debuglevel: "' +
                        logging.getLevelName(debuglevel) +
                        '", Debuglevel logfile: "' +
                        logging.getLevelName(debuglevel_logfile) + '"')
            stop_tv()
            stop_hdd_led()
        else:
            logger.info('HoneyPi ' + get_rpiscripts_version() +
                        ' Started on ' + get_pi_model())
            start_hdd_led()

        runpostupgradescript()

        GPIO_BTN = settings["button_pin"]
        GPIO_LED = settings["led_pin"]

        # setup LED as output
        GPIO.setup(GPIO_LED, GPIO.OUT)

        # blink with LED on startup
        tblink = threading.Thread(target=blink_led, args=(GPIO_LED, ))
        tblink.start()

        # Call wvdial for surfsticks
        connect_internet_modem(settings)

        # check undervolate for since system start
        check_undervoltage()

        # start as seperate background thread
        # because Taster pressing was not recognised
        isMaintenanceActive = setStateToStorage('isMaintenanceActive', False)
        measurement_stop = threading.Event(
        )  # create event to stop measurement
        measurement = threading.Thread(target=start_measurement,
                                       args=(measurement_stop, ))
        measurement.start()  # start measurement

        # setup Button
        GPIO.setup(
            GPIO_BTN, GPIO.IN, pull_up_down=GPIO.PUD_DOWN
        )  # Set pin 16 to be an input pin and set initial value to be pulled low (off)
        bouncetime = 100  # ignoring further edges for 100ms for switch bounce handling
        # register button press event
        GPIO.add_event_detect(GPIO_BTN,
                              GPIO.BOTH,
                              callback=button_pressed,
                              bouncetime=bouncetime)

        # Main Lopp: Cancel with STRG+C
        while True:
            time.sleep(
                0.2)  # wait 200 ms to give CPU chance to do other things
            pass

        print("This text will never be printed.")
    except Exception as ex:
        logger.critical("Unhandled Exception in main: " + repr(ex))
        if not debug:
            time.sleep(60)
            reboot()
def check_wittypi_voltage(time_measured_Voltage, wittyPi, voltageSensors,
                          isLowVoltage, interval, shutdownAfterTransfer):
    if wittyPi["voltagecheck_enabled"] and wittyPi["enabled"]:
        intervalVoltageCheck = 60
        time_now = time.time()
        isTimeToCheckVoltage = (time_now - time_measured_Voltage >=
                                intervalVoltageCheck)
        if isTimeToCheckVoltage:
            if voltageSensors and len(voltageSensors) == 1:
                voltage = get_raw_voltage(voltageSensors[0])
                if voltage is not None:
                    now = time.strftime("%H:%M", time.localtime(time_now))
                    print("Voltage Check at " + str(now) + ": " +
                          str(voltage) + " Volt")
                    if voltage <= wittyPi["low"]["voltage"]:
                        print("Running on low voltage")
                        if (isLowVoltage == False) or (isLowVoltage is None):
                            if wittyPi["low"]["enabled"]:
                                error_log(
                                    "Info: Enable wittyPi low voltage settings!"
                                )
                                update_wittypi_schedule(
                                    wittyPi["low"]["schedule"])
                            else:
                                error_log(
                                    "Info: Low voltage but wittyPi disabled!")
                                update_wittypi_schedule("")
                            interval = wittyPi["low"]["interval"]
                            shutdownAfterTransfer = wittyPi["low"][
                                "shutdownAfterTransfer"]
                            isLowVoltage = setStateToStorage(
                                'isLowVoltage', True)
                            error_log("Info: New Interval: '" + str(interval) +
                                      "', Shutdown after transfer is '" +
                                      str(shutdownAfterTransfer) + "'")
                    elif voltage < wittyPi["normal"]["voltage"]:
                        print(
                            "No longer low voltage but recovery voltage not reached"
                        )
                    elif voltage >= wittyPi["normal"]["voltage"]:
                        print("Running on normal voltage")
                        if (isLowVoltage == True) or (isLowVoltage is None):
                            if wittyPi["normal"]["enabled"]:
                                error_log(
                                    "Info: Enable wittyPi normal voltage settings!"
                                )
                                update_wittypi_schedule(
                                    wittyPi["normal"]["schedule"])
                            else:
                                error_log(
                                    "Info: Normal voltage but wittyPi disabled!"
                                )
                                update_wittypi_schedule("")
                                interval = wittyPi["normal"]["interval"]
                                shutdownAfterTransfer = wittyPi["normal"][
                                    "shutdownAfterTransfer"]
                            isLowVoltage = setStateToStorage(
                                'isLowVoltage', False)
                            error_log("Info: New Interval: '" + str(interval) +
                                      "', Shutdown after transfer is '" +
                                      str(shutdownAfterTransfer) + "'")
                    else:
                        error_log(
                            "Warning: Choosen WittyPi Voltage settings irregular Voltage Normal should be higher than Undervoltage"
                        )
                else:
                    error_log("Error: Voltagesensor did not return a value!")
            else:
                error_log(
                    "Warning: WittyPi Voltage checks enabled but no VoltageSensors configured"
                )
                time_measured_Voltage = time.time()
        else:
            print("No Voltage Check due")

    return (time_measured_Voltage, interval, shutdownAfterTransfer,
            isLowVoltage)