Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 11 additions & 10 deletions BlocksScreen/BlocksScreen.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,10 @@
import sys
import typing

import logger
from lib.panels.mainWindow import MainWindow
from logger import setup_logging
from PyQt6 import QtCore, QtGui, QtWidgets

_logger = logging.getLogger(name="logs/BlocksScreen.log")
QtGui.QGuiApplication.setAttribute(
QtCore.Qt.ApplicationAttribute.AA_SynthesizeMouseForUnhandledTouchEvents,
True,
Expand All @@ -22,13 +21,6 @@
RESET = "\033[0m"


def setup_app_loggers():
"""Setup logger"""
_ = logger.create_logger(name="logs/BlocksScreen.log", level=logging.DEBUG)
_logger = logging.getLogger(name="logs/BlocksScreen.log")
_logger.info("============ BlocksScreen Initializing ============")


def show_splash(window: typing.Optional[QtWidgets.QWidget] = None):
"""Show splash screen on app initialization"""
logo = QtGui.QPixmap("BlocksScreen/BlocksScreen/lib/ui/resources/logoblocks.png")
Expand All @@ -39,7 +31,16 @@ def show_splash(window: typing.Optional[QtWidgets.QWidget] = None):


if __name__ == "__main__":
setup_app_loggers()
setup_logging(
filename="logs/BlocksScreen.log",
level=logging.DEBUG, # File gets DEBUG+
console_output=True, # Print to terminal
console_level=logging.DEBUG, # Console gets DEBUG+
capture_stderr=True, # Capture X11 errors
capture_stdout=False, # Don't capture print()
)
_logger = logging.getLogger(__name__)
_logger.info("============ BlocksScreen Initializing ============")
BlocksScreen = QtWidgets.QApplication([])
BlocksScreen.setApplicationName("BlocksScreen")
BlocksScreen.setApplicationDisplayName("BlocksScreen")
Expand Down
14 changes: 8 additions & 6 deletions BlocksScreen/configfile.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@

from helper_methods import check_file_on_path

logger = logging.getLogger(__name__)

HOME_DIR = os.path.expanduser("~/")
WORKING_DIR = os.getcwd()
DEFAULT_CONFIGFILE_PATH = pathlib.Path(HOME_DIR, "printer_data", "config")
Expand Down Expand Up @@ -253,9 +255,9 @@ def add_section(self, section: str) -> None:
self.config.add_section(section)
self.update_pending = True
except configparser.DuplicateSectionError as e:
logging.error(f'Section "{section}" already exists. {e}')
logger.error(f'Section "{section}" already exists. {e}')
except configparser.Error as e:
logging.error(f'Unable to add "{section}" section to configuration: {e}')
logger.error(f'Unable to add "{section}" section to configuration: {e}')

def add_option(
self,
Expand Down Expand Up @@ -283,9 +285,9 @@ def add_option(
self.config.set(section, option, value)
self.update_pending = True
except configparser.DuplicateOptionError as e:
logging.error(f"Option {option} already present on {section}: {e}")
logger.error(f"Option {option} already present on {section}: {e}")
except configparser.Error as e:
logging.error(
logger.error(
f'Unable to add "{option}" option to section "{section}": {e} '
)

Expand All @@ -301,7 +303,7 @@ def save_configuration(self) -> None:
self.config.write(sio)
sio.close()
except Exception as e:
logging.error(
logger.error(
f"ERROR: Unable to save new configuration, something went wrong while saving updated configuration. {e}"
)
finally:
Expand Down Expand Up @@ -386,6 +388,6 @@ def get_configparser() -> BlocksScreenConfig:
config_object = BlocksScreenConfig(configfile=configfile, section="server")
config_object.load_config()
if not config_object.has_section("server"):
logging.error("Error loading configuration file for the application.")
logger.error("Error loading configuration file for the application.")
raise ConfigError("Section [server] is missing from configuration")
return BlocksScreenConfig(configfile=configfile, section="server")
8 changes: 5 additions & 3 deletions BlocksScreen/lib/machine.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@

from PyQt6 import QtCore

logger = logging.getLogger(__name__)


class MachineControl(QtCore.QObject):
service_restart = QtCore.pyqtSignal(str, name="service-restart")
Expand Down Expand Up @@ -67,10 +69,10 @@ def _run_command(self, command: str):
)
return p.stdout.strip() + "\n" + p.stderr.strip()
except ValueError as e:
logging.error("Failed to parse command string '%s': '%s'", command, e)
logger.error("Failed to parse command string '%s': '%s'", command, e)
raise RuntimeError(f"Invalid command format: {e}") from e
except subprocess.CalledProcessError as e:
logging.error(
logger.error(
"Caught exception (exit code %d) failed to run command: %s \nStderr: %s",
e.returncode,
command,
Expand All @@ -82,4 +84,4 @@ def _run_command(self, command: str):
subprocess.TimeoutExpired,
FileNotFoundError,
):
logging.error("Caught exception failed to run command %s", command)
logger.error("Caught exception failed to run command %s", command)
2 changes: 1 addition & 1 deletion BlocksScreen/lib/moonrakerComm.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
from lib.utils.RepeatedTimer import RepeatedTimer
from PyQt6 import QtCore, QtWidgets

_logger = logging.getLogger(name="logs/BlocksScreen.log")
_logger = logging.getLogger(__name__)


class OneShotTokenError(Exception):
Expand Down
4 changes: 3 additions & 1 deletion BlocksScreen/lib/moonrest.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@
import requests
from requests import Request, Response

logger = logging.getLogger(__name__)


class UncallableError(Exception):
"""Raised when a method is not callable"""
Expand Down Expand Up @@ -145,4 +147,4 @@ def _request(
return response.json() if json_response else response.content

except Exception as e:
logging.info(f"Unexpected error while sending HTTP request: {e}")
logger.info(f"Unexpected error while sending HTTP request: {e}")
36 changes: 18 additions & 18 deletions BlocksScreen/lib/network.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
from PyQt6 import QtCore
from sdbus_async import networkmanager as dbusNm

logger = logging.getLogger("logs/BlocksScreen.log")
logger = logging.getLogger(__name__)


class NetworkManagerRescanError(Exception):
Expand Down Expand Up @@ -87,7 +87,7 @@ def _listener_run_loop(self) -> None:
asyncio.set_event_loop(self.loop)
self.loop.run_until_complete(asyncio.gather(self.listener_monitor()))
except Exception as e:
logging.error(f"Exception on loop coroutine: {e}")
logger.error(f"Exception on loop coroutine: {e}")

async def _end_tasks(self) -> None:
for task in self.listener_task_queue:
Expand All @@ -105,7 +105,7 @@ def close(self) -> None:
try:
future.result(timeout=5)
except Exception as e:
logging.info(f"Exception while ending loop tasks: {e}")
logger.info(f"Exception while ending loop tasks: {e}")
self.stop_listener_event.set()
self.loop.call_soon_threadsafe(self.loop.stop)
self.listener_thread.join()
Expand All @@ -132,7 +132,7 @@ async def listener_monitor(self) -> None:
await self.stop_listener_event.wait()

except Exception as e:
logging.error(f"Exception on listener monitor produced coroutine: {e}")
logger.error(f"Exception on listener monitor produced coroutine: {e}")

async def _nm_state_listener(self) -> None:
while self._listeners_running:
Expand All @@ -141,17 +141,17 @@ async def _nm_state_listener(self) -> None:
enum_state = dbusNm.NetworkManagerState(state)
self.nm_state_change.emit(enum_state.name)
except Exception as e:
logging.error(f"Exception on Network Manager state listener: {e}")
logger.error(f"Exception on Network Manager state listener: {e}")

async def _nm_properties_listener(self) -> None:
while self._listeners_running:
try:
logging.debug("Listening for Network Manager state change")
logger.debug("Listening for Network Manager state change")
async for properties in self.nm.properties_changed:
self.nm_properties_change.emit(properties)

except Exception as e:
logging.error(f"Exception on Network Manager state listener: {e}")
logger.error(f"Exception on Network Manager state listener: {e}")

def check_nm_state(self) -> typing.Union[str, None]:
"""Check NetworkManager state"""
Expand All @@ -162,7 +162,7 @@ def check_nm_state(self) -> typing.Union[str, None]:
state_value = future.result(timeout=2)
return str(dbusNm.NetworkManagerState(state_value).name)
except Exception as e:
logging.error(f"Exception while fetching Network Monitor State: {e}")
logger.error(f"Exception while fetching Network Monitor State: {e}")
return None

def check_connectivity(self) -> str:
Expand Down Expand Up @@ -191,7 +191,7 @@ def check_connectivity(self) -> str:
connectivity = future.result(timeout=2)
return dbusNm.NetworkManagerConnectivityState(connectivity).name
except Exception as e:
logging.error(
logger.error(
f"Exception while fetching Network Monitor Connectivity State: {e}"
)
return ""
Expand Down Expand Up @@ -225,7 +225,7 @@ def get_available_interfaces(self) -> typing.Union[typing.List[str], None]:
interfaces.append(interface_name)
return interfaces
except Exception as e:
logging.error(f"Exception on fetching available interfaces: {e}")
logger.error(f"Exception on fetching available interfaces: {e}")

def wifi_enabled(self) -> bool:
"""Returns a boolean if wireless is enabled on the device.
Expand Down Expand Up @@ -321,15 +321,15 @@ def toggle_hotspot(self, toggle: bool) -> None:
dbusNm.NetworkManagerConnectivityState.FULL
| dbusNm.NetworkManagerConnectivityState.LIMITED
):
logging.debug(f"Hotspot AP {self.hotspot_ssid} up!")
logger.debug(f"Hotspot AP {self.hotspot_ssid} up!")

return
else:
if self.old_ssid:
self.connect_network(self.old_ssid)
return
except Exception as e:
logging.error(f"Caught Exception while toggling hotspot to {toggle}: {e}")
logger.error(f"Caught Exception while toggling hotspot to {toggle}: {e}")

def hotspot_enabled(self) -> typing.Optional["bool"]:
"""Returns a boolean indicating whether the device hotspot is on or not .
Expand Down Expand Up @@ -437,7 +437,7 @@ def get_current_ssid(self) -> str:
future = asyncio.run_coroutine_threadsafe(self._gather_ssid(), self.loop)
return future.result(timeout=5)
except Exception as e:
logging.info(f"Unexpected error occurred: {e}")
logger.info(f"Unexpected error occurred: {e}")
return ""

def get_current_ip_addr(self) -> str:
Expand All @@ -451,7 +451,7 @@ def get_current_ip_addr(self) -> str:
)
primary_con = primary_con_fut.result(timeout=2)
if primary_con == "/":
logging.info("There is no NetworkManager active connection.")
logger.info("There is no NetworkManager active connection.")
return ""

_device_ip4_conf_path = dbusNm.ActiveConnection(
Expand All @@ -462,7 +462,7 @@ def get_current_ip_addr(self) -> str:
)

if _device_ip4_conf_path == "/":
logging.info(
logger.info(
"NetworkManager reports no IP configuration for the interface"
)
return ""
Expand Down Expand Up @@ -1312,7 +1312,7 @@ def delete_network(self, ssid: str) -> None:
if not isinstance(ssid, str):
raise TypeError("SSID argument is of type string")
if not self.is_known(ssid):
logging.debug(f"No known network with SSID {ssid}")
logger.debug(f"No known network with SSID {ssid}")
return
try:
self.deactivate_connection_by_ssid(ssid)
Expand All @@ -1324,7 +1324,7 @@ def delete_network(self, ssid: str) -> None:
if isinstance(result, Exception):
raise Exception(result)
except Exception as e:
logging.debug(f"Caught Exception while deleting network {ssid}: {e}")
logger.debug(f"Caught Exception while deleting network {ssid}: {e}")

def get_hotspot_ssid(self) -> str:
"""Get current hotspot ssid"""
Expand Down Expand Up @@ -1426,7 +1426,7 @@ def create_hotspot(
self.loop.run_until_complete(task)

except Exception as e:
logging.error(f"Caught Exception while creating hotspot: {e}")
logger.error(f"Caught Exception while creating hotspot: {e}")

def set_network_priority(
self, ssid: str, priority: ConnectionPriority = ConnectionPriority.LOW
Expand Down
23 changes: 9 additions & 14 deletions BlocksScreen/lib/panels/mainWindow.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,14 @@
from lib.panels.networkWindow import NetworkControlWindow
from lib.panels.printTab import PrintTab
from lib.panels.utilitiesTab import UtilitiesTab
from lib.panels.widgets.basePopup import BasePopup
from lib.panels.widgets.connectionPage import ConnectionPage
from lib.panels.widgets.loadWidget import LoadingOverlayWidget
from lib.panels.widgets.cancelPage import CancelPage
from lib.panels.widgets.popupDialogWidget import Popup
from lib.panels.widgets.updatePage import UpdatePage
from lib.printer import Printer
from lib.ui.mainWindow_ui import Ui_MainWindow # With header
from lib.panels.widgets.updatePage import UpdatePage
from lib.panels.widgets.basePopup import BasePopup
from lib.panels.widgets.loadWidget import LoadingOverlayWidget

# from lib.ui.mainWindow_v2_ui import Ui_MainWindow # No header
from lib.ui.resources.background_resources_rc import *
Expand All @@ -29,10 +29,11 @@
from lib.ui.resources.main_menu_resources_rc import *
from lib.ui.resources.system_resources_rc import *
from lib.ui.resources.top_bar_resources_rc import *
from logger import LogManager
from PyQt6 import QtCore, QtGui, QtWidgets
from screensaver import ScreenSaver

_logger = logging.getLogger(name="logs/BlocksScreen.log")
_logger = logging.getLogger(__name__)


def api_handler(func):
Expand Down Expand Up @@ -724,19 +725,13 @@ def set_header_nozzle_diameter(self, diam: str):

def closeEvent(self, a0: typing.Optional[QtGui.QCloseEvent]) -> None:
"""Handles GUI closing"""
_loggers = [
logging.getLogger(name) for name in logging.root.manager.loggerDict
] # Get available logger handlers
for logger in _loggers: # noqa: F402
if hasattr(logger, "cancel"):
_callback = getattr(logger, "cancel")
if callable(_callback):
_callback()

# Shutdown logger (closes files, stops threads, restores streams)
LogManager.shutdown()

self.ws.wb_disconnect()
self.close()
if a0 is None:
return
QtWidgets.QMainWindow.closeEvent(self, a0)
super().closeEvent(a0)

def event(self, event: QtCore.QEvent) -> bool:
Expand Down
13 changes: 3 additions & 10 deletions BlocksScreen/lib/panels/networkWindow.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,7 @@
import logging
import threading
from functools import partial
from typing import (
Any,
Callable,
Dict,
List,
NamedTuple,
Optional,
)
from typing import Any, Callable, Dict, List, NamedTuple, Optional

from lib.network import SdbusNetworkManagerAsync
from lib.panels.widgets.keyboardPage import CustomQwertyKeyboard
Expand All @@ -25,7 +18,7 @@
from PyQt6 import QtCore, QtGui, QtWidgets
from PyQt6.QtCore import QObject, QRunnable, QThreadPool, pyqtSignal

logger = logging.getLogger("logs/BlocksScreen.log")
logger = logging.getLogger(__name__)


LOAD_TIMEOUT_MS = 30_000
Expand Down Expand Up @@ -2757,7 +2750,7 @@ def connect_and_refresh():

def _handle_failed_network_add(self, error_msg: str) -> None:
"""Handle failed network addition."""
logging.error(error_msg)
logger.error(error_msg)
error_messages = {
"Invalid password": "Invalid password. Please try again",
"Network connection properties error": (
Expand Down
Loading