examples/System-Management.ps1

<#
.SYNOPSIS
    System management and update examples.

.DESCRIPTION
    Demonstrates system control functions including emergency stop,
    service restarts, update management, and system monitoring.
#>


Import-Module KlippyCLI

#region Emergency Controls

# EMERGENCY STOP - Use with caution!
# Immediately stops all motion and heaters
# Requires typing 'STOP' to confirm
Stop-KlippyEmergency

# After emergency stop, you'll need to restart firmware
Restart-KlippyFirmware

# Wait for Klipper to become ready again
Wait-KlippyReady -Timeout 120

#endregion

#region Firmware and Service Control

# Restart Klipper firmware (soft restart)
Restart-KlippyFirmware

# Restart with wait for ready
Restart-KlippyFirmware -Wait

# Restart Moonraker service
Restart-KlippyService -Service "moonraker"

# Restart Klipper service
Restart-KlippyService -Service "klipper"

#endregion

#region Host Control

# Reboot the host machine (Raspberry Pi, etc.)
# WARNING: This will reboot the entire system!
Restart-KlippyHost -Force

# Shutdown the host machine
# WARNING: This will shutdown the system!
Stop-KlippyHost -Force

#endregion

#region Update Management

# Check for available updates
Get-KlippyUpdate | Format-Table Name, Version, RemoteVersion, UpdateAvailable

# Refresh update status from remote
Get-KlippyUpdate -Refresh

# Check specific component
Get-KlippyUpdate | Where-Object Name -eq "klipper"

# Find all components with available updates
Get-KlippyUpdate | Where-Object UpdateAvailable | Format-Table Name, Version, RemoteVersion

#endregion

#region Apply Updates

# Update a specific component
Update-KlippyComponent -Component "klipper"

# Update via pipeline
Get-KlippyUpdate | Where-Object Name -eq "moonraker" | Update-KlippyComponent

# Update all components with available updates
Update-KlippyComponent -All

# Update workflow with confirmation
$updates = Get-KlippyUpdate | Where-Object UpdateAvailable
if ($updates) {
    Write-Host "Available updates:" -ForegroundColor Cyan
    $updates | Format-Table Name, Version, RemoteVersion

    $confirm = Read-Host "Apply all updates? (y/n)"
    if ($confirm -eq 'y') {
        Update-KlippyComponent -All
    }
}
else {
    Write-Host "All components are up to date!" -ForegroundColor Green
}

#endregion

#region System Information

# Get Moonraker server info
Get-KlippyServerInfo | Format-List

# Get machine/host information
Get-KlippyMachineInfo | Format-List

# Get network configuration
Get-KlippyNetworkInfo | Format-List

# Get service status
Get-KlippyServiceStatus | Format-Table Name, ActiveState, SubState

# List connected USB devices
Get-KlippyUsbDevice | Format-Table Description, Manufacturer, VendorId, ProductId

# List serial devices
Get-KlippySerialDevice | Format-Table Path, HardwarePath

#endregion

#region Announcements

# Get RSS announcements (Klipper updates, Moonraker news)
Get-KlippyAnnouncement | Format-Table Title, Category, DatePosted

# Get all announcements including dismissed
Get-KlippyAnnouncement -IncludeDismissed

# View announcement details
Get-KlippyAnnouncement | Select-Object -First 1 | Format-List Title, Description, Url, Priority

#endregion

#region Automated Maintenance

function Invoke-PrinterMaintenance {
    <#
    .SYNOPSIS
        Automated maintenance routine
    #>

    param(
        [string]$PrinterName,
        [switch]$ApplyUpdates
    )

    Write-Host "=== Printer Maintenance: $PrinterName ===" -ForegroundColor Cyan

    # 1. Check printer status
    Write-Host "`n[1/5] Checking printer status..."
    $status = Get-KlippyStatus -PrinterName $PrinterName
    if ($status.State -eq "printing") {
        Write-Warning "Printer is currently printing. Skipping maintenance."
        return
    }
    Write-Host " Status: $($status.State)"

    # 2. Check for updates
    Write-Host "`n[2/5] Checking for updates..."
    $updates = Get-KlippyUpdate -PrinterName $PrinterName -Refresh
    $availableUpdates = $updates | Where-Object UpdateAvailable
    if ($availableUpdates) {
        Write-Host " Available updates: $($availableUpdates.Count)"
        $availableUpdates | ForEach-Object {
            Write-Host " - $($_.Name): $($_.Version) -> $($_.RemoteVersion)"
        }

        if ($ApplyUpdates) {
            Write-Host " Applying updates..."
            Update-KlippyComponent -PrinterName $PrinterName -All
        }
    }
    else {
        Write-Host " All components up to date"
    }

    # 3. Check services
    Write-Host "`n[3/5] Checking services..."
    $services = Get-KlippyServiceStatus -PrinterName $PrinterName
    $problemServices = $services | Where-Object { $_.ActiveState -ne 'active' }
    if ($problemServices) {
        Write-Warning " Services not active:"
        $problemServices | ForEach-Object { Write-Warning " - $($_.Name): $($_.ActiveState)" }
    }
    else {
        Write-Host " All services running"
    }

    # 4. Check temperatures (ensure nothing is unexpectedly hot)
    Write-Host "`n[4/5] Checking temperatures..."
    $heaters = Get-KlippyHeater -PrinterName $PrinterName
    $hotHeaters = $heaters | Where-Object { $_.Temperature -gt 50 }
    if ($hotHeaters) {
        Write-Warning " Hot heaters detected:"
        $hotHeaters | ForEach-Object { Write-Warning " - $($_.Name): $($_.Temperature)C" }
    }
    else {
        Write-Host " All heaters at safe temperature"
    }

    # 5. Print statistics summary
    Write-Host "`n[5/5] Print statistics..."
    $totals = Get-KlippyPrintHistoryTotals -PrinterName $PrinterName
    Write-Host " Total prints: $($totals.TotalJobs)"
    Write-Host " Total print time: $($totals.TotalPrintTime.ToString('d\.hh\:mm'))"
    Write-Host " Filament used: $($totals.TotalFilamentUsed) meters"

    Write-Host "`n=== Maintenance Complete ===" -ForegroundColor Green
}

# Run maintenance on all printers
Get-KlippyPrinter | ForEach-Object {
    Invoke-PrinterMaintenance -PrinterName $_.PrinterName -ApplyUpdates
}

#endregion

#region Config Backup

function Backup-PrinterConfig {
    <#
    .SYNOPSIS
        Backup all configuration files from a printer
    #>

    param(
        [string]$PrinterName,
        [string]$BackupFolder
    )

    $timestamp = Get-Date -Format "yyyyMMdd_HHmmss"
    $printerBackupFolder = Join-Path $BackupFolder "${PrinterName}_$timestamp"

    New-Item -ItemType Directory -Path $printerBackupFolder -Force | Out-Null

    Write-Host "Backing up config for $PrinterName..."

    # Get and save all config files
    $configs = Get-KlippyConfigFile -PrinterName $PrinterName
    foreach ($config in $configs) {
        $destPath = Join-Path $printerBackupFolder $config.Path
        $destDir = Split-Path $destPath -Parent
        if (-not (Test-Path $destDir)) {
            New-Item -ItemType Directory -Path $destDir -Force | Out-Null
        }
        Save-KlippyConfigFile -PrinterName $PrinterName -FileName $config.Path -Destination $destPath
        Write-Host " Saved: $($config.Path)"
    }

    Write-Host "Backup complete: $printerBackupFolder" -ForegroundColor Green
}

# Backup all printers
Get-KlippyPrinter | ForEach-Object {
    Backup-PrinterConfig -PrinterName $_.PrinterName -BackupFolder "C:\PrinterBackups"
}

#endregion