Пример #1
0
def disable_network(id):
    try:
        wpa_cli.disable_network(id)
    except wpa_cli.WPAException:
        Printer(['Failed to', 'disable network'], i, o, skippable=True)
    else:
        wpa_cli.save_config()
        Printer(['Disabled network', str(id)], i, o, skippable=True)
Пример #2
0
def select_network(id):
    try:
        wpa_cli.select_network(id)
    except wpa_cli.WPAException:
        Printer(['Failed to', 'select network'], i, o, skippable=True)
    else:
        wpa_cli.save_config()
        Printer(['Selected network', str(id)], i, o, skippable=True)
Пример #3
0
def start_unit(name):
    print(name)
    status = systemctl.action_unit("start", name)
    if status:
        Printer(["Started unit", name], i, o, 1)
    else:
        Printer(["Can't start", name], i, o, 1)
    raise MenuExitException
Пример #4
0
def callback():
    # picking a wireless interface to go with
    # needed on i.e. RPi3 to avoid the p2p-dev-wlan0 stuff
    # thanks Raspbian developers, you broke a lot of decent WiFi setup tutorials
    # even if by accident =(
    # also needed to support proper multi-interface work for the app
    global last_interface, current_interface, wifi_connect_status_cb
    winterfaces = pyw.winterfaces()
    if not winterfaces:
        Printer("No wireless cards found, exiting", i, o, 3, skippable=True)
        return
    if last_interface:
        # last_interface is only set when an interface was explicitly changed
        if last_interface in winterfaces:
            # last interface still present
            current_interface = last_interface
        else:
            # last interface no longer present, clearing it to avoid confusion
            # and picking an interface that actually exists
            last_interface = None
            current_interface = winterfaces[0]
    else:
        current_interface = winterfaces[0]  # Simple, I know
        # Might add some ZP-specific logic here later, so that
        # i.e. the ESP-12 based WiFi is guaranteed to be the first
    # clearing the connect status callback that might be left over
    # after the WiFi connect wizard
    wifi_connect_status_cb = None

    def get_contents():
        # A function for main menu to be able to dynamically update
        return [["Status", status_monitor],
                ["Current: {}".format(current_interface), change_interface],
                ["Scan", scan], ["Networks", show_scan_results],
                ["Saved networks", saved_networks]]

    # Testing if we actually can connect
    try:
        wpa_cli.set_active_interface(current_interface)
    except OSError as e:
        if e.errno == 2:
            Printer("wpa_cli not found, exiting", i, o, 3, skippable=True)
            return
        else:
            raise e
    except wpa_cli.WPAException:
        Printer(
            "Do you have wireless cards? Is wpa_supplicant running? Exiting",
            i,
            o,
            3,
            skippable=True)
        return
    else:
        start_monitor()
        Menu([], i, o, "wpa_cli main menu",
             contents_hook=get_contents).activate()
        stop_monitor()
Пример #5
0
def start_lecture():
    if not file_path:
        Printer("File path not set!", i, o, skippable=True)
    if not interval:
        Printer("Interval not set!", i, o, skippable=True)
    if not file_path or not interval:
        return
    helper = LectureHelper(file_path, interval)
    helper.start()
Пример #6
0
def quick_scan_network_by_ip(ip_on_network):
    if ip_on_network == "None":
        Printer("No IP to scan!", i, o, 2)
        return False
    network_ip = get_network_from_ip(ip_on_network)
    Printer("Scanning {}".format(network_ip), i, o, 0)
    nm = nmap.PortScanner()
    nm.scan(network_ip, arguments="-sn")
    show_quick_scan_results_for_network(network_ip, nm)
Пример #7
0
def change_current_interface(interface):
    try:
        wpa_cli.set_active_interface(interface)
    except wpa_cli.WPAException:
        Printer(['Failed to change', 'interface'], i, o, skippable=True)
    else:
        Printer(['Changed to', interface], i, o, skippable=True)
    finally:
        raise MenuExitException
Пример #8
0
def enable_network(net_id, silent=False):
    try:
        wpa_cli.enable_network(net_id)
    except wpa_cli.WPAException:
        if not silent:
            Printer('Failed to enable network', i, o, skippable=True)
    else:
        wpa_cli.save_config()
        if not silent:
            Printer('Enabled network ' + str(net_id), i, o, skippable=True)
Пример #9
0
def flash_image_ui():
    if not MTKDownloadProcess(None, None, path=config["mtkdownload_path"]).mtkdownload_is_available():
        Printer("mtkdownload not found!", i, o, 5)
        choice = DialogBox("yn", i, o, name="Hardware setup app mtkdownload path confirmation", message="Set mtkdownload path?").activate()
        if choice:
            if set_mtkdownload_path():
                # Running again, now the path should be valid
                flash_image_ui()
            return # No need to continue whether we've recursed or not, exiting
    files = collect_fw_folders(config["gsm_fw_path"])
    lbc = [[os.path.basename(file), file] for file in files]
    if not lbc:
        Printer("No firmware images found!", i, o, 5)
        choice = DialogBox("yn", i, o, name="Hardware setup app mtkdownload path confirmation", message="Alternative FW path?").activate()
        if choice:
            if set_sim_firmware_path():
                # Running again, now there should be some firmware
                flash_image_ui()
            return
    choice = Listbox(lbc, i, o, name="Hardware setup app GSM FW picker").activate()
    # A ProgressBar for the flashing specifically
    pb = ProgressBar(i, o, message="Flashing the modem")
    # A LoadingIndicator for everything else
    li = LoadingIndicator(i, o, message="Waiting for modem")
    if choice:
        cb = lambda state: process_state(pb, li, state)
        p = MTKDownloadProcess("/dev/ttyAMA0", choice, callback=cb, path=config["mtkdownload_path"])
        gp = get_gsm_reset_gpio()
        if not gp:
            return
        def reset():
            gpio.setup(gp, gpio.OUT)
            gpio.set(gp, False)
            sleep(0.1)
            gpio.set(gp, True)
        e = None
        try:
            p.write_image(reset_cb=reset)
        except Exception as e:
            e = traceback.format_exc()
        state = p.get_state()
        if state["state"] == "failed" or e:
            choice = DialogBox("yn", i, o, message="Send bugreport?").activate()
            if choice:
                br = BugReport("mtkdownload_flash_fail.zip")
                if e:
                    br.add_text(json.dumps(e), "mtkdownload_exception.json")
                br.add_text(json.dumps(p.dump_info()), "mtkdownload_psinfo.json")
                result = br.send_or_store("/boot/", logger=logger)
                if result[0]:
                    logger.info("Report sent to {}".format(result[1]))
                else:
                    logger.info("Report stored in {}".format(result[1]))
Пример #10
0
def show_devices():
    menu_contents = []
    try:
        usb_devices = lsusb.lsusb()
    except OSError:
        Printer(["Do you have", "lsusb?"], i, o, 2)
        return False
    for bus, dev, vid_pid, name in usb_devices:
        ell_name = ellipsize(name, o.cols)
        menu_contents.append([["{}{},{}".format(bus, dev, vid_pid), ell_name],
                              lambda x=name: Printer(x, i, o, skippable=True)])
    Menu(menu_contents, i, o, entry_height=2).activate()
Пример #11
0
def scan():
    try:
        wpa_cli.initiate_scan()
    except wpa_cli.WPAException as e:
        if e.code == "FAIL-BUSY":
            Printer("Still scanning...", i, o, 1)
        else:
            raise
    else:
        Printer("Scanning...", i, o, 1)
    finally:
        sleep(1)
Пример #12
0
def remove_network(id):
    want_to_remove = DialogBox("yn", i, o, message="Remove network?").activate()
    if not want_to_remove:
        return 
    try:
        wpa_cli.remove_network(id)
    except wpa_cli.WPAException:
        Printer(['Failed to', 'remove network'], i, o, skippable=True)
    else:
        wpa_cli.save_config()
        Printer(['Removed network', str(id)], i, o, skippable=True)
        raise MenuExitException
Пример #13
0
def change_current_interface(interface):
    global current_interface, last_interface
    try:
        wpa_cli.set_active_interface(interface)
    except wpa_cli.WPAException:
        Printer('Failed to change interface', i, o, skippable=True)
    else:
        Printer('Changed to ' + interface, i, o, skippable=True)
        restart_monitor(interface=interface)
        current_interface = interface
        last_interface = interface
    finally:
        raise MenuExitException
Пример #14
0
def scan(delay=True):
    delay = 1 if delay else 0
    try:
        wpa_cli.initiate_scan()
        enable_temp_disabled_networks()
    except wpa_cli.WPAException as e:
        if e.code == "FAIL-BUSY":
            Printer("Still scanning...", i, o, 1)
        else:
            raise
    else:
        Printer("Scanning...", i, o, 1)
    finally:
        sleep(delay)
Пример #15
0
def smart_scan():
    #First, getting all available interfaces
    networks = []
    interface_data = get_ip_addr()
    for interface_name in interface_data.keys():
        #Autofiltering unsuitable interfaces
        interface_info = interface_data[interface_name]
        state = interface_info["state"]
        ip = interface_info["addr"] if interface_info["addr"] else None
        if state == "up" and ip is not None:
            #Only using interface if it's up and has an IP
            #Automatically filters out localhost
            networks.append(["{}:{}".format(interface_name, ip), ip])
    if not networks:
        #No suitable interfaces found after filtering
        Printer(ffs("No suitable network interfaces found!", o.cols), i, o, 3)
        return None
    if len(networks) == 1:
        #Only one good interface, using it automatically
        network_ip = networks[0][1]
    else:
        #Allowing user to pick an interface
        network_ip = Listbox(networks, i, o).activate()
        if network_ip is None:  #Listbox exited without making a choice
            return None
    network_ip = get_network_from_ip(network_ip)
    chosen_ports = Checkbox(heuristic_ports,
                            i,
                            o,
                            name="NMap: select port types",
                            final_button_name="Run scan").activate()
    if chosen_ports is None: return None
    chosen_port_list = [
        port_choice for port_choice in chosen_ports
        if chosen_ports[port_choice] == True
    ]
    port_string = ",".join(chosen_port_list)
    #So the library I'm using is silently failing. I launch the scan from command-line and see:
    #
    #WARNING: Duplicate port number(s) specified.  Are you alert enough to be using Nmap?  Have some coffee or Jolt(tm).
    #
    #Well, thank you, but it's a script and f**k off.
    port_string = ",".join(list(set(port_string.split(","))))
    #De-duplicated and ready to go.
    print(port_string)
    Printer(ffs("Scanning {}".format(network_ip), o.cols), i, o, 0)
    nm = nmap.PortScanner()
    nm.scan(network_ip, arguments="-n -p {}".format(port_string))
    print(nm)
    show_quick_scan_results_for_network(network_ip, nm)
Пример #16
0
def get_request(url):
    req_get = requests.get(url)
    cont = unicode(req_get.content, "utf-8")
    if len(cont) == 0:
        if req_get.status_code == 200:
            TextReader(html2text.html2text(cont), i, o)
        elif req_get.status_code == 404:
            Printer("Error 404, Not Found!", i, o)
        elif req_get.status_code == 500:
            Printer("Error 500, Internal server error!", i, o)
        else:
            TextReader(html2text.html2text(cont), i, o)
    else:
        TextReader(html2text.html2text(cont), i, o)
Пример #17
0
def call_external(script_list, shell=False):
    if shell == True:
        script_path = script_list.split(' ')[0]
    else:
        script_path = os.path.split(script_list[0])[1]
    Printer("Calling {}".format(script_path), i, o, 1)
    try:
        output = check_output(script_list, stderr=STDOUT, shell=shell)
    except OSError as e:
        if e.errno == 2:
            Printer("File not found!", i, o, 1)
        elif e.errno == 13:
            Printer(["Permission", "denied!"], i, o, 1)
        elif e.errno == 8:
            Printer(["Unknown format,", "forgot header?"], i, o, 1)
        else:
            error_data = ["Unknown error", ""]
            error_data += ffs(repr(e), o.cols)
            Printer(error_data, i, o, 1)
        output = ""
    except CalledProcessError as e:
        Printer(["Failed with", "code {}".format(e.returncode)], i, o, 1)
        output = e.output
    else:
        Printer("Success!", i, o, 1)
    finally:
        if not output:
            return
        answer = DialogBox("yn", i, o, message="Show output?").activate()
        if answer == True:
            Printer(ffs(output, o.cols, False), i, o, 5, True)
Пример #18
0
 def force_sync_time(self):
     Printer("Syncing time", self.i, self.o, 0)
     try:
         output = check_output(["sntp", "-S", "pool.ntp.org"])
     except CalledProcessError:
         logger.exception("Failed to sync time!")
         Printer("Failed to sync time!", self.i, self.o, 1)
         return False
     except OSError:
         logger.exception("Failed to sync time - sntp not installed!")
         Printer("Failed to sync time (no sntp)!", self.i, self.o, 1)
         return False
     else:
         Printer("Synced time successfully!", self.i, self.o, 1)
         return True
Пример #19
0
def callback():
    problem_found = False
    problem_fixed = False
    logger.debug("App launched")
    li = LoadingBar(i, o, message="Detecting hardware")
    li.run_in_background()
    sleep(1)  # Showing the message a little bit
    hw_version = get_hw_version(li)
    if not hw_version:
        return False  # User pressed LEFT in Listbox
    # DKMS check
    # if hardware is undetected, do we need to check it?
    # ask the user.
    hw_wrong_but_check_esp = False
    if hw_version == "other":
        hw_wrong_but_check_esp = DialogBox(
            "yn", i, o, message="Using ESP8266?").activate()
    # This deals with ESP8266 problems
    if hw_version == "zero" or hw_wrong_but_check_esp:
        #check dkms module
        problem_found = check_esp8089_dkms(li)
        #check esp8089 module
        if not problem_found:
            if kmodpy:
                problem_found, problem_fixed = check_esp8089_module(li)
            else:
                logger.debug(
                    "kmodpy not available, not checking the esp8089 module")
        # Check dmesg
        if not problem_found:
            problem_found = check_dmesg(li)
        # Check config.txt
        if not problem_found:
            problem_found = problem_fixed = check_zero_config_txt(li)
    elif hw_version == "zerow":
        # Check brcmfmac module
        problem_found, problem_fixed = check_brcmfmac_module(li)
        # Check config.txt
        if not problem_found:
            problem_found = problem_fixed = check_zerow_config_txt(li)
    li.stop()
    if problem_found:
        if problem_fixed:
            Printer("Fixed some problems!", i, o)
        else:
            Printer("Couldn't fix problems!", i, o)
    else:
        Printer("No problems found!", i, o)
Пример #20
0
def call(number):
    Printer("Calling {}".format(number), i, o, 0)
    try:
        phone.call(number)
    except ATError as e:
        PrettyPrinter("Calling fail! "+repr(e), i, o, 0)
    logger.error("Function stopped executing")
Пример #21
0
def show_menu():
    script_menu_contents = []
    scripts_in_config = []
    try:
        config = read_config(config_path)
    except ValueError:
        Printer("Invalid config!", i, o)
    else:
        for script_def in config:
            script_path = script_def["path"]
            if script_path.startswith('./'):
                script_path = script_path.lstrip('.').lstrip('/')
                script_path = os.path.join(base_dir, script_path)
                scripts_in_config.append(script_path)
            args = script_def["args"] if "args" in script_def else []
            script_name = script_def[
                "name"] if "name" in script_def else os.path.split(
                    script_path)[1]
            script_list = [script_path] + args
            script_menu_contents.append(
                [script_name, lambda x=script_list: call_external(x)])
    other_scripts = os.listdir(os.path.join(base_dir, scripts_dir))
    for script in other_scripts:
        relpath = os.path.join(base_dir, scripts_dir, script)
        if relpath not in scripts_in_config:
            script_menu_contents.append([
                os.path.join(scripts_dir, script),
                lambda x=relpath: call_external([x])
            ])
    Menu(script_menu_contents, i, o, "Script menu").activate()
Пример #22
0
def select_hdmi_mode():
    menu_contents = []
    try:
        current_group = tvservice.status()['gmd'][0]
    except KeyError, IndexError:
        Printer(["Error, is HDMI", "enabled?"], i, o)
        return False
Пример #23
0
def scan_i2c_bus():
    global current_bus
    Printer("Scanning:", i, o, 0)
    current_bus = smbus.SMBus(1)  # 1 indicates /dev/i2c-1
    found_devices = OrderedDict()
    scan_range = config.get("scan_range", "conservative")
    if scan_range not in scan_ranges.keys(
    ):  #unknown scan range - config edited manually?
        scan_range = "conservative"
    scan_range_args = scan_ranges[scan_range]
    for device in range(*scan_range_args):
        try:  #If you try to read and it answers, it's there
            current_bus.read_byte(device)
        except IOError as e:
            if e.errno == 16:
                found_devices[device] = "busy"
            elif e.errno == 121:
                pass
            else:
                found_devices[device] = "error unknown"
                logger.error("Errno {} unknown - can be used? {}".format(
                    e.errno, repr(e)))
        else:
            found_devices[device] = "ok"
    return found_devices
Пример #24
0
def callback():
    if not check_modem_connection():
        Printer(ffs("Modem connection failed. Try again in 10 seconds.", o.cols), i, o)
        return
    contents = [["Status", status_refresher],
                ["Call", call_view]]
    Menu(contents, i, o).activate()
Пример #25
0
def init_app(input, output):
    global callback, i, o
    i = input
    o = output
    lsusb_output = check_output(['lsusb'])
    callback = lambda: Printer(
        ffs(lsusb_output, o.cols), i, o, sleep_time=5, skippable=True)
Пример #26
0
 def test_rgb_led(self):
     PrettyPrinter("Testing RGB LED", self.i, self.o, 1)
     from zerophone_hw import RGB_LED
     led = RGB_LED()
     for color in ["red", "green", "blue"]:
         led.set_color(color)
         Printer(color.center(self.o.cols), self.i, self.o, 3)
     led.set_color("none")
Пример #27
0
def exception_wrapper(callback):
    """This is a wrapper for all applications and menus. It catches exceptions and stops the system the right way when something bad happens, be that a Ctrl+c or an exception in one of the applications."""
    try:
        callback()
    except KeyboardInterrupt:
        Printer(["Does Ctrl+C", "hurt scripts?"], None, o, 0)
        i.atexit()
        sys.exit(1)
    except Exception as e:
        traceback.print_exc()
        Printer(["A wild exception", "appears!"], None, o, 0)
        i.atexit()
        sys.exit(1)
    else:
        Printer("Exiting ZPUI", None, o, 0)
        i.atexit()
        sys.exit(0)
Пример #28
0
def set_password(id):    
    input = NumpadCharInput(i, o, message="Password:"******"WiFi password enter UI element")
    password = input.activate()
    if password is None:
        return False
    wpa_cli.set_network(id, 'psk', '"{}"'.format(password))
    wpa_cli.save_config()
    Printer(["Password entered"], i, o, 1)
Пример #29
0
def adjust_timeout():
    global config
    timeout = IntegerAdjustInput(config["timeout"], i, o, message="Socket timeout:").activate()
    if timeout is not None and timeout > 0:
        config["timeout"] = timeout
        write_config(config, config_path)
    elif not timeout > 0:
        Printer(ffs("Timeout has to be larger than 0!", o.cols), i, o)
Пример #30
0
def mocp_command(*command, **options):
    try:
        return call(['mocp'] + list(command))
    except:
        #We shouldn't print anything to the screen if called from a non-maskable callback
        silent = options.get("silent", False)
        if not silent:
            Printer(["Oops", "Is mocp there?"], i, o, 1)