### Create and Configure Printer Instance (Python) Source: https://github.com/prusa3d/prusa-connect-sdk-printer/blob/master/README.rst Demonstrates how to create a Printer instance with its type, serial number, and fingerprint, and then set up the connection to Prusa Connect using server and token credentials. The communication loop is started afterwards. ```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) SERVER = "https://connect.prusa3d.com" TOKEN = "Secret token from prusa_printer_settings.ini" printer.set_connection(SERVER, TOKEN) printer.loop() # Communication loop ``` ```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) printer.connection_from_config("./prusa_printer_settings.ini") printer.loop() # Communication loop ``` -------------------------------- ### Python Command Handler Example for Prusa Connect SDK Source: https://github.com/prusa3d/prusa-connect-sdk-printer/blob/master/README.rst Demonstrates how to define command handlers for START_PRINT and STOP_PRINT commands using the @printer.handler decorator. It shows how to set printer states and includes the main communication loop for processing commands. ```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.PRINTING, const.Source.CONNECT) print(f"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") ... # 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) ``` -------------------------------- ### Python: Start Telemetry Reporting Loop Source: https://context7.com/prusa3d/prusa-connect-sdk-printer/llms.txt Illustrates how to initiate the telemetry reporting mechanism for a connected printer. It involves starting the main communication loop in a separate background thread and setting the initial state of the printer to 'READY'. This ensures continuous data exchange with the PrusaConnect platform. ```python from prusa.connect.printer import Printer, const from threading import Thread from time import sleep # Assume printer is already initialized and connected printer = Printer(const.PrinterType.I3MK3S, "SERIAL123", "fingerprint123") printer.set_connection("https://connect.prusa3d.com", "token123") # Start communication loop in background thread thread = Thread(target=printer.loop, daemon=True) thread.start() # Set initial printer state printer.set_state(const.State.READY, const.Source.MARLIN) ``` -------------------------------- ### Define Download Handlers for Printer Commands (Python) Source: https://context7.com/prusa3d/prusa-connect-sdk-printer/llms.txt Defines functions to handle specific printer commands related to starting URL downloads, starting Connect downloads, stopping transfers, and sending transfer information. These handlers interact with the printer's download manager and transfer objects, raising ValueErrors or RuntimeErrors for invalid input or states. They return dictionaries containing transfer details and source information. ```python import const from threading import Thread from time import sleep # Assume 'printer' is an instance of Printer class @printer.handler(const.Command.START_URL_DOWNLOAD) def start_url_download(command): """Handle URL download command""" if not command.kwargs: raise ValueError("START_URL_DOWNLOAD requires kwargs") try: result = printer.download_mgr.start( const.TransferType.FROM_WEB, command.kwargs["path"], command.kwargs["url"], to_print=command.kwargs.get("printing", False), to_select=command.kwargs.get("selecting", False), start_cmd_id=command.command_id ) result['source'] = const.Source.CONNECT return result except KeyError as e: raise ValueError(f"Missing required parameter: {e}") @printer.handler(const.Command.START_CONNECT_DOWNLOAD) def start_connect_download(command): """Handle Connect download command""" if not command.kwargs: raise ValueError("START_CONNECT_DOWNLOAD requires kwargs") try: uri = "/p/teams/{team_id}/files/{hash}/raw".format(**command.kwargs) result = printer.download_mgr.start( const.TransferType.FROM_CONNECT, command.kwargs["path"], printer.server + uri, to_print=command.kwargs.get("printing", False), to_select=command.kwargs.get("selecting", False), start_cmd_id=command.command_id, hash_=command.kwargs["hash"], team_id=command.kwargs["team_id"] ) result['source'] = const.Source.CONNECT return result except KeyError as e: raise ValueError(f"Missing required parameter: {e}") @printer.handler(const.Command.STOP_TRANSFER) def stop_transfer(command): """Handle transfer stop command""" transfer_id = (command.kwargs or {}).get("transfer_id") if transfer_id and transfer_id != printer.transfer.transfer_id: raise RuntimeError("Wrong transfer_id") printer.transfer.stop() return {"source": const.Source.CONNECT} @printer.handler(const.Command.SEND_TRANSFER_INFO) def transfer_info(command): """Handle transfer info request""" kwargs = command.kwargs or {} transfer_id = kwargs.get('transfer_id') if transfer_id and transfer_id != printer.transfer.transfer_id: raise ValueError("Not current transfer") info = printer.download_mgr.info() info['source'] = const.Source.CONNECT info['event'] = const.Event.TRANSFER_INFO return info # Download finished callback def on_download_finished(transfer): """Called when download completes""" print(f"Download finished: {transfer.path}") print(f"Transfer ID: {transfer.transfer_id}") print(f"Size: {transfer.size} bytes") printer.download_finished_cb = on_download_finished # Start communication loop thread = Thread(target=printer.loop, daemon=True) thread.start() # Monitor transfer progress while printer.transfer.in_progress: progress = printer.transfer.progress remaining = printer.transfer.time_remaining() print(f"Download progress: {progress}%, remaining: {remaining}s") sleep(1) printer.stop_loop() ``` -------------------------------- ### Manage Printer State and Events with Prusa Connect SDK (Python) Source: https://context7.com/prusa3d/prusa-connect-sdk-printer/llms.txt This snippet illustrates how to manage the printer's state and send custom events to PrusaConnect using the SDK. It demonstrates setting states like BUSY and READY, and their associated readiness flags. Requires the 'prusa.connect.printer' library and threading setup. ```python from prusa.connect.printer import Printer, const from threading import Thread from time import sleep printer = Printer(const.PrinterType.I3MK3S, "SERIAL123", "fingerprint123") printer.set_connection("https://connect.prusa3d.com", "token123") # Start communication loop thread = Thread(target=printer.loop, daemon=True) thread.start() # Change printer state printer.set_state(const.State.BUSY, const.Source.MARLIN) print(f"Printer state: {printer.state.value}") # Transition to READY state printer.set_state(const.State.READY, const.Source.MARLIN, ready=True) print(f"Printer ready: {printer.ready}") ``` -------------------------------- ### Send an Event Notification (Python) Source: https://github.com/prusa3d/prusa-connect-sdk-printer/blob/master/README.rst Demonstrates how to send a custom event notification to Prusa Connect, for example, to report an error. The main communication loop should be running in a separate thread. ```python from threading import Thread # ... (printer initialization and connection setup assumed) # 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)) ``` -------------------------------- ### Handle Printer Commands with Prusa Connect SDK (Python) Source: https://context7.com/prusa3d/prusa-connect-sdk-printer/llms.txt This snippet shows how to implement custom command handlers for START_PRINT, STOP_PRINT, PAUSE_PRINT, RESUME_PRINT, and GCODE commands received from PrusaConnect. It uses the `@printer.handler` decorator to register functions for specific commands. Requires the 'prusa.connect.printer' library and basic threading setup. ```python from prusa.connect.printer import Printer, const from threading import Thread from time import sleep printer = Printer(const.PrinterType.I3MK3S, "SERIAL123", "fingerprint123") printer.set_connection("https://connect.prusa3d.com", "token123") # Define command handlers @printer.handler(const.Command.START_PRINT) def start_print(command): """Handle START_PRINT command""" if not command.kwargs or "path" not in command.kwargs: raise ValueError("START_PRINT requires path parameter") file_path = command.kwargs["path"] print(f"Starting print: {file_path}") # Update printer state printer.set_state(const.State.PRINTING, const.Source.CONNECT) # Set job ID from command printer.job_id = command.kwargs.get("job_id") # Return success response return { "source": const.Source.CONNECT, "event": const.Event.ACCEPTED } @printer.handler(const.Command.STOP_PRINT) def stop_print(command): """Handle STOP_PRINT command""" print("Stopping print") # Stop the print job printer.set_state(const.State.IDLE, const.Source.CONNECT) printer.job_id = None return {"source": const.Source.CONNECT} @printer.handler(const.Command.PAUSE_PRINT) def pause_print(command): """Handle PAUSE_PRINT command""" print("Pausing print") printer.set_state(const.State.PAUSED, const.Source.CONNECT) return {"source": const.Source.CONNECT} @printer.handler(const.Command.RESUME_PRINT) def resume_print(command): """Handle RESUME_PRINT command""" print("Resuming print") printer.set_state(const.State.PRINTING, const.Source.CONNECT) return {"source": const.Source.CONNECT} @printer.handler(const.Command.GCODE) def execute_gcode(command): """Handle GCODE command""" if not command.kwargs or "gcode" not in command.kwargs: raise ValueError("GCODE command requires gcode parameter") gcode = command.kwargs["gcode"] print(f"Executing G-code: {gcode}") # Execute the G-code on printer # ... implementation specific to your printer return {"source": const.Source.CONNECT} # Start communication loop thread = Thread(target=printer.loop, daemon=True) thread.start() # Set printer to READY state printer.set_state(const.State.READY, const.Source.CONNECT) # Process commands continuously try: while True: # Check for and execute commands every 100ms printer.command() sleep(0.1) except KeyboardInterrupt: printer.stop_loop() ``` -------------------------------- ### Send Telemetry Data (Python) Source: https://github.com/prusa3d/prusa-connect-sdk-printer/blob/master/README.rst Illustrates how to send telemetry data to Prusa Connect. It involves starting the main communication loop in a separate thread and then sending telemetry updates periodically in the main thread. ```python from threading import Thread from time import sleep # ... (printer initialization and connection setup assumed) # 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) ``` -------------------------------- ### Python: Initialize and Connect Printer Instance Source: https://context7.com/prusa3d/prusa-connect-sdk-printer/llms.txt Demonstrates how to create a Printer instance with essential identification details (serial number, fingerprint, printer type) and establish a connection to the PrusaConnect server. It also shows how to set the printer's firmware version and network information, and optionally load connection details from a configuration file. ```python from prusa.connect.printer import Printer, const from hashlib import sha256 # Initialize printer with identification SN = "CZPX1234X012XC12345" FINGERPRINT = sha256(SN.encode()).hexdigest() PRINTER_TYPE = const.PrinterType.I3MK3S printer = Printer(PRINTER_TYPE, SN, FINGERPRINT) # Set connection details SERVER = "https://connect.prusa3d.com" TOKEN = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." printer.set_connection(SERVER, TOKEN) # Or load connection from configuration file printer.connection_from_config("./prusa_printer_settings.ini") # Set printer firmware version printer.firmware = "4.7.2" # Configure network information printer.network_info = { "lan_mac": "00:1A:2B:3C:4D:5E", "lan_ipv4": "192.168.1.100", "hostname": "prusa-i3mk3s", } print(f"Printer initialized: {printer.sn} ({printer.type})") print(f"Connected to: {printer.server}") ``` -------------------------------- ### File Download Management Placeholder (Python) Source: https://context7.com/prusa3d/prusa-connect-sdk-printer/llms.txt This is a placeholder snippet for file download management. It initializes the Printer object, sets up a connection to Prusa Connect, and attaches a USB storage device. The actual file download logic, which would typically involve downloading G-code files from URLs or Prusa Connect with progress tracking, is not implemented in this snippet. Dependencies include `prusa.connect.printer`, `threading.Thread`, and `time.sleep`. ```python from prusa.connect.printer import Printer, const from threading import Thread from time import sleep printer = Printer(const.PrinterType.I3MK3S, "SERIAL123", "fingerprint123") printer.set_connection("https://connect.prusa3d.com", "token123") printer.attach("/media/usb", "usb") ``` -------------------------------- ### Camera Integration for Snapshot Capture and Streaming (Python) Source: https://context7.com/prusa3d/prusa-connect-sdk-printer/llms.txt Demonstrates how to register and manage cameras for snapshot capture and streaming using the Prusa Connect SDK. It involves creating a custom camera driver, initializing a Camera object, configuring its properties like resolution and exposure, and registering it with the printer's camera controller. A callback function is set up to handle snapshots when they are ready. ```python from prusa.connect.printer import Printer, const from prusa.connect.printer.camera import Camera, Resolution, Snapshot from prusa.connect.printer.camera_driver import CameraDriver from threading import Thread from time import sleep, time printer = Printer(const.PrinterType.I3MK3S, "SERIAL123", "fingerprint123") printer.set_connection("https://connect.prusa3d.com", "token123") # Create camera driver (implementation specific) class CustomCameraDriver(CameraDriver): """Custom camera driver implementation""" def __init__(self): super().__init__() self.name = "custom_camera" def capture_image(self): """Capture image from camera""" # Implementation specific return b"jpeg_image_data" def get_available_resolutions(self): """Get available resolutions""" return [ Resolution(640, 480), Resolution(1280, 720), Resolution(1920, 1080) ] # Initialize camera driver = CustomCameraDriver() camera = Camera(driver) camera.name = "Prusa Camera" camera.camera_id = "camera_001" camera.fingerprint = "camera_fingerprint_123" # Set camera resolution camera.resolution = Resolution(1920, 1080) camera.rotation = 0 camera.exposure = 0.0 # Register camera with Connect printer.camera_controller.add_camera(camera) # Snapshot callback def on_snapshot_ready(snapshot): """Called when snapshot is ready to send""" if snapshot.is_sendable(): print(f"Snapshot ready at {snapshot.timestamp}") # Snapshot will be sent automatically by camera controller camera.photo_cb = on_snapshot_ready # Start communication loop thread = Thread(target=printer.loop, daemon=True) thread.start() ``` -------------------------------- ### Manage Printer File System (Python) Source: https://context7.com/prusa3d/prusa-connect-sdk-printer/llms.txt This Python code illustrates comprehensive file system management on the printer. It includes attaching and detaching storage devices (USB, SD card), setting up handlers for file deletion and folder creation commands received from Prusa Connect, and interacting with the file system via the SDK. Dependencies include `prusa.connect.printer`, `threading.Thread`, `time.sleep`, and the `os` module for file operations. The handlers ensure validation checks before performing operations. ```python from prusa.connect.printer import Printer, const from threading import Thread from time import sleep printer = Printer(const.PrinterType.I3MK3S, "SERIAL123", "fingerprint123") printer.set_connection("https://connect.prusa3d.com", "token123") # Attach storage locations printer.attach("/media/usb", "usb") printer.attach("/media/sdcard", "sdcard") # Set up file handlers @printer.handler(const.Command.DELETE_FILE) def delete_file(command): """Handle file deletion""" if not command.kwargs or "path" not in command.kwargs: raise ValueError("DELETE_FILE requires path") file_path = command.kwargs["path"] # Check if file is read-only node = printer.fs.get(file_path) if node and node.attrs.get("read_only"): raise ValueError("File is read only") # Check if file is currently printing if printer.printed_file_cb() == file_path: raise ValueError("Cannot delete file that is currently printing") # Get absolute OS path and delete abs_path = printer.inotify_handler.get_abs_os_path(file_path) import os os.unlink(abs_path) return {"source": const.Source.CONNECT} @printer.handler(const.Command.CREATE_FOLDER) def create_folder(command): """Handle folder creation""" if not command.kwargs or "path" not in command.kwargs: raise ValueError("CREATE_FOLDER requires path") folder_path = command.kwargs["path"] abs_path = printer.inotify_handler.get_abs_os_path(folder_path) import os os.makedirs(abs_path, exist_ok=True) return {"source": const.Source.CONNECT} # Start loops comm_thread = Thread(target=printer.loop, daemon=True) comm_thread.start() inotify_thread = Thread(target=printer.inotify_handler, daemon=True) inotify_thread.start() # Get file information file_info = printer.fs.to_dict_legacy() print(f"Total files: {len(file_info)}") # Simulate file operations sleep(2) # Detach storage printer.detach("usb") # Send storage ejected event printer.event_cb( const.Event.MEDIUM_EJECTED, const.Source.HW, path="usb" ) sleep(1) printer.stop_loop() ``` -------------------------------- ### Configure and Manage MMU Features with Python Source: https://context7.com/prusa3d/prusa-connect-sdk-printer/llms.txt Initializes the Prusa Printer object with MMU support enabled, configures MMU parameters like firmware version and type, and demonstrates handling of MMU-related commands (LOAD_FILAMENT, UNLOAD_FILAMENT, SLOT_ACTION). It also shows how to send MMU telemetry data. Requires the `prusa-connect-sdk-printer` library. ```python from prusa.connect.printer import Printer, const from threading import Thread from time import sleep # Initialize printer with MMU support printer = Printer( const.PrinterType.I3MK3S, # Example printer type "SERIAL123", # Example serial number "fingerprint123", # Example fingerprint mmu_supported=True # Enable MMU support ) printer.set_connection("https://connect.prusa3d.com", "token123") # Connect to Prusa Connect # Configure MMU specific settings printer.mmu_enabled = True printer.mmu_fw = "3.0.2" # MMU firmware version printer.mmu_type = const.MMUType.MMU3 # MMU type # Get slot count based on MMU type slot_count = const.MMU_SLOT_COUNTS[printer.mmu_type] print(f"MMU3 slots: {slot_count}") # --- MMU Command Handlers --- @printer.handler(const.Command.LOAD_FILAMENT) def load_filament(command): """Handle filament load command""" if not command.kwargs: raise ValueError("LOAD_FILAMENT requires kwargs") slot = command.kwargs.get("slot", 0) print(f"Loading filament from slot {slot}") # Placeholder for actual filament loading implementation # ... (e.g., send commands to the MMU) # Send an event indicating filament has been loaded from a specific slot printer.event_cb( const.Event.SLOT_EVENT, const.Source.SLOT, slot=slot, event="loaded" ) return {"source": const.Source.CONNECT} @printer.handler(const.Command.UNLOAD_FILAMENT) def unload_filament(command): """Handle filament unload command""" print("Unloading filament") # Placeholder for actual filament unloading implementation # ... (e.g., send commands to the MMU) # Send an event indicating filament has been unloaded printer.event_cb( const.Event.SLOT_EVENT, const.Source.SLOT, event="unloaded" ) return {"source": const.Source.CONNECT} @printer.handler(const.Command.SLOT_ACTION) def slot_action(command): """Handle generic slot action command""" if not command.kwargs: raise ValueError("SLOT_ACTION requires kwargs") action = command.kwargs.get("action") slot = command.kwargs.get("slot", 0) print(f"Slot action: {action} on slot {slot}") # Placeholder for other slot actions # ... return {"source": const.Source.CONNECT} # Start the communication loop in a separate thread thread = Thread(target=printer.loop, daemon=True) thread.start() # Example: Send MMU telemetry data printer.telemetry( temp_nozzle=220.0, # Current nozzle temperature temp_bed=60.0, # Current bed temperature mmu_current_slot=2, # Current active MMU slot mmu_filament_loaded=True # Whether filament is loaded in the current slot ) sleep(2) # Keep the script running for a short duration printer.stop_loop() # Stop the communication loop ``` -------------------------------- ### Manage Printer State (Python) Source: https://github.com/prusa3d/prusa-connect-sdk-printer/blob/master/README.rst Shows how to manage the printer's state, such as switching between READY and BUSY states. The communication loop must be running in a separate thread for this to function correctly. ```python from threading import Thread from time import sleep # ... (printer initialization and connection setup assumed) # 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) ``` -------------------------------- ### Capture and Send Camera Snapshot using Python Source: https://context7.com/prusa3d/prusa-connect-sdk-printer/llms.txt Captures a snapshot image from the printer's camera, prepares it as a Snapshot object, and sends it to the Prusa Connect platform if it's sendable. Includes error handling for the capture and send process. Requires a configured camera and driver. ```python from prusa.connect.printer import const from prusa.connect.printer.models import Snapshot from time import time, sleep # Assuming 'camera' and 'driver' objects are already initialized and configured # and 'printer' object is connected to Prusa Connect. # Trigger camera capture at a defined interval trigger_scheme = const.TriggerScheme.THIRTY_SEC camera.trigger_scheme = trigger_scheme # Manual snapshot capture try: snapshot = Snapshot() snapshot.camera_token = camera.token snapshot.camera_fingerprint = camera.fingerprint snapshot.camera_id = camera.camera_id snapshot.timestamp = time() snapshot.data = driver.capture_image() # Assumes driver.capture_image() returns image data # Send snapshot if it's valid and sendable if snapshot.is_sendable(): printer.send_cb(snapshot) print("Snapshot sent successfully") except Exception as e: print(f"Camera error: {e}") sleep(60) # Run for 60 seconds to allow for operation printer.stop_loop() # Stop the communication loop ``` -------------------------------- ### Python: Register Printer with PrusaConnect Source: https://context7.com/prusa3d/prusa-connect-sdk-printer/llms.txt Shows the process of registering a new printer with PrusaConnect. It involves requesting a temporary code, providing a direct registration URL for the user, and then waiting for the user to complete the registration on the web interface to obtain an authentication token. Includes error handling for timeouts and registration failures. ```python from prusa.connect.printer import Printer, const from time import sleep from hashlib import sha256 SERVER = "https://connect.prusa3d.com" SN = "CZPX1234X012XC12345" FINGERPRINT = sha256(SN.encode()).hexdigest() PRINTER_TYPE = const.PrinterType.I3MK3 printer = Printer(PRINTER_TYPE, SN, FINGERPRINT) printer.firmware = "4.7.2" printer.set_connection(SERVER, None) try: # Request temporary registration code tmp_code = printer.register() print(f"Registration Code: {tmp_code}") print(f"Visit: {SERVER}/printers/overview?code={tmp_code}") # For I3MK3, use direct add-printer URL direct_url = f"{SERVER}/add-printer/connect/{PRINTER_TYPE}/{tmp_code}" print(f"Direct registration URL: {direct_url}") # Wait for user to complete registration on web timeout = 60 # 60 seconds elapsed = 0 while printer.token is None and elapsed < timeout: print(f"Waiting for registration... ({elapsed}s)") sleep(1) elapsed += 1 if printer.token: print(f"Registration successful! Token: {printer.token[:20]}...") # Save token for future use with open("printer_token.txt", "w") as f: f.write(printer.token) else: print("Registration timeout") except RuntimeError as e: print(f"Registration failed: {e}") ``` -------------------------------- ### Register Printer with Prusa Connect (Python) Source: https://github.com/prusa3d/prusa-connect-sdk-printer/blob/master/README.rst Shows the process of registering a printer with Prusa Connect if it hasn't been registered yet. It generates a temporary code to be entered in the Connect Web interface and waits for the printer to be automatically registered. ```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}") ``` -------------------------------- ### Send Telemetry Continuously with Prusa Connect SDK Source: https://context7.com/prusa3d/prusa-connect-sdk-printer/llms.txt This snippet demonstrates how to continuously send telemetry data from a 3D printer using the Prusa Connect SDK. It includes sending basic telemetry and more detailed telemetry during printing. Ensure the 'printer' object is initialized and connected. ```python try: while True: # Send basic telemetry printer.telemetry( temp_nozzle=215.5, temp_bed=60.2, target_nozzle=220.0, target_bed=60.0, axis_x=125.4, axis_y=98.3, axis_z=15.7, speed=100, flow=100 ) sleep(1) # Send telemetry during printing if printer.state == const.State.PRINTING: printer.telemetry( temp_nozzle=219.8, temp_bed=60.1, target_nozzle=220.0, target_bed=60.0, print_speed=100, progress=45.5, time_printing=1825, # seconds time_remaining=2175, axis_z=15.7 ) sleep(1) except KeyboardInterrupt: printer.stop_loop() print("Telemetry stopped") ``` -------------------------------- ### Send Custom Printer Events (Python) Source: https://context7.com/prusa3d/prusa-connect-sdk-printer/llms.txt This snippet demonstrates how to send various custom events from the printer to the Prusa Connect service. It covers simulating filament runout, file changes, print failures, and successful print completion. Error handling is included to send a FAILED event if an exception occurs during event processing. Dependencies include the `prusa.connect.printer` library and `time.sleep`. ```python try: # Simulate a filament runout event printer.event_cb( const.Event.ATTENTION, const.Source.HW, reason="Filament runout detected" ) # Simulate file change event printer.event_cb( const.Event.FILE_CHANGED, const.Source.WUI, path="/usb/test_print.gcode" ) # Send error event with details printer.event_cb( const.Event.FAILED, const.Source.FIRMWARE, reason="Temperature error", temp_nozzle=0.0, target_nozzle=220.0 ) # Simulate print finish printer.set_state(const.State.FINISHED, const.Source.MARLIN) printer.event_cb( const.Event.FINISHED, const.Source.MARLIN, reason="Print completed successfully" ) except Exception as err: # Send error event on exception printer.event_cb( const.Event.FAILED, const.Source.WUI, reason=str(err) ) sleep(2) printer.stop_loop() ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.