def add_secret(): global config name = UniversalInput(i, o, message="Name").activate() if name is None: return secret = UniversalInput(i, o, message="Secret").activate() if secret is None: return config["secrets"].append([name, secret]) save_config(config)
def set_password(id): input = UniversalInput(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)
def call_command(): command = UniversalInput(i, o, message="Command:", name="Script command input").activate() if command is None: return call_external(command, shell=True)
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 edit_password(net_id): conf_fail = False try: conf_data = read_conf_data.read_data() except: conf_data = {} conf_fail = True ssid = wpa_cli.get_network(net_id, "ssid") conf = conf_data.get(ssid, None) if not conf: if conf_fail: Printer( "Configuration file can't be read, can't get current password!", i, o) else: Printer( "Network not found in the configuration file, can't get current password!", i, o) psk = "" else: psk = conf.get("psk", "") if not psk: if conf.get("key_mgmt", None) == "NONE": result = DialogBox("yn", i, o, message="Is open, edit?").activate() if not result: return psk = "" else: # weird, no psk in file # using an empty string for now psk = "" input = UniversalInput(i, o, value=psk, message="Password:"******"WiFi password enter UI element") password = input.activate() if password is None: return False wpa_cli.set_network(net_id, 'psk', '"{}"'.format(password)) wpa_cli.save_config() Printer("Password entered", i, o, 1)
def write_message(self, room): message = UniversalInput(self.i, self.o, message="Message", name="Matrix app message input").activate() if message is None: return False # Send the message to the room and display it for a short amount of time room.send_text(message)
def login_with_username(self): # Get the required user data username = UniversalInput( self.i, self.o, message="Enter username", name="Matrix app username dialog").activate() if not username: return False displayname = username # Create a matrix user id from the username and server from the config username = "******".format(username, self.server) password = UniversalInput(self.i, self.o, message="Enter password", name="Matrix app password dialog", charmap="password").activate() if not password: return False # Show a beautiful loading animation while setting everything up with LoadingIndicator(self.i, self.o, message="Logging in ...") as l: self.client = Client(username, password=password, server=self.server) # Store username and token if self.client.logged_in: self.config['user_id'] = username self.config['token'] = self.client.get_token() self.config['displayname'] = displayname self.save_config() logger.info("Succesfully logged in") return True else: with l.paused: Printer("Failed to log in", self.i, self.o) return False
def call_by_path(): path = PathPicker("/", i, o).activate() if path is None: return args = UniversalInput(i, o, message="Arguments:", name="Script argument input").activate() if args is not None: path = path + " " + args call_external(path, shell=True)
def call_command(command=None): if not command: command = UniversalInput(i, o, message="Command:", name="Script command input").activate() if not command: return call_external(command, shell=True) if command not in config["history"]: config["history"] = [command] + config["history"] save_config(config)
def connect_to_network(network_info): #First, looking in the known networks configured_networks = wpa_cli.list_configured_networks() for network in configured_networks: if network_info['ssid'] == network['ssid']: Printer([network_info['ssid'], "known,connecting"], i, o, 1) wpa_cli.enable_network(network['network id']) wpa_cli.save_config() raise MenuExitException #Then, if it's an open network, just connecting if wpa_cli.is_open_network(network_info): network_id = wpa_cli.add_network() Printer(["Network is open", "adding to known"], i, o, 1) ssid = network_info['ssid'] wpa_cli.set_network(network_id, 'ssid', '"{}"'.format(ssid)) wpa_cli.set_network(network_id, 'key_mgmt', 'NONE') Printer(["Connecting to", network_info['ssid']], i, o, 1) wpa_cli.enable_network(network_id) wpa_cli.save_config() raise MenuExitException #Offering to enter a password else: input = UniversalInput(i, o, message="Password:"******"WiFi password enter UI element") password = input.activate() if password is None: return False network_id = wpa_cli.add_network() Printer(["Password entered", "adding to known"], i, o, 1) ssid = network_info['ssid'] wpa_cli.set_network(network_id, 'ssid', '"{}"'.format(ssid)) wpa_cli.set_network(network_id, 'psk', '"{}"'.format(password)) Printer(["Connecting to", network_info['ssid']], i, o, 1) wpa_cli.enable_network(network_id) wpa_cli.save_config() raise MenuExitException
def set_filename(self, attr_name, config_option_name, message="Filename:"): """ A convenience wrapper for setting filenames. For now, is only used for "read_filename". """ original_value = getattr(self, attr_name) value = original_value if original_value else "" filename = UniversalInput(self.i, self.o, message=message, value=value).activate() if filename: setattr(self, attr_name, filename) self.config[config_option_name] = filename self.save_config() return True
def i2c_read_ui(address, reg=None): global last_values if reg == True: reg = UniversalInput(i, o, message="Register:", charmap="hex").activate() if reg is None: # User picked "cancel" return if isinstance(reg, basestring): reg = int(reg, 16) last_values = [] values_on_screen = o.cols def read_value( ): # A helper function to read a value and format it into a list global last_values try: if reg: answer = "{} {}".format( hex(reg), hex(current_bus.read_byte_data(address, reg))) else: answer = hex(current_bus.read_byte(address)) except IOError: answer = "{} error".format(reg) if reg else "error" last_values.append(answer) last_values = last_values[:values_on_screen] return list(reversed(last_values)) r = Refresher(read_value, i, o) def change_interval( ): # A helper function to adjust the Refresher's refresh interval while it's running new_interval = IntegerAdjustInput( r.refresh_interval, i, o, message="Refresh interval:").activate() if new_interval is not None: r.set_refresh_interval(new_interval) r.update_keymap({"KEY_RIGHT": change_interval}) r.activate()
def test_zerophone(self): """tests whether UniversalInput works on ZeroPhone""" ui = UniversalInput(get_mock_input("zerophone"), get_mock_output(), name=ui_name) self.assertIsInstance(ui, NumpadCharInput)
def main(): link = UniversalInput(i, o, message="URL:", name="URL input").activate() get_request(link)
def test_ascii_keyboard(self): """test whether UniversalInput works on an ascii keyboard""" ui = UniversalInput(get_mock_input("ascii_keyboard"), get_mock_output(), name=ui_name) self.assertIsInstance(ui, NumpadKeyboardInput)
def test_hardpass(self): """tests whether UniversalInput works on Hardpass""" ui = UniversalInput(get_mock_input("hardpass"), get_mock_output(), name=ui_name) self.assertIsInstance(ui, CharArrowKeysInput)
def test_adafruit_oled_bonnet(self): """tests whether UniversalInput works on Adafruit OLED Bonnet""" ui = UniversalInput(get_mock_input("adafruit_oledbonnet"), get_mock_output(), name=ui_name) self.assertIsInstance(ui, CharArrowKeysInput)
def connect_to_network(network_info): #First, looking in the known networks configured_networks = wpa_cli.list_configured_networks() known = False # flag that avoids going through the whole "enter password" # thing if the network is known for network in configured_networks: if network_info['ssid'] == network['ssid']: Printer(network_info['ssid'] + " known, connecting", i, o, 1) wpa_cli.enable_network(network['network id']) wpa_cli.save_config() known = True #Then, if it's an open network, just connecting if not known and wpa_cli.is_open_network(network_info): network_id = wpa_cli.add_network() Printer("Network is open, adding to known", i, o, 1) ssid = network_info['ssid'] wpa_cli.set_network(network_id, 'ssid', '"{}"'.format(ssid)) wpa_cli.set_network(network_id, 'key_mgmt', 'NONE') Printer("Connecting to " + network_info['ssid'], i, o, 1) wpa_cli.enable_network(network_id) wpa_cli.save_config() #Offering to enter a password elif not known: input = UniversalInput(i, o, message="Password:"******"WiFi password enter UI element", charmap="password") password = input.activate() if password is None: return False network_id = wpa_cli.add_network() Printer("Password entered, adding to known", i, o, 1) ssid = network_info['ssid'] wpa_cli.set_network(network_id, 'ssid', '"{}"'.format(ssid)) wpa_cli.set_network(network_id, 'psk', '"{}"'.format(password)) Printer("Connecting to " + network_info['ssid'], i, o, 1) wpa_cli.enable_network(network_id) wpa_cli.save_config() #No WPS PIN input possible yet and I cannot yet test WPS button functionality. # Setup finished. Now let's check if we're actually connected # If we're not, we'll do stuff to try and ensure a connection status = wpa_cli.connection_status() current_ssid = status.get('ssid', 'None') # We might init a LoadingBar, here's a variable to refer to it later lb = None # we might disable networks, need to re-enable them once we're connected disabled_networks = [] # also, in the "WiFi wizard" menu, we need to return some kind of status connect_status = {"connected": False, "reason": None} if current_ssid and current_ssid == network_info["ssid"]: # We seem to be connected! logger.info( "right ssid in status instantly, seems like we're connected ") connect_status["connected"] = True connect_status["reason"] = "instant_connect" logger.info("new connect_status: {}".format(connect_status)) else: # Entering the "do something until we're actually connected" phase # first - let's start a LoadingBar for user-friendliness # and record the time we started connecting, for the same =) do_exit = Event() lb = LoadingBar(i, o, message="Connecting...", on_left=do_exit.set) lb.run_in_background() start_time = time() # don't want to waste time waiting for scan results scan_has_been_initiated = False # second - we'll be monitoring events, so that we're a bit more efficient # and we don't need to go through a bunch of old events => flush monitor.flush_status() # third - let's do enable_temp_disabled_networks enable_temp_disabled_networks() # fourth - let's check if we're currently connected to another network # if so - we should disable it connected = False while not connected and not do_exit.isSet(): if current_ssid != network_info["ssid"]: status = wpa_cli.connection_status() current_ssid = status.get('ssid', None) # what if a race condition happens? # lol while current_ssid not in [None, network_info["ssid"]]: unwanted_net_id = status.get("id", None) unwanted_net_ssid = status.get("ssid", None) if unwanted_net_id is not None: logger.info( "Disabling unwanted network: {} (id: {})".format( unwanted_net_ssid, unwanted_net_id)) wpa_cli.disable_network(unwanted_net_id) disabled_networks.append(unwanted_net_id) else: # connected to a network but id is not present in the status? # weird. logger.warning( "Network connected but id is not available! Status: {}" .format(status)) # calling the "disconnect" function # but first, let's check if we're really really not connected yet # we're in a weird place already if try_scan(): scan_has_been_initiated = True status = wpa_cli.connection_status() current_ssid = status.get('ssid', None) if current_ssid not in [None, network_info["ssid"]]: try: wpa_cli.disconnect() except: logger.exception( "and we can't disconnect from the network, either" ) else: # all is good, it seems if current_ssid == network_info["ssid"]: connected = True logger.info( "ssid is set after 'disconnect', seems like we're connected" ) connect_status["connected"] = True connect_status[ "reason"] = "ssid_check_after_disconnect_unknown_id" logger.info("new connect_status: {}".format( connect_status)) break logger.info( "Disconnecting from wrong network {}: trying scan". format(unwanted_net_ssid)) if try_scan(): scan_has_been_initiated = True logger.info( "Disconnecting from wrong network {}: getting status". format(unwanted_net_ssid)) status = wpa_cli.connection_status() current_ssid = status.get('ssid', None) # we might've gotten connected after the "while current_ssid is wrong" loop if current_ssid == network_info["ssid"]: #connected = True # commented out because sometimes, when pw is wrong, # it will connect for a second and then disconnect logger.debug( "ssid is set, we *might* be connected (ssid: {}, status: {})" .format(current_ssid, status)) net_status = monitor.pop_status() if net_status: logger.info( "Connecting: received status from monitor: {}".format( net_status)) code = net_status.get("code", "") wrong_pw = False if code == "CTRL-EVENT-CONNECTED": net_id = net_status["data"].get("id", None) network_cache = wpa_cli.dict_configured_networks_by_id() if network_cache[str( net_id)]["ssid"] == network_info["ssid"]: # yay! logger.info( "received a CONNECTED event, seems like we're connected" ) connected = True connect_status["connected"] = True connect_status["reason"] = "got_connected_status" logger.info( "new connect_status: {}".format(connect_status)) break elif code == "CTRL-EVENT-DISCONNECTED": reason = net_status["data"].get("reason", None) wanted_bssid = network_info["bssid"] bssid = net_status["data"].get("bssid", None) logger.info(" ".join([reason, bssid, wanted_bssid])) if (bssid and bssid == wanted_bssid) and reason in [ "2", "3" ]: logger.info( "received a DISCONNECTED event with what seems like a 'WRONG PASSWORD' code" ) wrong_pw = True elif code == "CTRL-EVENT-SSID-TEMP-DISABLED": reason = net_status["data"].get("reason", None) wanted_ssid = network_info["ssid"] ssid = net_status["data"].get("ssid", None) logger.info(" ".join([reason, ssid, wanted_ssid])) if (ssid and ssid == wanted_ssid) and reason == "WRONG_KEY": logger.info( "received a SSID-TEMP-DISABLED event with what seems like a 'WRONG PASSWORD' reason" ) wrong_pw = True elif code == "CTRL-EVENT-SCAN-RESULTS": status = wpa_cli.connection_status() current_ssid = status.get('ssid', None) if current_ssid is None: # we're not connected to anything available_networks = wpa_cli.get_scan_results() for a_network in available_networks: if a_network["ssid"] == network_info["ssid"]: # desired network is present in the network search results # let's call "wpa_cli reconnect" # in hopes that triggers a connection logger.info( "We're not connected but network is present in scan results, calling 'wpa_cli reconnect'" ) wpa_cli.reconnect() break else: # break didn't trigger - network is no longer there? connect_status["connected"] = False connect_status["reason"] = "network_lost" logger.info("new connect_status: {}".format( connect_status)) break if wrong_pw: lb.stop() while lb.is_active: sleep(0.1) lb = None logger.info( "Wrong password, seems like we're not getting connected!" ) Printer("Wrong password?", i, o, 3) connect_status["connected"] = False connect_status["reason"] = "wrong_password" logger.info( "new connect_status: {}".format(connect_status)) break # fifth - we should check if the network is still available - that is, # can be found in scan results # so, let's trigger the scan and wait for the results to come # if network is available and we're not connected to anything, # we'll receive CTRL-EVENT-SCAN-RESULTS and then do further action # in the status processing code above if not scan_has_been_initiated: # this flag can be set in the "disabling other networks" code if try_scan(): scan_has_been_initiated = True # sixth - we should check if we haven't timeouted yet, by any chance ;-P now_time = time() if now_time - start_time > connect_timeout: lb.stop() while lb.is_active: sleep(0.1) lb = None logger.info( "Connection timeout, seems like we're not getting connected!" ) Printer("Connect timeout!", i, o, 3) connect_status["connected"] = False connect_status["reason"] = "timeout" logger.info("new connect_status: {}".format(connect_status)) break if lb: # LoadingBar was created, stopping it lb.stop() # re-enabling all the networks we previously disabled for net_id in disabled_networks: logger.info( "Re-enabling network {} that was disabled during connection". format(net_id)) wpa_cli.enable_network(net_id) if callable(wifi_connect_status_cb): wifi_connect_status_cb(connect_status) logger.info("end connect_status: {}".format(connect_status)) raise MenuExitException