Exemple #1
0
def stop_systemd_service(service_name: str):
    try:
        run_command(
            f"systemctl stop {service_name}", timeout=20, check=False, log_errors=False
        )
    except Exception:
        pass
Exemple #2
0
 def _is_doc_package_installed(self):
     try:
         run_command("dpkg -l python3-pitop-doc",
                     timeout=3,
                     check=True,
                     log_errors=False)
         return True
     except Exception:
         return False
Exemple #3
0
    def print_dmesg(self):
        try:
            dmesg = run_command("dmesg", timeout=10)
        except Exception:
            dmesg = "Error reading dmesg"

        for line in dmesg.split("\n"):
            StdoutFormat.print_line(line)
Exemple #4
0
 def __get_online_sdk_docs_url(self):
     try:
         return (self.ONLINE_BASE_URI + "en/v" +
                 run_command("dpkg -s python3-pitop",
                             timeout=10,
                             check=True,
                             log_errors=False).split("\n")[8].split()[1])
     except Exception:
         return self.ONLINE_BASE_URI
Exemple #5
0
def get_systemd_active_state(service_name: str):
    try:
        state = run_command(
            f"systemctl is-active {service_name}", timeout=10, log_errors=False
        )
        state = str(state.strip())
    except Exception:
        state = "Unknown Error"
    finally:
        return state
Exemple #6
0
    def print_raspberry_pi_device_info(self):
        data_arr = [
            ("Device", f"{run_command('cat /proc/device-tree/model', timeout=2)}"),
            ("Architecture", f"{uname().machine}"),
        ]

        t = StdoutTable()
        t.add_section("Raspberry Pi Device Information", data_arr)
        t.print()

        if device_type() == DeviceName.pi_top_4.value:
            StdoutFormat.print_subsection("Raspberry Pi 4 Bootloader Configuration")
            eeprom_info = run_command("sudo rpi-eeprom-config", timeout=5, check=False)
            print(f"{eeprom_info.strip()}")
            StdoutFormat.print_subsection("Raspberry Pi 4 EEPROM Information")
            eeprom_info = run_command("sudo rpi-eeprom-update", timeout=5, check=False)
            print(f"{eeprom_info.strip()}")
            StdoutFormat.print_subsection("VideoCore GPU Detailed Configuration")
            self.print_vcgenmod_settings()
Exemple #7
0
 def print_vcgenmod_settings(self):
     t = StdoutTable()
     data_arr = []
     for description, command in self.VCGENMOD_SETTINGS.items():
         try:
             result = run_command(command, timeout=1)
             result = result.strip().replace("\n", "; ")
         except Exception:
             result = "Error retrieving information"
         data_arr.append([description, result])
     t.print_data(data_arr)
Exemple #8
0
def touchscreen_is_connected():
    """Checks if pi-top touchscreen is connected to the device."""
    resp = run_command("lsusb", timeout=3)
    for line in resp.split("\n"):
        fields = line.split(" ")
        if len(fields) < 6:
            continue
        device_id = fields[5]
        if device_id == "222a:0001":
            return True

    return False
Exemple #9
0
def pitop_keyboard_is_connected():
    """Checks if pi-top keyboard is connected to the device."""
    resp = run_command("lsusb", timeout=3)
    for line in resp.split("\n"):
        fields = line.split(" ")
        if len(fields) < 6:
            continue
        device_id = fields[5]
        if device_id == "1c4f:0063":
            return True

    return False
def get_user_using_display(display_no):
    """Returns the name of the user that is currently using the defined
    display.

    Returns:
            user (str): String representing the user
    """
    from pitop.common.command_runner import run_command

    user = None
    for line in run_command("who", timeout=1).split("\n"):
        if "(%s)" % display_no in line:
            fields = line.split(" ")
            if len(fields) > 1:
                user = fields[0]
                break
    return user
Exemple #11
0
def get_ap_mode_status():
    key_lookup = {
        "State": "state",
        "Access Point Network SSID": "ssid",
        "Access Point Wi-Fi Password": "******",
        "Access Point IP Address": "ip_address",
    }

    data = {}
    try:
        ap_mode_status = run_command("/usr/bin/wifi-ap-sta status", timeout=10)
        for str in ap_mode_status.strip().split("\n"):
            k, v = str.split(":")
            key = key_lookup.get(k.strip())
            if key:
                data[key] = v.strip()
    except Exception:
        pass
    return data
Exemple #12
0
def is_connected_to_internet() -> bool:
    try:
        run_command("ping -c1 8.8.8.8", timeout=2, check=True, log_errors=False)
        return True
    except Exception:
        return False
Exemple #13
0
 def command_succeeds(cmd, timeout):
     try:
         run_command(cmd, timeout=timeout, check=True, log_errors=False)
         return True
     except Exception:
         return False
Exemple #14
0
 def get_raspi_config_setting_value(self, setting):
     try:
         return run_command(f"raspi-config nonint {setting}", timeout=5).strip()
     except Exception:
         return "Error getting setting"
Exemple #15
0
def send_notification(
    title: str,
    text: str,
    icon_name: str = "",
    timeout: int = 0,
    app_name: str = "",
    notification_id: int = -1,
    actions_manager: NotificationActionManager = None,
    urgency_level: NotificationUrgencyLevel = None,
    capture_notification_id: bool = True,
) -> str:

    # Check that `notify-send-ng` is available, as it's not a hard dependency of the package
    try:
        run(["dpkg-query", "-l", "notify-send-ng"],
            capture_output=True,
            check=True)
    except CalledProcessError:
        raise Exception("notify-send-ng not installed")

    cmd = "/usr/bin/notify-send "
    cmd += "--print-id "
    cmd += "--expire-time=" + str(timeout) + " "

    if icon_name:
        cmd += "--icon=" + icon_name + " "

    if notification_id >= 0:
        cmd += "--replace=" + str(notification_id) + " "

    if actions_manager is not None:
        for action in actions_manager.actions:
            cmd += ('--action="' + action.call_to_action_text + ":" +
                    action.command_str + '" ')

        if actions_manager.default_action is not None:
            cmd += ("--default-action=" +
                    actions_manager.default_action.command_str + " ")

        if actions_manager.close_action is not None:
            cmd += "--close-action=" + actions_manager.close_action.command_str + " "

    if app_name:
        cmd += "--app-name=" + app_name + " "

    if urgency_level is not None:
        cmd += "--urgency=" + urgency_level.name + " "

    cmd += ' "' + title + '" '
    cmd += '"' + text + '"'

    logger.info("notify-send command: {}".format(cmd))

    try:
        resp_stdout = run_command(cmd,
                                  2000,
                                  capture_output=capture_notification_id)
    except Exception as e:
        logger.warning("Failed to show message: {}".format(e))
        raise
    return resp_stdout
Exemple #16
0
def change_wifi_mode():
    if get_wifi_ap_state() == "Enabled":
        run_command("/usr/bin/wifi-ap-sta stop", timeout=30)
        run_command("/usr/bin/wifi-ap-sta disable", timeout=30)
    else:
        run_command("/usr/bin/wifi-ap-sta start", timeout=30)