### Load connection from config file Source: https://github.com/prusa3d/prusa-connect-sdk-printer/blob/master/README.rst Use connection_from_config() to read server and token directly from the .ini file, then start the communication loop. ```python printer.connection_from_config("./prusa_printer_settings.ini") printer.loop() # Communication loop ``` -------------------------------- ### Set connection and start communication loop Source: https://github.com/prusa3d/prusa-connect-sdk-printer/blob/master/README.rst Configure the connection using server and token from prusa_printer_settings.ini, then start the communication loop with printer.loop(). ```python SERVER = "https://connect.prusa3d.com" TOKEN = "Secret token from prusa_printer_settings.ini" printer.set_connection(SERVER, TOKEN) printer.loop() # Communication loop ``` -------------------------------- ### Usage example via Printer as Connect commands Source: https://github.com/prusa3d/prusa-connect-sdk-printer/blob/master/_autodocs/api-reference/download.md Shows how the download manager is handled automatically when the default handler is wired, with the printer.loop() running in a thread and the download loop started separately. The comments document the Connect commands (START_URL_DOWNLOAD, START_CONNECT_DOWNLOAD, STOP_TRANSFER, SEND_TRANSFER_INFO) that are handled automatically. ```python # Handled automatically when the default handler is wired: # START_URL_DOWNLOAD {"path": "/usb/file.gcode", "url": "https://...", "printing": false, "selecting": false} # START_CONNECT_DOWNLOAD {"team_id": ..., "hash": ..., "path": "/usb/x.gcode"} # STOP_TRANSFER # SEND_TRANSFER_INFO printer.loop() # in a thread Thread(target=printer.download_mgr.loop).start() # run the download loop ``` -------------------------------- ### start method signature Source: https://github.com/prusa3d/prusa-connect-sdk-printer/blob/master/_autodocs/api-reference/download.md Starts a new transfer with the given type, path, and optional parameters. Validates the basename and raises exceptions if invalid; raises TransferRunningError if a transfer is already in progress. ```python def start(self, type_: TransferType, path: str, url: Optional[str] = None, to_print: Optional[bool] = None, to_select: Optional[bool] = None, start_cmd_id: Optional[int] = None, hash_: Optional[str] = None, team_id: Optional[int] = None) -> dict: """Set a new transfer type, if no transfer is in progress""" ``` -------------------------------- ### Basic setup and loop (from README.rst) Source: https://github.com/prusa3d/prusa-connect-sdk-printer/blob/master/_autodocs/api-reference/printer.md Initializes a Printer instance with a serial number, fingerprint, and printer type, sets the connection to Prusa Connect, and starts the printer loop in a separate thread. Requires the prusa.connect.printer package and a valid token or settings file. ```python from hashlib import sha256 from threading import Thread from prusa.connect.printer import Printer, const SN = "Printer serial number" FINGERPRINT = sha256(SN.encode()).hexdigest() PRINTER_TYPE = const.PrinterType.I3MK3 printer = Printer(PRINTER_TYPE, SN, FINGERPRINT) printer.set_connection("https://connect.prusa3d.com", "token") # or: printer.connection_from_config("./prusa_printer_settings.ini") thread = Thread(target=printer.loop) thread.start() ``` -------------------------------- ### Communication loop with command handling Source: https://github.com/prusa3d/prusa-connect-sdk-printer/blob/master/README.rst Starts a thread for the communication loop and runs the command handler every 100 ms. The loop only creates and parametrizes the command instance; the handler must be called in another thread. ```python # Communication loop thread = Thread(target=printer.loop) thread.start() # Set printer state to READY. printer.set_state(const.State.READY, const.Source.CONNECT) # Try run command handler each 100 ms while True: printer.command() sleep(0.1) ``` -------------------------------- ### Create Printer instance with constructor Source: https://github.com/prusa3d/prusa-connect-sdk-printer/blob/master/README.rst Instantiate a Printer by passing printer type, serial number, and fingerprint. For I3MK3 and SL1, the fingerprint is a SHA256 HEX digest of the serial number. ```python from prusa.connect.printer import Printer, const SN = "Printer serial number" FINGERPRINT = sha256(SN.encode()).hexdigest() PRINTER_TYPE = const.PrinterType.I3MK3 printer = Printer(PRINTER_TYPE, SN, FINGERPRINT) ``` -------------------------------- ### Transfer.start() Source: https://github.com/prusa3d/prusa-connect-sdk-printer/blob/master/_autodocs/api-reference/download.md Starts a file transfer. Raises TransferRunningError if a transfer is already in progress. ```APIDOC ## Transfer.start() ### Description Starts a file transfer. Raises TransferRunningError if a transfer is already in progress. ### Method start() ### Parameters None ### Returns None ### Exceptions - **TransferRunningError** - Raised when a transfer is already in progress and `Transfer.start` is called again. ``` -------------------------------- ### Start snapshot loop and manage cameras Source: https://github.com/prusa3d/prusa-connect-sdk-printer/blob/master/_autodocs/api-reference/camera_controller.md Shows how to start the snapshot loop in a background thread and use the CameraController methods to set camera order, register a camera, and trigger layer changes. The Printer already owns a CameraController accessible via printer.camera_controller. ```python from threading import Thread # The Printer already owns a CameraController: # printer.camera_controller Thread(target=printer.camera_controller.snapshot_loop).start() printer.camera_controller.set_camera_order([camera_id]) printer.camera_controller.register_camera(camera_id) # POST /p/camera printer.camera_controller.layer_trigger() # from firmware layer-change hook ``` -------------------------------- ### DownloadMgr.start Source: https://github.com/prusa3d/prusa-connect-sdk-printer/blob/master/_autodocs/api-reference/download.md Starts a new transfer (download) from a web URL or Connect. Returns a dictionary with transfer details or a rejection event if a transfer is already running. ```APIDOC ## DownloadMgr.start ### Description Starts a new transfer (download) from a web URL or Connect. Returns a dictionary with transfer details or a rejection event if a transfer is already running. ### Method start ### Signature mgr.start(transfer_type, path, url=None, to_print=False) ### Parameters - **transfer_type** (const.TransferType) - Required - Type of transfer (e.g., FROM_WEB) - **path** (str) - Required - Destination path on the printer filesystem (e.g., "/usb/benchy.gcode") - **url** (str) - Optional - Source URL for web downloads - **to_print** (bool) - Optional - Whether to print after download (default: False) ### Returns - **retval** (dict) - Contains transfer_id, progress, and other transfer details. If rejected, contains "event" and "reason". ### Errors - **ValueError** - Invalid arguments - **ForbiddenCharactersError** - Path contains forbidden characters - **FilenameTooLongError** - Filename too long - **TransferRunningError** - Another transfer is already in progress (converted to a reject dict) ### Example ```python retval = mgr.start(const.TransferType.FROM_WEB, path="/usb/benchy.gcode", url="https://example.com/benchy.gcode", to_print=False) ``` ``` -------------------------------- ### Usage example with RetryingSession and make_fingerprint Source: https://github.com/prusa3d/prusa-connect-sdk-printer/blob/master/_autodocs/api-reference/util.md Shows how to create a RetryingSession and POST a registration request with a fingerprint. The session retries on connection errors up to max_retries. ```python from prusa.connect.printer.util import RetryingSession, make_fingerprint session = RetryingSession(max_retries=3) res = session.post("https://connect.prusa3d.com/p/register", json={"sn": "CZPX1234", "fingerprint": fingerprint}, timeout=10) ``` -------------------------------- ### Filesystem scan, detach, and lookup Source: https://github.com/prusa3d/prusa-connect-sdk-printer/blob/master/_autodocs/api-reference/files.md Shows how to create a Filesystem instance with a separator and event callback, scan a directory, detach a storage, and perform a generic node lookup. The get() call returns None if the node is not found; check is_dir before treating it as a file. ```python from prusa.connect.printer.files import Filesystem fs = Filesystem(sep="/", event_cb=printer.event_cb) fs.from_dir("/tmp/usb", "usb") # scans and attaches # later, on storage change: fs.detach("usb") # generic lookup node = fs.get("/usb/benchy.gcode") if node is not None and not node.is_dir: print(node.to_dict()) ``` -------------------------------- ### Camera usage example Source: https://github.com/prusa3d/prusa-connect-sdk-printer/blob/master/_autodocs/api-reference/camera.md Shows how to create a Camera instance with a CameraDriver subclass, set trigger scheme, resolution, and rotation, then take a photo. Setting an unsupported trigger scheme raises NotSupported. ```python from prusa.connect.printer.camera import Camera camera = Camera(driver) # driver: CameraDriver subclass camera.trigger_scheme = TriggerScheme.SIXTY_SEC # raises NotSupported if unsupported camera.resolution = camera.available_resolutions.pop() camera.rotation = 90 snapshot = camera.take_a_photo() # blocks until photo arrives ``` -------------------------------- ### DownloadMgr.start method signature Source: https://github.com/prusa3d/prusa-connect-sdk-printer/blob/master/_autodocs/api-reference/download.md Starts a download with the same signature as Transfer.start. It calls self.transfer.start(...) and returns a rejected dict if TransferRunningError is raised, then translates the virtual path and creates the parent directory. ```python def start(self, type_: TransferType, path: str, url: Optional[str] = None, to_print: Optional[bool] = None, to_select: Optional[bool] = None, start_cmd_id: Optional[int] = None, hash_: Optional[str] = None, team_id: Optional[int] = None) -> dict: ``` -------------------------------- ### get_settings() Source: https://github.com/prusa3d/prusa-connect-sdk-printer/blob/master/_autodocs/api-reference/camera.md Gets the object representation of settings for conversion. Returns object-form settings for all configurable capabilities plus name, plus token when registered. ```APIDOC ## get_settings() ### Description Gets the object representation of settings for conversion. ### Method get_settings ### Parameters None ### Returns - **Dict[str, Any]** - Object-form settings. ### Source `camera.py:539` ``` -------------------------------- ### Toggle printer state with set_state Source: https://github.com/prusa3d/prusa-connect-sdk-printer/blob/master/README.rst Change the printer state between READY and BUSY each second using printer.set_state with the MARLIN source. ```python from threading import Thread from time import sleep ... # Start communication loop thread = Thread(target=printer.loop) thread.start() # Toggle the state each second while True: if printer.state == const.State.READY: printer.set_state(const.State.BUSY, const.Source.MARLIN) elif printer.state == const.State.BUSY: printer.set_state(const.State.READY, const.Source.MARLIN) sleep(1) ``` -------------------------------- ### get_settings method Source: https://github.com/prusa3d/prusa-connect-sdk-printer/blob/master/_autodocs/api-reference/camera.md Gets the object representation of settings for conversion. Returns object-form settings for all configurable_capabilities plus name, plus token when registered. ```python def get_settings(self): """Gets the object representation of settings for conversion""" ``` -------------------------------- ### Command handler with START_PRINT and STOP_PRINT Source: https://github.com/prusa3d/prusa-connect-sdk-printer/blob/master/README.rst Handlers for START_PRINT and STOP_PRINT commands. Each handler must return a dictionary with at least the 'source' key. The 'event' key is required if overriding the default FINISHED event. Additional data is passed via the 'data' key. ```python from threading import Thread from time import sleep ... @printer.handler(const.Command.START_PRINT) def start_print(args: list[str]): """This handler will be called when START_PRINT command was sent to the printer.""" printer.set_state(const.State.READY, const.Source.CONNECT) print("Printing file: {args[0]}") ... @printer.handler(const.Command.STOP_PRINT) def start_print(args: list[str]): """This handler will be called when STOP_PRINT command was sent to the printer.""" printer.set_state(const.State.READY, const.Source.CONNECT) print("Printing stopped") ... ``` -------------------------------- ### Usage example for ClockWatcher Source: https://github.com/prusa3d/prusa-connect-sdk-printer/blob/master/_autodocs/api-reference/clock.md Shows how to use ClockWatcher: create an instance, check if clock was adjusted, and reset after detection. In the SDK, Printer.make_headers() automatically adds Clock-Adjusted header and resets the watcher. ```python from prusa.connect.printer.clock import ClockWatcher watcher = ClockWatcher() # ... time passes, the system clock is stepped ... if watcher.clock_adjusted(): print("system clock was adjusted") watcher.reset() ``` -------------------------------- ### _get_initial_resolution static method Source: https://github.com/prusa3d/prusa-connect-sdk-printer/blob/master/_autodocs/api-reference/camera_driver.md Gets the configured resolution and validates it; falls back to the highest available on TypeError/ValueError or when not available. Parsed via Camera.settings_from_string. ```python @staticmethod def _get_initial_resolution(available_resolutions, config): """Gets the configured resolution and validates it, if invalid gives the highest possible one""" ``` -------------------------------- ### DownloadMgr.loop Source: https://github.com/prusa3d/prusa-connect-sdk-printer/blob/master/_autodocs/api-reference/download.md Runs the download loop in a separate thread to process transfers. Must be started to handle downloads. ```APIDOC ## DownloadMgr.loop ### Description Runs the download loop in a separate thread to process transfers. Must be started to handle downloads. ### Method loop ### Signature DownloadMgr.loop() ### Parameters None ### Usage ```python Thread(target=printer.download_mgr.loop).start() ``` ``` -------------------------------- ### Register printer and wait for token Source: https://github.com/prusa3d/prusa-connect-sdk-printer/blob/master/README.rst Register an unregistered printer by obtaining a temporary code and waiting until the token is assigned. For I3MK3, the Add Printer form does not allow manual code entry; use the provided URL instead. ```python from time import sleep from prusa.connect.printer import Printer, const SERVER = "https://connect.prusa3d.com" SN = "Printer serial number" FINGERPRINT = "Printer fingerprint" PRINTER_TYPE = const.PrinterType.I3MK3 printer = Printer(PRINTER_TYPE, SN, FINGERPRINT) printer.set_connection(SERVER, None) tmp_code = printer.register() print(f"Use this code `{tmp_code}` in add printer form " f"{SERVER}/printers/overview?code={tmp_code}.") while printer.token is None: print("Waiting for the printer registration on the Connect web...") sleep(1) print(f"Printer is registered with token {printer.token}") ``` -------------------------------- ### Usage of handler decorator Source: https://github.com/prusa3d/prusa-connect-sdk-printer/blob/master/_autodocs/api-reference/printer.md Example of using the handler decorator to register a handler for START_PRINT. The handler must return a dictionary containing the 'source' key. ```python @printer.handler(const.Command.START_PRINT) def start_print(caller: Command): """Handler called when START_PRINT was sent to the printer.""" printer.set_state(const.State.PRINTING, const.Source.CONNECT) return {'source': const.Source.CONNECT} # must contain source ``` -------------------------------- ### get method Source: https://github.com/prusa3d/prusa-connect-sdk-printer/blob/master/_autodocs/api-reference/files.md Returns the node identified by parts. Raises TypeError when parts is a plain string. parts == [""] returns self; walks children; returns None for missing nodes. ```python def get(self, parts: typing.Iterable[str]): """Return the node identified by `parts` ...""" ``` -------------------------------- ### snapshot_loop method Source: https://github.com/prusa3d/prusa-connect-sdk-printer/blob/master/_autodocs/api-reference/camera_controller.md Infinite loop (until stop()) that gets an item Snapshot from the queue and sends it. Waits TIMESTAMP_PRECISION on the queue, sends via Snapshot.send(self.session, self.server). Handles HTTP 401/403 (authorization error, resets camera token), >400 (warning log), ==400 (debug log), Empty (continue), and generic exceptions (log with traceback). Run in its own thread. ```python def snapshot_loop(self) -> None: """Gets an item Snapshot from queue and sends it""" ``` -------------------------------- ### Initialize CameraConfigurator and manage cameras Source: https://github.com/prusa3d/prusa-connect-sdk-printer/blob/master/_autodocs/api-reference/camera_configurator.md Shows how to create a CameraConfigurator with a ConfigParser, a camera controller, a config file path, a list of driver classes, and auto-detection. Then demonstrates ordering cameras with set_order() and resetting a camera to defaults with reset_to_defaults(). ```python from configparser import ConfigParser from prusa.connect.printer.camera_configurator import CameraConfigurator config = ConfigParser() config.read("/etc/prusalink/prusalink.ini") configurator = CameraConfigurator( camera_controller=printer.camera_controller, config=config, config_file_path="/etc/prusalink/prusalink.ini", drivers=[MyCameraDriver], # list of your driver classes auto_detect=True, ) # order cameras: [cam_a, cam_b, ...] configurator.set_order(["cam_b_id", "cam_a_id"]) # factory reset a camera's settings configurator.reset_to_defaults("cam_a_id") ``` -------------------------------- ### DownloadMgr.download method signature Source: https://github.com/prusa3d/prusa-connect-sdk-printer/blob/master/_autodocs/api-reference/download.md Executes the download and stores the file in self.tmp_filename(). Sets start timestamp, gets connection details, validates URL and content type, streams to a .part file, and raises TransferAbortedError for invalid status, content type, or empty response. ```python def download(self): """Execute the download and store the file in `self.tmp_filename()`""" ``` -------------------------------- ### name property Source: https://github.com/prusa3d/prusa-connect-sdk-printer/blob/master/_autodocs/api-reference/camera.md Property for getting and setting the camera name. ```APIDOC ## name property ### Description Property for the camera name. Getter returns `driver.config["name"]`; setter calls `driver.set_name(name)`. ### Getter Returns the camera name. ### Setter - **value** (str) - Required - The new camera name. - Calls `driver.set_name(name)`. ``` -------------------------------- ### focus property Source: https://github.com/prusa3d/prusa-connect-sdk-printer/blob/master/_autodocs/api-reference/camera.md Property for getting and setting the focus capability. ```APIDOC ## focus property ### Description Property for the focus capability. Getter returns the current focus; setter validates and sets the focus on the driver. ### Getter Returns the current focus. ### Setter - **value** (float) - Required - The new focus value. - Raises `ValueError` unless `0 <= focus <= 1`. - Calls `driver.set_focus`. ``` -------------------------------- ### exposure property Source: https://github.com/prusa3d/prusa-connect-sdk-printer/blob/master/_autodocs/api-reference/camera.md Property for getting and setting the exposure capability. ```APIDOC ## exposure property ### Description Property for the exposure capability. Getter returns the current exposure; setter validates and sets the exposure on the driver. ### Getter Returns the current exposure. ### Setter - **value** (float) - Required - The new exposure value. - Raises `ValueError` unless `-2 <= exposure <= 2`. - Calls `driver.set_exposure`. ``` -------------------------------- ### Camera.__init__(driver) Source: https://github.com/prusa3d/prusa-connect-sdk-printer/blob/master/_autodocs/api-reference/camera.md Constructor for the Camera class, initializing the camera with a driver and validating required capabilities. ```APIDOC ## Camera.__init__(driver) ### Description Initializes a Camera instance with the given driver, loading available resolutions and settings. ### Parameters - **driver** (CameraDriver) - Required - The driver for the physical camera. ### Behavior - Raises `AttributeError("Be sure to fill out driver supported capabilities. TRIGGER_SCHEME is the bare minimum")` when the driver does not declare `CapabilityType.TRIGGER_SCHEME`. - When the driver supports `RESOLUTION`, loads `_available_resolutions` from it. - Merges `DEFAULT_CAMERA_SETTINGS` (deep copy) with the driver's config parsed via `settings_from_string`. - Raises `AttributeError` when required settings (for `configurable_capabilities`) are missing from the merged defaults. - Applies `set_settings(initial_settings, store=False)`. - Registers callbacks: `scheme_cb = lambda camera, old, new: None` and `photo_cb = lambda snapshot: None`; wires `driver.photo_cb = self._photo_handler`. ``` -------------------------------- ### store() Source: https://github.com/prusa3d/prusa-connect-sdk-printer/blob/master/_autodocs/api-reference/camera.md Stores the current settings using the driver's store_settings method. ```APIDOC ## store() ### Description Stores the current settings using the driver's store_settings method. ### Method store ### Parameters None ### Source `camera.py:552` ``` -------------------------------- ### rotation property Source: https://github.com/prusa3d/prusa-connect-sdk-printer/blob/master/_autodocs/api-reference/camera.md Property for getting and setting the rotation capability. ```APIDOC ## rotation property ### Description Property for the rotation capability. Getter returns the current rotation; setter validates and sets the rotation on the driver. ### Getter Returns the current rotation. ### Setter - **value** (int) - Required - The new rotation in degrees. - Raises `ValueError(f"Rotation of {n}° is not allowed")` unless in `{0, 90, 180, 270}`. - Calls `driver.set_rotation`. ``` -------------------------------- ### Module Singletons Source: https://github.com/prusa3d/prusa-connect-sdk-printer/blob/master/_autodocs/errors.md The module provides singleton instances `INTERNET`, `HTTP`, `TOKEN`, and `API` that form a chain where each `prev` points to the more fundamental one. These are updated in parallel with the `conditions` module. ```APIDOC ## Module Singletons ### Description The module provides singleton instances `INTERNET`, `HTTP`, `TOKEN`, and `API` that form a chain where each `prev` points to the more fundamental one. These are updated in parallel with the `conditions` module. ### Singletons - **INTERNET** - Represents the internet connectivity state. - **HTTP** - Represents the HTTP connection state. - **TOKEN** - Represents the token state. - **API** - Represents the API state. ### Usage Each singleton has an `ok` attribute that can be set to `True` or `False` to indicate the state. For example, `errors.API.ok = False` wherever `API.state = CondState.NOK`. ``` -------------------------------- ### resolution property Source: https://github.com/prusa3d/prusa-connect-sdk-printer/blob/master/_autodocs/api-reference/camera.md Property for getting and setting the resolution capability. ```APIDOC ## resolution property ### Description Property for the resolution capability. Getter returns the current resolution; setter validates and sets the resolution on the driver. ### Getter Returns the current resolution. ### Setter - **value** (Resolution) - Required - The new resolution. - Raises `ValueError(f"Resolution {r} is not available")` if the resolution is not in `available_resolutions`. - Calls `driver.set_resolution(resolution)`. ``` -------------------------------- ### trigger_scheme property Source: https://github.com/prusa3d/prusa-connect-sdk-printer/blob/master/_autodocs/api-reference/camera.md Property for getting and setting the trigger scheme capability. ```APIDOC ## trigger_scheme property ### Description Property for the trigger scheme capability. Getter returns the current value; setter validates and stores the new value, calling `scheme_cb(self, old, new)`. ### Getter Returns the current trigger scheme. ### Setter - **value** (Any) - Required - The new trigger scheme value. - Calls `scheme_cb(self, old, new)` then stores the value. ``` -------------------------------- ### File.abs_path Source: https://github.com/prusa3d/prusa-connect-sdk-printer/blob/master/_autodocs/api-reference/files.md Joins the absolute path parts with a prefix, normalised to start with the OS separator. ```APIDOC ## File.abs_path ### Description Joins the absolute path parts with a prefix, normalised to start with the OS separator. ### Method abs_path(prefix) ### Parameters - **prefix** (str) - Required - Prefix to prepend to the path ### Response #### Success Response - **str** - The absolute path string ``` -------------------------------- ### Filesystem.from_dir method Source: https://github.com/prusa3d/prusa-connect-sdk-printer/blob/master/_autodocs/api-reference/files.md Initializes a file tree from a directory path and attaches it. Used by Printer.attach. ```python def from_dir(self, dirpath: str, storage: str): """Initialize a (File) tree from `dirpath` and attach it.""" ``` -------------------------------- ### value_getter(capability_type) Source: https://github.com/prusa3d/prusa-connect-sdk-printer/blob/master/_autodocs/api-reference/camera.md Decorator for methods that get a camera option, raising an error if the capability is unsupported. ```APIDOC ## value_getter(capability_type) ### Description A decorator for methods getting a camera option. ### Parameters - **capability_type** (CapabilityType) - Required - The capability type being retrieved. ### Behavior Raises `NotSupported(f"The camera {name} does not support {TYPE.name}")` when the capability is unsupported, then returns the underlying getter result. ``` -------------------------------- ### Filesystem.get_os_path method Source: https://github.com/prusa3d/prusa-connect-sdk-printer/blob/master/_autodocs/api-reference/files.md Gets the OS file path for the given absolute path. Raises KeyError if the storage is unknown. ```python def get_os_path(self, abs_path): """Gets the OS file path of the file specified by abs_path""" ``` -------------------------------- ### RetryingSession.get(*args, **kw) Source: https://github.com/prusa3d/prusa-connect-sdk-printer/blob/master/_autodocs/api-reference/util.md Performs an HTTP GET request with retry on ConnectionError. Uses call_and_retry to wrap the underlying requests.Session.get. ```APIDOC ## RetryingSession.get(*args, **kw) ### Description Performs an HTTP GET request with retry on ConnectionError. Uses call_and_retry to wrap the underlying requests.Session.get. ### Parameters - **args** - Optional - Positional arguments passed to requests.Session.get (e.g., URL). - **kw** - Optional - Keyword arguments passed to requests.Session.get (e.g., timeout). ### Returns - **response** (requests.Response) - The response object. ### Raises - **requests.exceptions.ConnectionError** - After max_retries attempts. ### Example ```python import requests session = RetryingSession(max_retries=3) try: res = session.get("https://connect.prusa3d.com/p/telemetry", timeout=10) except requests.exceptions.ConnectionError as err: print("giving up:", err) ``` ``` -------------------------------- ### string_from_settings(src_settings) Source: https://github.com/prusa3d/prusa-connect-sdk-printer/blob/master/_autodocs/api-reference/camera.md Inverse to settings_from_string: converts settings to string representation. trigger_scheme becomes .name. ```APIDOC ## string_from_settings(src_settings) ### Description Inverse to settings_from_string: converts settings to string representation. ### Method string_from_settings ### Parameters - **src_settings** - Settings to convert. ### Returns - **Dict[str, str]** - String representation of settings. ### Source `camera.py:505` ``` -------------------------------- ### value_getter decorator definition Source: https://github.com/prusa3d/prusa-connect-sdk-printer/blob/master/_autodocs/api-reference/camera.md Decorator for methods getting a camera option. Raises NotSupported when the capability is unsupported. ```python def value_getter(capability_type): """A decorator for methods getting a camera option""" ``` -------------------------------- ### wait_ready(timeout=None) Source: https://github.com/prusa3d/prusa-connect-sdk-printer/blob/master/_autodocs/api-reference/camera.md Waits for the camera to become ready, raising an error if it times out. ```APIDOC ## wait_ready(timeout=None) ### Description Waits for the camera to become ready. Raises `ReadyTimeoutError` if the camera does not become ready within the timeout. ### Parameters - **timeout** (float, optional) - The maximum time to wait in seconds. Defaults to `None`. ### Raises - `ReadyTimeoutError(f"The camera {self.camera_id} did not become ready in time.")` when `_ready_event` isn't set within `timeout`. ``` -------------------------------- ### CameraDriver._get_initial_resolution(available_resolutions, config) Source: https://github.com/prusa3d/prusa-connect-sdk-printer/blob/master/_autodocs/api-reference/camera_driver.md Static method that gets the configured resolution and validates it, falling back to the highest available if invalid. ```APIDOC ## CameraDriver._get_initial_resolution(available_resolutions, config) ### Description Static method that gets the configured resolution and validates it, falling back to the highest available if invalid. ### Parameters - **available_resolutions** (list) - List of available resolutions. - **config** (dict) - Configuration dictionary containing the resolution setting. ### Returns - The initial resolution to use. ``` -------------------------------- ### File.parent property Source: https://github.com/prusa3d/prusa-connect-sdk-printer/blob/master/_autodocs/api-reference/files.md Gets or sets the parent node. The getter returns a weakref proxy; the setter wraps the new parent in weakref.proxy. ```APIDOC ## File.parent property ### Description Gets or sets the parent node. The getter returns a weakref proxy; the setter wraps the new parent in weakref.proxy. ### Method Property getter/setter ### Parameters - **value** (File) - Optional - The new parent node ### Response #### Success Response - **parent** (File) - The parent node as a weakref proxy ### Response Example ```python parent = file.parent ``` ``` -------------------------------- ### Direct use of DownloadMgr and Transfer Source: https://github.com/prusa3d/prusa-connect-sdk-printer/blob/master/_autodocs/api-reference/download.md Directly instantiates Transfer and DownloadMgr, then calls mgr.start() with a FROM_WEB transfer type. Catches ValueError, ForbiddenCharactersError, and FilenameTooLongError on failure; on success, retval already contains transfer_id/progress/... and is printed. ```python from prusa.connect.printer.download import DownloadMgr, Transfer, TransferRunningError from prusa.connect.printer import const transfer = Transfer() mgr = DownloadMgr(printer.fs, transfer, printer.get_connection_details, printer.event_cb, printer.printed_file_cb, printer.download_finished_cb) try: retval = mgr.start( const.TransferType.FROM_WEB, path="/usb/benchy.gcode", url="https://example.com/benchy.gcode", to_print=False) except (ValueError, ForbiddenCharactersError, FilenameTooLongError) as err: print("cannot start:", err) else: # retval already contains transfer_id/progress/... print(retval) ``` -------------------------------- ### Storage.__init__ Source: https://github.com/prusa3d/prusa-connect-sdk-printer/blob/master/_autodocs/api-reference/files.md Initializes a Storage object representing a storage on the virtual filesystem. It requires a root File node and a storage name, with optional physical path and inotify watching. ```APIDOC ## Storage.__init__ ### Description Initializes a Storage object representing a storage on the virtual filesystem. It requires a root File node and a storage name, with optional physical path and inotify watching. ### Method Constructor ### Signature ```python Storage(tree: File, storage: str, abs_path_storage: Optional[str] = None, use_inotify: bool = True) ``` ### Parameters - **tree** (File) - Required - Root node of the tree - **storage** (str) - Required - Storage name on the virtual FS - **abs_path_storage** (Optional[str]) - Optional - Absolute path on physical storage - **use_inotify** (bool) - Optional - Watch this storage with inotify ### Raises - `ValueError` when `use_inotify` is true without `abs_path_storage` set. ``` -------------------------------- ### File.__init__ Source: https://github.com/prusa3d/prusa-connect-sdk-printer/blob/master/_autodocs/api-reference/files.md Initializes a File node representing a file or folder in a filesystem tree. ```APIDOC ## File.__init__ ### Description Initializes a File node representing a file or folder in a filesystem tree. ### Method Constructor ### Parameters - **name** (str) - Required - Node name - **is_dir** (bool) - Optional - Folder flag (default: False) - **parent** (Optional[File]) - Optional - Parent node (stored as a weakref.proxy to avoid reference loops) - **attrs** (**kwargs) - Optional - Arbitrary attributes; to_dict() picks up read_only and m_timestamp ### Request Example ```python file = File(name="example.txt", is_dir=False, parent=None, read_only=False, m_timestamp=1234567890) ``` ``` -------------------------------- ### trigger(snapshot=None) Source: https://github.com/prusa3d/prusa-connect-sdk-printer/blob/master/_autodocs/api-reference/camera_driver.md Triggers a photo capture. If no snapshot is provided, a new Snapshot is created with the camera_id filled. Starts a daemon thread running _photo_taker. ```APIDOC ## trigger(snapshot=None) ### Description Triggers a photo capture. ### Method trigger ### Parameters - **snapshot** (Snapshot, optional) - Optional - The snapshot to use; if None, a new Snapshot is created with camera_id filled. ### Behavior Creates a Snapshot if None, starts a daemon Thread running `_photo_taker`. ``` -------------------------------- ### Printer command loop with START_PRINT and STOP_PRINT handlers Source: https://github.com/prusa3d/prusa-connect-sdk-printer/blob/master/_autodocs/api-reference/command.md Sets up a Printer instance, registers command handlers for START_PRINT and STOP_PRINT, and runs the command loop in a background thread. The START_PRINT handler sets the state to PRINTING and prints the file path from caller.args[0]; STOP_PRINT sets state to READY. The loop calls printer.command() every 100 ms. ```python from threading import Thread from time import sleep from prusa.connect.printer import Printer, const printer = Printer(const.PrinterType.I3MK3, SN, FINGERPRINT) printer.set_connection("https://connect.prusa3d.com", TOKEN) @printer.handler(const.Command.START_PRINT) def start_print(caller): """Called when START_PRINT command arrives.""" printer.set_state(const.State.PRINTING, const.Source.CONNECT) print("Printing file:", caller.args[0]) return {"source": const.Source.CONNECT} @printer.handler(const.Command.STOP_PRINT) def stop_print(caller): printer.set_state(const.State.READY, const.Source.CONNECT) return {"source": const.Source.CONNECT} Thread(target=printer.loop).start() printer.set_state(const.State.READY, const.Source.CONNECT) # Try to run the command handler each 100 ms while True: printer.command() sleep(0.1) ``` -------------------------------- ### Filesystem.from_dir Source: https://github.com/prusa3d/prusa-connect-sdk-printer/blob/master/_autodocs/api-reference/files.md Initializes a file tree from a directory path and attaches it under a storage name. Used by Printer.attach. ```APIDOC ## Filesystem.from_dir ### Description Initializes a file tree from a directory path and attaches it under a storage name. Used by Printer.attach. ### Method Method ### Signature ```python from_dir(dirpath: str, storage: str) ``` ### Parameters - **dirpath** (str) - Required - Directory path to walk - **storage** (str) - Required - Storage name to attach under ``` -------------------------------- ### Filesystem class constructor Source: https://github.com/prusa3d/prusa-connect-sdk-printer/blob/master/_autodocs/api-reference/files.md Initializes a Filesystem object with a path separator and optional event callback. The event callback is typically Printer.event_cb and enables event enqueuing. ```python class Filesystem: """Model a collection of Files ... flat like the DOS filesystem ...""" def __init__(self, sep: str = "/", event_cb: Optional[EventCallback] = None): ``` -------------------------------- ### Generic get_value and set_value methods Source: https://github.com/prusa3d/prusa-connect-sdk-printer/blob/master/_autodocs/api-reference/camera.md Generic methods to get or set a camera capability by its CapabilityType, using getattr/setattr on the property named by capability_type.value. ```python def get_value(self, capability_type: CapabilityType): ... def set_value(self, capability_type: CapabilityType, value: Any): ... ``` -------------------------------- ### Condition.state (property) Source: https://github.com/prusa3d/prusa-connect-sdk-printer/blob/master/_autodocs/api-reference/conditions.md Gets or sets the condition state. Setting to UNKNOWN raises ValueError; setting to OK or NOK fires the appropriate handlers. ```APIDOC ## state (property) ### Description Gets or sets the condition state. Setting to UNKNOWN raises ValueError; setting to OK or NOK fires the appropriate handlers. ### Method state (getter/setter) ### Parameters (setter) - **value** (CondState) - Required - The new state. Must be OK or NOK. ### Errors - **ValueError** - "Can't reset a condition to unknown" if setting to UNKNOWN. ``` -------------------------------- ### settings_from_string(src_settings) Source: https://github.com/prusa3d/prusa-connect-sdk-printer/blob/master/_autodocs/api-reference/camera.md Converts string config values to proper types. trigger_scheme via TriggerScheme[name] with fallback to default on KeyError, resolution "WxH" to Resolution, rotation to int, exposure/focus to float. ```APIDOC ## settings_from_string(src_settings) ### Description Converts string config values to proper types. ### Method settings_from_string ### Parameters - **src_settings** (Dict[str, str]) - Dictionary of string settings. ### Returns - **Dict[str, Any]** - Converted settings. ### Source `camera.py:452` ``` -------------------------------- ### RetryingSession get and post methods Source: https://github.com/prusa3d/prusa-connect-sdk-printer/blob/master/_autodocs/api-reference/util.md Override requests.Session.get and post to retry on ConnectionError. RequestException/ReadTimeoutError are not retried by this class; Printer.loop_step exception handling reports them as HTTP/INTERNET condition failures. ```python def get(self, *args, **kw): return self.call_and_retry(super().get, *args, **kw) def post(self, url, data=None, json=None, **kw): kw['data'] = data kw['json'] = json return self.call_and_retry(super().post, url, **kw) ``` -------------------------------- ### Handle duplicate broke handler registration Source: https://github.com/prusa3d/prusa-connect-sdk-printer/blob/master/_autodocs/api-reference/conditions.md Attempting to add the same broke handler twice raises ValueError with 'already added'. The example catches and prints the error. ```python try: cond.add_broke_handler(handler) cond.add_broke_handler(handler) # ValueError: already added except ValueError as err: print("handler duplicate:", err) ``` -------------------------------- ### Error handling in SEND_FILE_INFO handler with reject Source: https://github.com/prusa3d/prusa-connect-sdk-printer/blob/master/_autodocs/api-reference/command.md Shows how to reject a command with a reason when the requested file does not exist. Uses printer.command.reject(const.Source.WUI, reason=...) to report the failure to Connect. For genuine exceptions, the SDK automatically reports FAILED with error=repr(err), so manual reject is not needed. ```python @printer.handler(const.Command.SEND_FILE_INFO) def send_file_info(caller): path = caller.kwargs["path"] node = printer.fs.get(path) if node is None: # rejecting with a reason is reported to Connect printer.command.reject(const.Source.WUI, reason=f"File does not exist: {path}") return ... ``` -------------------------------- ### Send event callback on exception Source: https://github.com/prusa3d/prusa-connect-sdk-printer/blob/master/README.rst Inform Connect about a specific situation, such as a failure, by calling printer.event_cb with the event type and source. The event is sent to an internal queue. ```python from threading import Thread ... # Start communication loop thread = Thread(target=printer.loop) thread.start() try: ... except Exception as err: # Send event to internal queue printer.event_cb(const.Event.FAILED, const.Source.WUI, reason=str(err)) ``` -------------------------------- ### Filesystem.__init__ Source: https://github.com/prusa3d/prusa-connect-sdk-printer/blob/master/_autodocs/api-reference/files.md Initializes a Filesystem object that models a collection of files in a flat, DOS-like structure. It accepts a path separator and an optional event callback for notifications. ```APIDOC ## Filesystem.__init__ ### Description Initializes a Filesystem object that models a collection of files in a flat, DOS-like structure. It accepts a path separator and an optional event callback for notifications. ### Method Constructor ### Signature ```python Filesystem(sep: str = "/", event_cb: Optional[EventCallback] = None) ``` ### Parameters - **sep** (str) - Optional - Virtual path separator - **event_cb** (Optional[EventCallback]) - Optional - Typically `Printer.event_cb`; when set, attach/detach and inotify changes enqueue events ``` -------------------------------- ### DownloadMgr class definition and __init__ signature Source: https://github.com/prusa3d/prusa-connect-sdk-printer/blob/master/_autodocs/api-reference/download.md Defines the DownloadMgr class with constants for loop interval, valid MIME types, and buffer sizes. The __init__ method accepts a Filesystem, Transfer, and several callbacks for connection details, events, printed file path, and download completion. ```python class DownloadMgr: """Download manager.""" LOOP_INTERVAL = .1 VALID_MIME_TYPES = ('text/plain', 'text/x.gcode', 'application/binary', 'application/octet-stream') SMALL_BUFFER = 1024 BIG_BUFFER = 1024 * 100 def __init__(self, fs: Filesystem, transfer: Transfer, conn_details_cb: Callable, event_cb: EventCallback, printed_file_cb: Callable, download_finished_cb: Callable): ``` -------------------------------- ### CameraConfigurator.__init__ Source: https://github.com/prusa3d/prusa-connect-sdk-printer/blob/master/_autodocs/api-reference/camera_configurator.md Initializes the CameraConfigurator with a camera controller, configuration parser, config file path, and camera drivers. Optionally enables auto-detection of cameras via driver scan. ```APIDOC ## CameraConfigurator.__init__ ### Description Initializes the CameraConfigurator with a camera controller, configuration parser, config file path, and camera drivers. Optionally enables auto-detection of cameras via driver scan. ### Method Constructor ### Signature ```python def __init__(self, camera_controller: CameraController, config: ConfigParser, config_file_path: str, drivers: List[Type[CameraDriver]], auto_detect=True) -> None: ``` ### Parameters - **camera_controller** (`CameraController`) - Required - The SDK camera controller to hand working cameras to - **config** (`ConfigParser`) - Required - ConfigParser reading (and writing) the INI - **config_file_path** (`str`) - Required - Path of the INI file to write on changes - **drivers** (`List[Type[CameraDriver]]`) - Required - Driver classes; keyed by `driver.name` - **auto_detect** (`bool`) - Optional (default `True`) - Whether to run driver `scan()` on load ### Behavior Constructor immediately calls `load_cameras(load_configs=True)`. ### State - `lock = RLock()` - `loaded: Dict[str, CameraDriver]` - `stored: Set[str]` - `detected: Set[str]` - `hash_to_detected: Dict[str, str]` (config hash → camera id) - `order: List[str]` - `_already_loaded_configs = False` ``` -------------------------------- ### json_from_settings(src_settings) Source: https://github.com/prusa3d/prusa-connect-sdk-printer/blob/master/_autodocs/api-reference/camera.md Inverse to settings_from_json: converts settings to JSON representation. trigger_scheme becomes .name, resolution becomes dict(resolution). ```APIDOC ## json_from_settings(src_settings) ### Description Inverse to settings_from_json: converts settings to JSON representation. ### Method json_from_settings ### Parameters - **src_settings** - Settings to convert. ### Returns - **Dict[str, Any]** - JSON representation of settings. ### Source `camera.py:521` ``` -------------------------------- ### CameraDriver.connect() Source: https://github.com/prusa3d/prusa-connect-sdk-printer/blob/master/_autodocs/api-reference/camera_driver.md Validates the configuration and establishes the connection. Raises ConfigError if configuration is invalid. ```APIDOC ## CameraDriver.connect() ### Description Validates the configuration and establishes the connection. Raises ConfigError if configuration is invalid. ### Raises - **ConfigError** - If `is_config_valid` fails. ``` -------------------------------- ### add method Source: https://github.com/prusa3d/prusa-connect-sdk-printer/blob/master/_autodocs/api-reference/files.md Adds a file to this File's children. Raises ValueError("You can add only to directories") when self is not a folder. Hidden nodes (name starting with '.') are ignored. Returns the added File. ```python def add(self, name: str, is_dir: bool = False, **attrs): """Add a file to this File's children. Note that `self` must be a folder.""" ``` -------------------------------- ### File class constructor Source: https://github.com/prusa3d/prusa-connect-sdk-printer/blob/master/_autodocs/api-reference/files.md Initializes a File node representing either a file or a folder. The parent is stored as a weakref.proxy to avoid reference loops. Arbitrary attributes can be passed; to_dict() picks up read_only and m_timestamp. ```python class File: """A node of a Filesystem representing either a file or a folder""" def __init__(self, name: str, is_dir: bool = False, parent: Optional["File"] = None, **attrs): ``` -------------------------------- ### accept method Source: https://github.com/prusa3d/prusa-connect-sdk-printer/blob/master/_autodocs/api-reference/command.md Accepts a command by adding an event to the queue. Sets state to ACCEPTED, stores identity/args, emits ACCEPTED via event_cb, sets new_cmd_evt, and clears cmd_end_evt. ```python def accept(self, command_id: int, command_name: str, args: Optional[List[Any]] = None, kwargs: Optional[Dict[str, Any]] = None, force=False): """Accept command (add event to queue).""" ``` -------------------------------- ### Send telemetry in separate thread Source: https://github.com/prusa3d/prusa-connect-sdk-printer/blob/master/README.rst Run the communication loop in a separate thread and send telemetry at least once per second. Telemetry values may not be atomic, so this must be done outside Printer.loop. ```python from threading import Thread from time import sleep ... # Start communication loop in a separate thread thread = Thread(target=printer.loop) thread.start() # Send telemetry to the main thread queue once per second while True: printer.telemetry(const.State.READY, temp_nozzle=24.1, temp_bed=23.2) sleep(1) ``` -------------------------------- ### CameraConfigurator constructor Source: https://github.com/prusa3d/prusa-connect-sdk-printer/blob/master/_autodocs/configuration.md Initializes a CameraConfigurator instance with the given camera controller, configuration parser, config file path, and driver classes. The auto_detect parameter optionally runs driver.scan() on load. ```APIDOC ## CameraConfigurator(camera_controller, config, config_file_path, drivers, auto_detect=True) ### Description Initializes a CameraConfigurator instance with the given camera controller, configuration parser, config file path, and driver classes. The auto_detect parameter optionally runs driver.scan() on load. ### Parameters - **camera_controller** (CameraController) - Required - Receives working cameras - **config** (ConfigParser) - Required - INI representation (read + written) - **config_file_path** (str) - Required - File written on every config change - **drivers** (List[Type[CameraDriver]]) - Required - Driver classes, keyed by `name` - **auto_detect** (bool) - Optional - Runs `driver.scan()` on load (default: True) ``` -------------------------------- ### default_register_handler(token) implementation Source: https://github.com/prusa3d/prusa-connect-sdk-printer/blob/master/_autodocs/api-reference/printer.md Default register handler installed as Printer.register_handler. It only asserts the token is truthy; applications should replace it (e.g., with one that persists the token). Blocks communication with Connect in the loop method. ```python def default_register_handler(token): """Default register handler. It blocks communication with Connect in loop method!""" assert token ``` -------------------------------- ### RetryingSession.__init__(max_retries=3) Source: https://github.com/prusa3d/prusa-connect-sdk-printer/blob/master/_autodocs/api-reference/util.md Initializes a RetryingSession instance. Used when Printer(max_retries > 1). ```APIDOC ## RetryingSession.__init__(max_retries=3) ### Description Initializes a RetryingSession instance. Used when Printer(max_retries > 1). ### Parameters - **max_retries** (int) - Optional - Number of attempts before propagating the exception. Default: 3. ### Example ```python from prusa.connect.printer.util import RetryingSession session = RetryingSession(max_retries=3) ``` ``` -------------------------------- ### check_state method Source: https://github.com/prusa3d/prusa-connect-sdk-printer/blob/master/_autodocs/api-reference/command.md Checks if ready for another command. Returns True if command can be accepted, otherwise puts the right event to queue. Handles priority commands, running commands, and duplicate command ids. ```python def check_state(self, command_id: int, command_name: str): """Check if we're ready for another command :return: True, if command can be accepted. Otherwise, put right event to queue. """ ``` -------------------------------- ### send method Source: https://github.com/prusa3d/prusa-connect-sdk-printer/blob/master/_autodocs/api-reference/camera.md Sends the snapshot via PUT to {server}/c/snapshot with headers Timestamp, Fingerprint, Token, Content-Type: image/jpg. Logs a warning if incomplete. Uses timeout=const.CONNECTION_TIMEOUT and includes printer_uuid query param when set. ```python def send(self, conn: Session, server): """A snapshot send function""" ``` -------------------------------- ### Storage class constructor Source: https://github.com/prusa3d/prusa-connect-sdk-printer/blob/master/_autodocs/api-reference/files.md Initializes a Storage object with a file tree, storage name, optional absolute path, and inotify flag. Raises ValueError if use_inotify is true without abs_path_storage. ```python class Storage: def __init__(self, tree: File, storage: str, abs_path_storage: Optional[str] = None, use_inotify=True): ``` -------------------------------- ### Filesystem.get method Source: https://github.com/prusa3d/prusa-connect-sdk-printer/blob/master/_autodocs/api-reference/files.md Returns the File addressed by the given absolute path, or None if not found. ```python def get(self, abs_path: str): """Return the File addressed by `abs_path`""" ```