### Run Complete Prusa Exporter Application Source: https://context7.com/pubeldev/prusa_exporter/llms.txt This Go code snippet provides a complete exporter application that combines Prusa Link and UDP metric collection. It loads configuration, initializes and registers the Prusa Link collector, enables UDP metrics on printers, and starts a UDP metrics listener. The application exposes both Prusa Link and UDP metrics on separate endpoints (`/metrics/prusalink` and `/metrics/udp`) and provides a root endpoint with links to these metrics. It then starts an HTTP server on port 10009 to serve all functionalities. ```go package main import ( "log" "net/http" "strconv" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promhttp" "github.com/pstrobl96/prusa_exporter/config" prusalink "github.com/pstrobl96/prusa_exporter/prusalink/buddy" udp "github.com/pstrobl96/prusa_exporter/udp" ) func main() { // Load configuration cfg, err := config.LoadConfig("./prusa.yml", 10, "", false, "crash,power_panic", "") if err != nil { log.Fatal("Configuration error:", err) } // Initialize Prusa Link metrics collector := prusalink.NewCollector(cfg) prometheus.MustRegister(collector) http.Handle("/metrics/prusalink", promhttp.Handler()) // Enable UDP metrics on printers prusalink.EnableUDPmetrics(cfg.Printers) // Initialize UDP metrics listener udpRegistry := prometheus.NewRegistry() udp.Init(udpRegistry) go udp.MetricsListener("0.0.0.0:8514", "prusa_") http.Handle("/metrics/udp", promhttp.HandlerFor(udpRegistry, promhttp.HandlerOpts{ Registry: udpRegistry, })) // Root endpoint with information http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { html := ` Prusa Exporter

Prusa Exporter

Prusa Link Metrics

UDP Metrics

` w.Write([]byte(html)) }) port := 10009 log.Printf("Prusa Exporter started on port %d", port) log.Fatal(http.ListenAndServe(":"+strconv.Itoa(port), nil)) } ``` -------------------------------- ### Docker Deployment and Configuration Source: https://context7.com/pubeldev/prusa_exporter/llms.txt Provides instructions for deploying the Prusa Exporter using Docker and Docker Compose. It covers setting environment variables, starting the service, viewing logs, and checking exposed metrics endpoints. A sample `docker-compose.yaml` file is included for multi-service orchestration with Prometheus and Grafana. ```bash # Export host IP for UDP metrics configuration export HOST_IP=192.168.1.50 # Start with docker-compose docker compose up -d # Or use the startup script ./start_docker.sh # View logs docker compose logs -f prusa_exporter # Check metrics endpoints curl http://localhost:10009/metrics/prusalink curl http://localhost:10009/metrics/udp ``` ```yaml # docker-compose.yaml version: '3.8' services: prusa_exporter: image: pstrobl96/prusa_exporter:latest container_name: prusa_exporter ports: - "10009:10009" - "8514:8514/udp" volumes: - ./prusa.yml:/app/prusa.yml:ro environment: - HOST_IP=${HOST_IP} restart: unless-stopped prometheus: image: prom/prometheus:latest container_name: prometheus ports: - "9090:9090" volumes: - ./prometheus.yaml:/etc/prometheus/prometheus.yml:ro restart: unless-stopped grafana: image: grafana/grafana:latest container_name: grafana ports: - "3000:3000" environment: - GF_SECURITY_ADMIN_PASSWORD=admin restart: unless-stopped ``` -------------------------------- ### Initialize UDP Metrics Listener for Prusa Exporter Source: https://context7.com/pubeldev/prusa_exporter/llms.txt This Go code snippet sets up a syslog server to listen for incoming UDP metrics from Prusa printers. It initializes a Prometheus registry for these metrics and starts a goroutine that listens on port 8514. The listener processes incoming syslog messages, preparing them for Prometheus. The application remains running indefinitely using a `select {}` statement. ```go package main import ( "log" "github.com/prometheus/client_golang/prometheus" udp "github.com/pstrobl96/prusa_exporter/udp" ) func main() { // Create Prometheus registry for UDP metrics udpRegistry := prometheus.NewRegistry() // Initialize UDP metrics system udp.Init(udpRegistry) // Start listening for UDP metrics on port 8514 // This runs in a goroutine and processes incoming syslog messages go udp.MetricsListener("0.0.0.0:8514", "prusa_") log.Println("UDP metrics listener started on 0.0.0.0:8514") log.Println("Waiting for metrics from printers...") // Keep the application running select {} } ``` -------------------------------- ### Configure prusa.yml for Prusa Link Metrics Source: https://github.com/pubeldev/prusa_exporter/blob/main/docs/readme/prusalink/PRUSALINK.md This configuration snippet demonstrates how to define printer connection details within the prusa.yml file. It includes fields for the printer's IP address, username, password, a user-chosen name, and the printer type. This setup is crucial for the prusa_exporter to fetch metrics from the Prusa Link API. ```yaml - address: IPv4 Address username: User password: Password name: type: ``` -------------------------------- ### Create Prometheus Collector for Prusa Link Metrics Source: https://context7.com/pubeldev/prusa_exporter/llms.txt This Go code snippet demonstrates how to create and register a Prometheus collector for Prusa Link metrics. It first loads the exporter's configuration from a YAML file. Then, it instantiates a Prusa Link collector using the loaded configuration and registers it with the default Prometheus registry. Finally, it sets up an HTTP endpoint at `/metrics/prusalink` to expose these metrics and starts an HTTP server on port 10009. ```go package main import ( "log" "net/http" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promhttp" "github.com/pstrobl96/prusa_exporter/config" prusalink "github.com/pstrobl96/prusa_exporter/prusalink/buddy" ) func main() { cfg, err := config.LoadConfig("./prusa.yml", 10, "", false, "", "") if err != nil { log.Fatal("Failed to load config:", err) } // Create collector for Prusa Link metrics collector := prusalink.NewCollector(cfg) // Register with Prometheus prometheus.MustRegister(collector) // Expose metrics endpoint http.Handle("/metrics/prusalink", promhttp.Handler()) log.Println("Prusa Link metrics available at http://localhost:10009/metrics/prusalink") log.Fatal(http.ListenAndServe(":10009", nil)) } ``` -------------------------------- ### Prusa Link API: Get Version Source: https://context7.com/pubeldev/prusa_exporter/llms.txt Retrieve printer version information from the Prusa Link API. ```APIDOC ## Access Prusa Link API Endpoint ### Description Retrieve printer version information via the Prusa Link API. ### Method GET ### Endpoint `/api/version` (relative to printer's IP address) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go package main import ( "log" "github.com/pstrobl96/prusa_exporter/config" prusalink "github.com/pstrobl96/prusa_exporter/prusalink/buddy" ) func main() { printer := config.Printers{ Address: "192.168.1.100", Username: "maker", Password: "your_password", Name: "MK4_Test", Type: "MK4", } // Get version information version, err := prusalink.GetVersion(printer) if err != nil { log.Fatal("Failed to get version:", err) } log.Printf("API Version: %s", version.API) log.Printf("Server Version: %s", version.Server) log.Printf("Hostname: %s", version.Hostname) } ``` ### Response #### Success Response (200) - **API** (string) - The API version of the printer. - **Server** (string) - The server version of the printer. - **Hostname** (string) - The hostname of the printer. #### Response Example ```json { "API": "1.0", "Server": "2.6.9", "Hostname": "Prusa-MK4" } ``` ``` -------------------------------- ### Prusa Link API: Get Printer Temperature and Status Source: https://context7.com/pubeldev/prusa_exporter/llms.txt Fetch real-time temperature and operational state of the printer via the Prusa Link API. ```APIDOC ## Get Printer Temperature and Status ### Description Fetch real-time temperature and operational state. ### Method GET ### Endpoint `/api/printer` (relative to printer's IP address) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go package main import ( "log" "github.com/pstrobl96/prusa_exporter/config" prusalink "github.com/pstrobl96/prusa_exporter/prusalink/buddy" ) func main() { printer := config.Printers{ Address: "192.168.1.100", Username: "maker", Password: "your_password", } printerData, err := prusalink.GetPrinter(printer) if err != nil { log.Fatal("Failed to get printer data:", err) } // Temperature information log.Printf("Bed Temperature: %.1f°C (Target: %.1f°C)", printerData.Temperature.Bed.Actual, printerData.Temperature.Bed.Target) log.Printf("Nozzle Temperature: %.1f°C (Target: %.1f°C)", printerData.Temperature.Tool0.Actual, printerData.Temperature.Tool0.Target) // Printer state log.Printf("State: %s", printerData.State.Text) log.Printf("Operational: %v", printerData.State.Flags.Operational) log.Printf("Printing: %v", printerData.State.Flags.Printing) // Axis positions log.Printf("X: %.2f, Y: %.2f, Z: %.2f", printerData.Telemetry.AxisX, printerData.Telemetry.AxisY, printerData.Telemetry.AxisZ) } ``` ### Response #### Success Response (200) - **Temperature** (object) - Temperature readings. - **Bed** (object) - **Actual** (float64) - Actual bed temperature. - **Target** (float64) - Target bed temperature. - **Tool0** (object) - Nozzle temperature. - **Actual** (float64) - Actual nozzle temperature. - **Target** (float64) - Target nozzle temperature. - **State** (object) - Printer state information. - **Text** (string) - Textual representation of the printer state. - **Flags** (object) - **Operational** (bool) - Indicates if the printer is operational. - **Printing** (bool) - Indicates if the printer is currently printing. - **Telemetry** (object) - Real-time telemetry data. - **AxisX** (float64) - Current X-axis position. - **AxisY** (float64) - Current Y-axis position. - **AxisZ** (float64) - Current Z-axis position. #### Response Example ```json { "temperature": { "bed": { "actual": 60.5, "target": 60.0 }, "tool0": { "actual": 210.2, "target": 210.0 } }, "state": { "text": "Printing", "flags": { "operational": true, "printing": true } }, "telemetry": { "axis_x": 120.5, "axis_y": 150.2, "axis_z": 5.75 } } ``` ``` -------------------------------- ### Prusa Link API: Get Current Print Job Status Source: https://context7.com/pubeldev/prusa_exporter/llms.txt Query active print job details and progress from the Prusa Link API. ```APIDOC ## Retrieve Current Print Job Status ### Description Query active print job details and progress. ### Method GET ### Endpoint `/api/print/job` (relative to printer's IP address) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go package main import ( "log" "github.com/pstrobl96/prusa_exporter/config" prusalink "github.com/pstrobl96/prusa_exporter/prusalink/buddy" ) func main() { printer := config.Printers{ Address: "192.168.1.100", Username: "maker", Password: "your_password", } job, err := prusalink.GetJob(printer) if err != nil { log.Fatal("Failed to get job:", err) } log.Printf("Job Name: %s", job.Job.File.Name) log.Printf("Progress: %.2f%%", job.Progress.Completion*100) log.Printf("Print Time: %.0f seconds", job.Progress.PrintTime) log.Printf("Time Remaining: %.0f seconds", job.Progress.PrintTimeLeft) if job.State == "Printing" { log.Println("Printer is actively printing") } } ``` ### Response #### Success Response (200) - **Job** (object) - Information about the current print job. - **File** (object) - **Name** (string) - The name of the print job file. - **Progress** (object) - The progress of the print job. - **Completion** (float64) - The completion percentage of the print job (0.0 to 1.0). - **PrintTime** (float64) - The elapsed print time in seconds. - **PrintTimeLeft** (float64) - The estimated time remaining in seconds. - **State** (string) - The current state of the printer (e.g., "Printing", "Paused"). #### Response Example ```json { "job": { "file": { "name": "example.3mf" } }, "progress": { "completion": 0.5, "print_time": 1800, "print_time_left": 1800 }, "state": "Printing" } ``` ``` -------------------------------- ### Get Prusa Printer Temperature and Status Source: https://context7.com/pubeldev/prusa_exporter/llms.txt This Go code retrieves real-time temperature and operational status for a Prusa printer. It uses `prusalink.GetPrinter` to fetch data including actual and target temperatures for the bed and nozzle, the printer's current state (text, operational flags, printing flags), and axis positions (X, Y, Z). ```go package main import ( "log" "github.com/pstrobl96/prusa_exporter/config" prusalink "github.com/pstrobl96/prusa_exporter/prusalink/buddy" ) func main() { printer := config.Printers{ Address: "192.168.1.100", Username: "maker", Password: "your_password", } printerData, err := prusalink.GetPrinter(printer) if err != nil { log.Fatal("Failed to get printer data:", err) } // Temperature information log.Printf("Bed Temperature: %.1f°C (Target: %.1f°C)", printerData.Temperature.Bed.Actual, printerData.Temperature.Bed.Target) log.Printf("Nozzle Temperature: %.1f°C (Target: %.1f°C)", printerData.Temperature.Tool0.Actual, printerData.Temperature.Tool0.Target) // Printer state log.Printf("State: %s", printerData.State.Text) log.Printf("Operational: %v", printerData.State.Flags.Operational) log.Printf("Printing: %v", printerData.State.Flags.Printing) // Axis positions log.Printf("X: %.2f, Y: %.2f, Z: %.2f", printerData.Telemetry.AxisX, printerData.Telemetry.AxisY, printerData.Telemetry.AxisZ) ``` -------------------------------- ### Configure Prusa Exporter with YAML Source: https://context7.com/pubeldev/prusa_exporter/llms.txt This snippet demonstrates how to set up the Prusa Exporter configuration using a YAML file. It specifies printer connection details such as address, username, password, name, and type. The `config.LoadConfig` function reads this YAML and initializes the exporter's configuration. ```yaml # prusa.yml printers: - address: 192.168.1.100 username: maker password: your_password name: MK4_Printer_1 type: MK4 - address: 192.168.1.101 username: maker password: another_password name: XL_Printer_2 type: XL ``` ```go package main import ( "log" "github.com/pstrobl96/prusa_exporter/config" ) func main() { cfg, err := config.LoadConfig( "./prusa.yml", 10, // scrapeTimeout in seconds "", // udpIPOverride (empty for auto-detect) false, // udpAllMetrics "", // udpExtraMetrics "", // lokiPushURL ) if err != nil { log.Fatal("Failed to load config:", err) } // Configuration loaded successfully for _, printer := range cfg.Printers { log.Printf("Configured printer: %s at %s (Type: %s)", printer.Name, printer.Address, printer.Type) } ``` -------------------------------- ### Customize Exporter Behavior with CLI Arguments (Bash) Source: https://context7.com/pubeldev/prusa_exporter/llms.txt Demonstrates how to customize the Prusa Exporter's behavior using command-line flags. This includes specifying configuration files, changing metric paths and ports, overriding UDP settings, enabling/disabling specific metrics, adjusting scrape timeouts, and integrating with Loki. ```bash # Basic usage with defaults ./prusa_exporter # Custom configuration file ./prusa_exporter --config.file=/etc/prusa/config.yml # Custom metrics paths ./prusa_exporter \ --exporter.metrics-path=/metrics/pl \ --exporter.udp-metrics-path=/metrics/syslog \ --exporter.metrics-port=9100 # Override UDP IP and enable all metrics (WARNING: impacts printer CPU) ./prusa_exporter \ --udp.ip-override=192.168.1.50 \ --udp.all-metrics=true # Add extra UDP metrics ./prusa_exporter --udp.extra-metrics="crash,power_panic,print_progress" # Custom scrape timeout and logging ./prusa_exporter \ --prusalink.scrape-timeout=15 \ --log.level=debug # Disable automatic UDP G-code configuration ./prusa_exporter --udp.gcode-enabled=false # Full example with Loki integration ./prusa_exporter \ --config.file=./prusa.yml \ --exporter.metrics-port=10009 \ --udp.listen-address=0.0.0.0:8514 \ --udp.prefix=prusa_ \ --loki.push-url=http://loki:3100/loki/api/v1/push \ --log.level=info ``` -------------------------------- ### Combined SYSLOG Configuration and Logging G-code Source: https://github.com/pubeldev/prusa_exporter/blob/main/docs/readme/udp_old_fw/UDP_OLD_FW.md This G-code snippet combines the SYSLOG server configuration (M330 and M334) with the command to send logs (M340). Remember to update the IP address and port to your specific SYSLOG server details. ```gcode M330 SYSLOG M334 192.168.20.2 10008 M340 192.168.20.2 10007 ``` -------------------------------- ### Probe Printer Connectivity (Go) Source: https://context7.com/pubeldev/prusa_exporter/llms.txt Tests the accessibility of Prusa printers before initiating data scraping. It configures the exporter with a scrape timeout and iterates through a list of printers, logging their online or offline status. This is crucial for ensuring reliable metric collection. ```go package main import ( "log" "github.com/pstrobl96/prusa_exporter/config" prusalink "github.com/pstrobl96/prusa_exporter/prusalink/buddy" ) func main() { cfg := config.Config{ Exporter: struct { ScrapeTimeout int LogLevel string IPOverride string AllMetricsUDP bool ExtraMetrics []string LokiPushURL string }{ ScrapeTimeout: 5000, // milliseconds }, } prusalink.SetConfiguration(cfg) printers := []config.Printers{ {Address: "192.168.1.100", Username: "maker", Password: "pass1"}, {Address: "192.168.1.101", Username: "maker", Password: "pass2"}, {Address: "192.168.1.102", Username: "maker", Password: "pass3"}, } for _, printer := range printers { reachable, err := prusalink.ProbePrinter(printer) if err != nil { log.Printf("Printer %s: ERROR - %v", printer.Address, err) continue } if reachable { log.Printf("Printer %s: ONLINE", printer.Address) } else { log.Printf("Printer %s: OFFLINE", printer.Address) } } } ``` -------------------------------- ### Configure SYSLOG Server with G-code Source: https://github.com/pubeldev/prusa_exporter/blob/main/docs/readme/udp_old_fw/UDP_OLD_FW.md These G-code commands are used to configure the SYSLOG server address and port on the Prusa printer. M330 enables SYSLOG, and M334 sets the IP address and port. You must manually edit the IP address and port to match your SYSLOG server. ```gcode M330 SYSLOG M334 192.168.20.2 10008 ``` -------------------------------- ### Access Prusa Link API for Printer Version Source: https://context7.com/pubeldev/prusa_exporter/llms.txt This Go code snippet shows how to retrieve version information from a Prusa printer using its Prusa Link API. It utilizes the `prusalink.GetVersion` function, which takes printer connection details as input and returns the API version, server version, and hostname. ```go package main import ( "log" "github.com/pstrobl96/prusa_exporter/config" prusalink "github.com/pstrobl96/prusa_exporter/prusalink/buddy" ) func main() { printer := config.Printers{ Address: "192.168.1.100", Username: "maker", Password: "your_password", Name: "MK4_Test", Type: "MK4", } // Get version information version, err := prusalink.GetVersion(printer) if err != nil { log.Fatal("Failed to get version:", err) } log.Printf("API Version: %s", version.API) log.Printf("Server Version: %s", version.Server) log.Printf("Hostname: %s", version.Hostname) ``` -------------------------------- ### Prusa Exporter Configuration Source: https://context7.com/pubeldev/prusa_exporter/llms.txt This section details how to configure the Prusa Exporter using a YAML file to load printer configurations. ```APIDOC ## Configuration File Setup ### Description Load printer configuration from YAML file. ### Method N/A (Configuration File) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```yaml # prusa.yml printers: - address: 192.168.1.100 username: maker password: your_password name: MK4_Printer_1 type: MK4 - address: 192.168.1.101 username: maker password: another_password name: XL_Printer_2 type: XL ``` ### Response #### Success Response (200) N/A (Configuration is loaded by the exporter) #### Response Example N/A ``` -------------------------------- ### Query Printer Storage Information (Go) Source: https://context7.com/pubeldev/prusa_exporter/llms.txt Retrieves storage details and file counts from a Prusa printer using the prusalink library. It requires printer connection details (address, username, password) as input and outputs storage path, free space, total space, and read-only status. ```go package main import ( "log" "github.com/pstrobl96/prusa_exporter/config" prusalink "github.com/pstrobl96/prusa_exporter/prusalink/buddy" ) func main() { printer := config.Printers{ Address: "192.168.1.100", Username: "maker", Password: "your_password", } storage, err := prusalink.GetStorageV1(printer) if err != nil { log.Fatal("Failed to get storage:", err) } for _, store := range storage.StorageList { log.Printf("Storage: %s", store.Path) log.Printf(" Free Space: %d bytes", store.FreeSpace) log.Printf(" Total Space: %d bytes", store.TotalSpace) log.Printf(" Read Only: %v", store.ReadOnly) } } ``` -------------------------------- ### Enable UDP Metrics via G-code for Prusa Printers Source: https://context7.com/pubeldev/prusa_exporter/llms.txt This Go code snippet configures Prusa printers to stream UDP metrics. It utilizes the prusa_exporter library to set exporter configurations and generate G-code commands (M330/M334/M331) to enable UDP metric streaming on specified printers. The configuration includes exporter settings like scrape timeout and IP override, and printer details such as address, credentials, and type. ```go package main import ( "log" "github.com/pstrobl96/prusa_exporter/config" prusalink "github.com/pstrobl96/prusa_exporter/prusalink/buddy" ) func main() { cfg := config.Config{ Exporter: struct { ScrapeTimeout int LogLevel string IPOverride string AllMetricsUDP bool ExtraMetrics []string LokiPushURL string }{ ScrapeTimeout: 10, IPOverride: "192.168.1.50", // exporter host IP AllMetricsUDP: false, ExtraMetrics: []string{"crash", "power_panic"}, }, Printers: []config.Printers{ { Address: "192.168.1.100", Username: "maker", Password: "your_password", Name: "MK4_Printer", Type: "MK4", }, }, } prusalink.SetConfiguration(cfg) // This generates G-code with metric configuration and uploads it to the printer // The G-code contains M330/M334/M331 commands to configure UDP metric streaming prusalink.EnableUDPmetrics(cfg.Printers) log.Println("UDP metrics enabled on all configured printers") } ``` -------------------------------- ### Send Printer Logs to SYSLOG Server with G-code Source: https://github.com/pubeldev/prusa_exporter/blob/main/docs/readme/udp_old_fw/UDP_OLD_FW.md The M340 G-code command is used to send printer logs to a specified SYSLOG server IP address and port. Ensure the IP address and port match your SYSLOG server configuration. ```gcode M340 192.168.20.2 10007 ``` -------------------------------- ### Retrieve Prusa Printer Print Job Status Source: https://context7.com/pubeldev/prusa_exporter/llms.txt This Go code fetches the current print job status from a Prusa printer. It uses the `prusalink.GetJob` function to obtain details about the active print job, including file name, completion percentage, print time, and time remaining. It also checks if the printer is currently in a 'Printing' state. ```go package main import ( "log" "github.com/pstrobl96/prusa_exporter/config" prusalink "github.com/pstrobl96/prusa_exporter/prusalink/buddy" ) func main() { printer := config.Printers{ Address: "192.168.1.100", Username: "maker", Password: "your_password", } job, err := prusalink.GetJob(printer) if err != nil { log.Fatal("Failed to get job:", err) } log.Printf("Job Name: %s", job.Job.File.Name) log.Printf("Progress: %.2f%%", job.Progress.Completion*100) log.Printf("Print Time: %.0f seconds", job.Progress.PrintTime) log.Printf("Time Remaining: %.0f seconds", job.Progress.PrintTimeLeft) if job.State == "Printing" { log.Println("Printer is actively printing") } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.