def stop_unit(name): status = systemctl.action_unit("stop", name) if status: PrettyPrinter("Stopped unit {}".format(name), i, o, 1) else: PrettyPrinter("Can't stop {}".format(name), i, o, 1) raise MenuExitException
def disable_unit(name): status = systemctl.action_unit("disable", name) if status: PrettyPrinter("Disabled unit {}".format(name), i, o, 1) else: PrettyPrinter("Can't disable {}".format(name), i, o, 1) raise MenuExitException
def scan_arbitrary_ip(): ip = NumpadIPAddressInput(i, o, message="IP to scan:").activate() if ip is None: return #Cancelled valid_ip = False while not valid_ip: #Validating the IP in a loop try: ip = cleanup_validate_ip(ip) except ValueError as e: #If not valid, giving an opportunity to either fix it or cancel the scan PrettyPrinter("Invalid ip: {}! Reason: {}".format(ip, e.message), i, o, 3) ip = NumpadIPAddressInput(i, o, message="Fix the IP", value=ip).activate() if ip is None: return #Cancelled #To the next loop iteration else: valid_ip = True if "/" in ip: #Network address with a netmask, interpreting it as a network address and just calling nmap quick_scan_network_by_ip(ip) elif "*" in ip: PrettyPrinter( "Wildcards without a netmask are not yet supported by the interface, sorry", i, o, 3) return else: scan_ip(ip)
def verify_and_run(): """ If either directory that we need to read into does not exist, the filename is invalid or there is already an invalid file in that location (character device or something like that), we should warn the user and abort. If there's already a file in that location, we should make the user confirm the overwrite. """ full_path = os.path.join(self.read_dir, self.read_filename) + ".hex" if not os.path.isdir(self.read_dir): PrettyPrinter("Wrong directory!", self.i, self.o, 3) return if '/' in self.read_filename: PrettyPrinter("Filename can't contain a slash!", self.i, self.o, 3) return if os.path.exists(full_path): if os.path.isdir(full_path) or not os.path.isfile(full_path): PrettyPrinter( "Trying to overwrite something that is not a file!", self.i, self.o, 5) return choice = DialogBox( 'ync', self.i, self.o, message="Overwrite?", name="Avrdude write overwrite confirmation").activate() if not choice: return self.create_process() if self.read_checklist(): self.detect_and_run()
def reload_unit(name): status = systemctl.action_unit("reload", name) if status: PrettyPrinter("Reloaded unit {}".format(name), i, o, 1) else: PrettyPrinter("Can't reload {}".format(name), i, o, 1) raise MenuExitException
def unpin_unit(name): global config if name in config["pinned_units"]: config["pinned_units"].remove(name) write_config(config, config_path) PrettyPrinter("Unpinned unit {}".format(name), i, o, 1) else: PrettyPrinter("Error: unit {} not pinned!".format(name), i, o, 1)
def send_files(): if not config.get("uuid", None): generate_uuid() uuid = config["uuid"] cb_contents = deepcopy(log_options) if config.get("last_choices", None): last_choices = config.get("last_choices") for e in cb_contents: if e[1] in last_choices: v = last_choices[e[1]] if len(e) > 2: e[2] = v elif len(e) == 2: e.append(v) else: e.append(e[0]) e.append(v) choices = Checkbox(cb_contents, i, o, name="Checkbox for selecting logs to be sent").activate() if not choices: return config["last_choices"] = choices save_config(config) ##### DATE_STR!~ date_str = "ololo" with LoadingIndicator(i, o, message="Processing files", name="Bugreport log sending loading bar") as li: try: filename = "ZPUI_logs-{}-{}.zip".format(uuid, date_str) bugreport = BugReport(filename) selected_choices = [key for key, value in choices.items() if value] bugreport.add_text(json.dumps(selected_choices), "bugreport_choices.json") for choice in selected_choices: try: process_choice(choice, bugreport, li) except: logger.exception("Failed to process {} choice".format(choice)) bugreport.add_text(json.dumps(traceback.format_exc()), "choice_{}_failed.json".format(choice)) except: logger.exception("Failed to collect files!") li.stop() PrettyPrinter("Failed while collecting files!", i, o, 3) return try: li.message = "Sending files" bugreport.send() except: logger.exception("Failed to send files!") bugreport.add_text(json.dumps(traceback.format_exc()), "bugreport_sending_failed.json") li.stop() PrettyPrinter("Failed while sending files!", i, o, 3) try: location = bugreport.store_in("/boot/") PrettyPrinter("Stored in {}".format(location), i, o, 3) except: PrettyPrinter("Failed to store files!", i, o, 3) return else: li.stop() PrettyPrinter("Sent files successfully!", i, o, 3)
def test_keypad_presence(self): #Checking keypad controller - 0x12 should answer bus = SMBus(1) try: bus.read_byte(0x12) except IOError: PrettyPrinter("Keypad does not respond!", self.i, self.o) else: PrettyPrinter("Keypad found!", self.i, self.o)
def test_i2c_gpio(self): #Checking IO expander - 0x20 should raise IOError with busy errno self.expander_ok = False bus = SMBus(1) try: bus.read_byte(0x20) except IOError as e: if e.errno == 16: PrettyPrinter("IO expander OK!", self.i, self.o) self.expander_ok = True elif e.errno == 121: PrettyPrinter("IO expander not found!", self.i, self.o) else: PrettyPrinter("IO expander driver not loaded!", self.i, self.o)
def callback(): menu_contents = [] try: usb_devices = lsusb.lsusb() except OSError: PrettyPrinter("Do you have lsusb?", i, o, 2) return False for bus, dev, vid_pid, name in usb_devices: name = name if name else "[Unknown]" ell_name = ellipsize(name, o.cols) info = "{}\n{}".format(vid_pid, name) menu_contents.append( [["D{},B{},{}".format(bus, dev, vid_pid), ell_name], lambda x=info: PrettyPrinter(x, i, o, skippable=True)]) Menu(menu_contents, i, o, entry_height=2).activate()
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")
def test_keypad(self): #Launching key_test app from app folder, that's symlinked from example app folder PrettyPrinter("Testing keypad", self.i, self.o, 1) remove_left_failsafe(self.i) import key_test key_test.init_app(self.i, self.o) key_test.callback()
def pick_bootloader(self): """ A menu to pick the bootloader from bootloaders.json. Also records fuse information in self.write_fuse_params, where it stays until user selects another bootloader or manually selects a file by path. """ bootloader_dir = local_path("bootloaders/") config = read_config( os.path.join(bootloader_dir, self.bootloader_config_filename)) bootloader_choices = [[bootloader["name"], bootloader] for bootloader in config["bootloaders"]] if not bootloader_choices: PrettyPrinter("No bootloaders found!", self.i, self.o, 3) return choice = Listbox(bootloader_choices, self.i, self.o, name="Avrdude bootloader picker").activate() if choice: self.write_file = os.path.join(bootloader_dir, choice["file"]) self.write_fuse_params = [] for type in self.fuse_types: if type in choice: self.write_fuse_params.append( [type, choice[type], config["fuse_format"]]) self.config["last_write_file"] = self.write_file self.config["last_write_fuse_params"] = self.write_fuse_params self.save_config()
def call_external(script_list, shell=False): if shell: script_path = script_list.split(' ')[0] else: script_path = os.path.split(script_list[0])[1] Printer("Calling {}".format(script_path), i, o, 1) output = None 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_message = "Unknown error! \n \n {}".format(e) PrettyPrinter(error_message, i, o, 3) 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: TextReader(output, i, o, autohide_scrollbars=True, h_scroll=True).activate()
def take_screenshot(): image = context.get_previous_context_image() if image != None: timestamp = datetime.now().strftime("%y%m%d-%H%M%S") filename = "screenshot_{}.png".format(timestamp) path = os.path.join(screenshot_folder, filename) image.save(path, "PNG") PrettyPrinter("Screenshot saved to {}".format(path), i, o)
def callback(): """A function that's called when the app is selected in the menu""" PrettyPrinter( "Hello and welcome to Aperture Science computer aided enrichment center", i, o, sleep_time=5, skippable=True)
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")
def test_usb_port(self): from zerophone_hw import USB_DCDC eh = ExitHelper(self.i, ["KEY_LEFT", "KEY_ENTER"]).start() PrettyPrinter("Press Enter to test USB", None, self.o, 0) counter = 5 for x in range(50): if eh.do_run(): if x % 10 == 0: counter -= 1 sleep(0.1) else: break if counter > 0: PrettyPrinter( "Insert or remove a USB device \n press Enter to skip", None, self.o, 0) dcdc = USB_DCDC() dcdc.on()
def offer_retry(counter): do_reactivate = DialogBox("ync", i, o, message="Retry?").activate() if do_reactivate: PrettyPrinter("Connecting, try {}...".format(counter), i, o, 0) init.reset() init.run() wait_for_connection() callback(counter)
def change_origin_url(self): original_url = self.config["url"] url = UniversalInput(i, o, message="URL:", value=original_url).activate() if url: self.config["url"] = url self.save_config() PrettyPrinter("Saved new URL!", i, o)
def test_charger(self): #Testing charging detection PrettyPrinter("Testing charger detection", self.i, self.o, 1) from zerophone_hw import Charger charger = Charger() eh = ExitHelper(self.i, ["KEY_LEFT", "KEY_ENTER"]).start() if charger.connected(): PrettyPrinter( "Charging, unplug charger to continue \n Enter to bypass", None, self.o, 0) while charger.connected() and eh.do_run(): sleep(1) else: PrettyPrinter( "Not charging, plug charger to continue \n Enter to bypass", None, self.o, 0) while not charger.connected() and eh.do_run(): sleep(1)
def callback(counter=0): try: counter += 1 status = check_modem_connection() except: if counter < 3: PrettyPrinter("Modem connection failed =(", i, o) offer_retry(counter) else: PrettyPrinter("Modem connection failed 3 times", i, o, 1) else: if not status: PrettyPrinter("Connecting...", i, o, 0) wait_for_connection() callback(counter) else: contents = [["Status", status_refresher], ["Call", call_view]] Menu(contents, i, o).activate()
def pick_branch(self): #TODO: allow adding branches dynamically instead of having a whitelist lc = [[branch_name] for branch_name in self.config["branches"]] branch = Listbox( lc, i, o, name="Git updater branch selection listbox").activate() if branch: try: GitInterface.checkout(branch) self.check_revisions = False updated = self.update() self.check_revisions = True except: PrettyPrinter( "Couldn't check out the {} branch! Try resolving the conflict through the command-line." .format(branch), i, o, 3) else: PrettyPrinter("Now on {} branch!".format(branch), i, o, 2) self.suggest_restart()
def quick_scan_network_by_ip(ip_on_network): if ip_on_network == "None": PrettyPrinter("No IP to scan!", i, o, 2) return False network_ip = get_network_from_ip(ip_on_network) with LoadingIndicator(i, o, message=network_ip): nm = nmap.PortScanner() nm.scan(network_ip, arguments="-sn") show_quick_scan_results_for_network(network_ip, nm)
def test_headphone_jack(self): #Testing audio jack sound PrettyPrinter("Testing audio jack", self.i, self.o, 1) if self.br: if self.br.running: PrettyPrinter( "Audio jack test music not yet downloaded, waiting...", None, self.o, 0) eh = ExitHelper(self.i, ["KEY_LEFT", "KEY_ENTER"]).start() while self.br.running and eh.do_run(): sleep(0.1) if eh.do_exit(): return elif self.br.failed: PrettyPrinter("Failed to download test music!", self.i, self.o, 1) disclaimer = [ "Track used:" "", "Otis McDonald", "-", "Otis McMusic", "YT AudioLibrary" ] Printer([s.center(self.o.cols) for s in disclaimer], self.i, self.o, 3) PrettyPrinter("Press C1 to restart music, C2 to continue testing", self.i, self.o) import pygame pygame.mixer.init() pygame.mixer.music.load(music_path) pygame.mixer.music.play() continue_event = Event() def restart(): pygame.mixer.music.stop() pygame.mixer.init() pygame.mixer.music.load(music_path) pygame.mixer.music.play() def stop(): pygame.mixer.music.stop() continue_event.set() self.i.clear_keymap() self.i.set_callback("KEY_F1", restart) self.i.set_callback("KEY_F2", stop) self.i.set_callback("KEY_ENTER", stop) continue_event.wait()
def callback(): global refresher, keys_called keys_called = [] i.set_streaming(process_key) refresher = Refresher(get_keys, i, o, 1, name="Key monitor") refresher.keymap.pop( "KEY_LEFT") #Removing deactivate callback to show KEY_LEFT PrettyPrinter("To exit this app, press the same key 3 times", i, o) refresher.activate() i.remove_streaming()
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: PrettyPrinter("Timeout has to be larger than 0!", i, o)
def on_start(self): if not self.check_avrdude_available(): PrettyPrinter("Avrdude not available!", self.i, self.o, 3) return mc = [["Read chip", self.read_menu], ["Write chip", self.write_menu], ["Erase chip", self.erase_menu], ["Pick programmer", self.pick_programmer], ["Pick chip", self.pick_chip], ["Pinouts", lambda: graphics.show_pinouts(self.i, self.o)], ["Settings", self.settings_menu]] Menu(mc, self.i, self.o, name="Avrdude app main menu").activate()
def full_test(self): try: self.test_keypad_presence() self.test_i2c_gpio() self.test_screen() self.test_keypad() self.test_charger() self.test_rgb_led() self.test_usb_port() self.test_headphone_jack() except: logger.exception("Failed during full self-test") exc = format_exc() PrettyPrinter(exc, self.i, self.o, 10) else: PrettyPrinter("Self-test passed!", self.i, self.o, 3, skippable=False)
def callback(): if systemctl is None: PrettyPrinter( "python-gi not found! Please install it using 'apt-get install python-gi' ", i, o, 5) return try: systemctl.list_units() except OSError as e: if e.errno == 2: PrettyPrinter("Do you use systemctl?", i, o, 3, skippable=True) return else: raise e main_menu_contents = [["Pinned units", pinned_units], ["Units (filtered)", filtered_units], ["All units", all_units], ["Change filters", change_filters]] main_menu = Menu(main_menu_contents, i, o, "systemctl main menu") main_menu.activate()