Backup & Wartung: Neustart, Firmware-Update, Werksreset, automatisches Wiederverbinden (#43, #44, #28)
Build / build (push) Canceled after 0s
Build / build (push) Canceled after 0s
- RouterMaintenanceService: Neustart, RouterBOARD-Firmware (upgrade + Neustart), Werksreset (no-defaults=no, skip-backup=no) nach eigener Sicherung - RouterOsReconnector + WizardSession.ReconnectAsync: Retry alle 5 s mit Zaehler in der Sidebar, erst erfolgreich wenn das Geraet auch antwortet (Mac v1.11.1) - Herzschlag alle 30 s bei aktivem Fenster, pausiert waehrend laengerer Aktionen - Nach Restore und RouterOS-Update wird automatisch wieder verbunden - RouterOsException.IsConnectionLost unterscheidet Abbruch von Ablehnung - Demo: RouterBOARD-Profile mit aelterer Firmware Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
de86a29fab
commit
3346129652
17 files changed
+579
-21
No files matched your search
@@ -1,4 +1,4 @@
|
||||
<ui:FluentWindow x:Class="MikrotikInstaller.App.MainWindow"
|
||||
<ui:FluentWindow x:Class="MikrotikInstaller.App.MainWindow"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
|
||||
@@ -62,6 +62,9 @@
|
||||
<TextBlock Text="Verbunden" FontSize="12" Opacity="0.7" VerticalAlignment="Center" />
|
||||
</StackPanel>
|
||||
<TextBlock Text="{Binding ConnectedDeviceLabel}" FontWeight="SemiBold" TextWrapping="Wrap" Margin="0,0,0,10" />
|
||||
<TextBlock Text="{Binding ConnectionState.StatusText}" FontSize="12" TextWrapping="Wrap" Margin="0,-4,0,10"
|
||||
Foreground="{StaticResource MikrotikWarningBrush}"
|
||||
Visibility="{Binding ConnectionState.StatusText, Converter={StaticResource StringToVisibilityConverter}}" />
|
||||
<ui:Button Content="Wechseln" Appearance="Secondary" HorizontalAlignment="Stretch"
|
||||
Command="{Binding SwitchConnectionCommand}" />
|
||||
</StackPanel>
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
|
||||
namespace MikrotikInstaller.App.ViewModels;
|
||||
|
||||
/// <summary>Beobachtbarer Zustand der Geräteverbindung für die Sidebar — v. a. ob gerade neu verbunden wird.</summary>
|
||||
public partial class ConnectionState : ObservableObject
|
||||
{
|
||||
[ObservableProperty]
|
||||
private bool _isReconnecting;
|
||||
|
||||
/// <summary>Hinweis unter „Verbunden", z. B. „Verbindung wird wiederhergestellt … (Versuch 3)".</summary>
|
||||
[ObservableProperty]
|
||||
private string? _statusText;
|
||||
}
|
||||
@@ -1,7 +1,10 @@
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Windows;
|
||||
using System.Windows.Threading;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using CommunityToolkit.Mvvm.Input;
|
||||
using MikrotikInstaller.App.ViewModels.Steps;
|
||||
using MikrotikInstaller.Core.Connectivity;
|
||||
|
||||
namespace MikrotikInstaller.App.ViewModels;
|
||||
|
||||
@@ -11,6 +14,7 @@ namespace MikrotikInstaller.App.ViewModels;
|
||||
public partial class MainViewModel : ObservableObject
|
||||
{
|
||||
private readonly WizardSession _session = new();
|
||||
private readonly DispatcherTimer _heartbeat = new() { Interval = TimeSpan.FromSeconds(30) };
|
||||
|
||||
public MainViewModel()
|
||||
{
|
||||
@@ -45,6 +49,42 @@ public partial class MainViewModel : ObservableObject
|
||||
}
|
||||
|
||||
CurrentStepIndex = 0;
|
||||
|
||||
_session.ConnectionEnded += (_, _) =>
|
||||
{
|
||||
Connection.IsConnected = false;
|
||||
OnPropertyChanged(nameof(ConnectedDeviceLabel));
|
||||
};
|
||||
_heartbeat.Tick += async (_, _) => await CheckConnectionAsync();
|
||||
_heartbeat.Start();
|
||||
}
|
||||
|
||||
public ConnectionState ConnectionState => _session.State;
|
||||
|
||||
/// <summary>
|
||||
/// Herzschlag alle 30 s, nur bei aktivem Fenster und ohne laufende längere Aktion (geringe Router-Last,
|
||||
/// Mac v1.3.0): fällt die Verbindung weg, wird automatisch neu verbunden.
|
||||
/// </summary>
|
||||
private async Task CheckConnectionAsync()
|
||||
{
|
||||
if (!Connection.IsConnected || _session.IsDeviceBusy || _session.State.IsReconnecting
|
||||
|| _session.Client is not { } client || Application.Current?.MainWindow?.IsActive != true)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
await client.GetAsync("/system/identity");
|
||||
}
|
||||
catch (RouterOsException ex) when (ex.IsConnectionLost)
|
||||
{
|
||||
await _session.ReconnectAsync(TimeSpan.Zero);
|
||||
}
|
||||
catch (RouterOsException)
|
||||
{
|
||||
// Das Gerät antwortet, lehnt nur ab — Verbindung besteht.
|
||||
}
|
||||
}
|
||||
|
||||
public ObservableCollection<WizardStepViewModelBase> Steps { get; }
|
||||
|
||||
@@ -16,7 +16,7 @@ public partial class AreaSelectionStepViewModel : WizardStepViewModelBase
|
||||
public AreaSelectionStepViewModel(WizardSession session)
|
||||
: base(
|
||||
title: "Was möchtest du tun?",
|
||||
description: "Wähle, ob du dein Gerät komplett neu einrichten oder nur ein Backup verwalten möchtest.")
|
||||
description: "Wähle, ob du dein Gerät komplett neu einrichten oder Backups und Wartung erledigen möchtest.")
|
||||
{
|
||||
_session = session;
|
||||
_isBackupManagement = session.SelectedArea == AppArea.BackupManagement;
|
||||
|
||||
@@ -4,6 +4,7 @@ using CommunityToolkit.Mvvm.Input;
|
||||
using MikrotikInstaller.Core.Backup;
|
||||
using MikrotikInstaller.Core.Connectivity;
|
||||
using MikrotikInstaller.Core.Devices;
|
||||
using MikrotikInstaller.Core.Maintenance;
|
||||
|
||||
namespace MikrotikInstaller.App.ViewModels.Steps;
|
||||
|
||||
@@ -21,8 +22,8 @@ public partial class BackupManagementStepViewModel : WizardStepViewModelBase
|
||||
|
||||
public BackupManagementStepViewModel(WizardSession session)
|
||||
: base(
|
||||
title: "Backup verwalten",
|
||||
description: "Vorhandene Backups auf diesem Gerät auflisten, ein neues erstellen oder eines zurückspielen.")
|
||||
title: "Backup & Wartung",
|
||||
description: "Backups auflisten, erstellen oder zurückspielen — und das Gerät neu starten, die Firmware aktualisieren oder auf Werkseinstellungen zurücksetzen.")
|
||||
{
|
||||
_session = session;
|
||||
}
|
||||
@@ -62,8 +63,28 @@ public partial class BackupManagementStepViewModel : WizardStepViewModelBase
|
||||
private string? _restoreProgressText;
|
||||
|
||||
[ObservableProperty]
|
||||
[NotifyPropertyChangedFor(nameof(ShowMainContent))]
|
||||
private bool _restoreFinished;
|
||||
|
||||
public bool ShowMainContent => !RestoreFinished && !FactoryResetDone;
|
||||
|
||||
/// <summary>RouterBOARD-Firmware (null bei Geräten ohne RouterBOARD oder wenn nicht lesbar).</summary>
|
||||
[ObservableProperty]
|
||||
[NotifyCanExecuteChangedFor(nameof(UpgradeFirmwareCommand))]
|
||||
private FirmwareInfo? _firmware;
|
||||
|
||||
[ObservableProperty]
|
||||
[NotifyCanExecuteChangedFor(nameof(FactoryResetCommand))]
|
||||
private bool _confirmFactoryReset;
|
||||
|
||||
[ObservableProperty]
|
||||
private string? _maintenanceMessage;
|
||||
|
||||
/// <summary>Nach dem Werksreset ist die Verbindung bewusst beendet — der Bereich zeigt nur noch den Abschluss-Hinweis.</summary>
|
||||
[ObservableProperty]
|
||||
[NotifyPropertyChangedFor(nameof(ShowMainContent))]
|
||||
private bool _factoryResetDone;
|
||||
|
||||
public override bool CanGoNext => true;
|
||||
|
||||
public override async Task OnActivatedAsync()
|
||||
@@ -77,6 +98,7 @@ public partial class BackupManagementStepViewModel : WizardStepViewModelBase
|
||||
ErrorMessage = null;
|
||||
CreateBackupMessage = null;
|
||||
RestoreFinished = false;
|
||||
FactoryResetDone = false;
|
||||
IsLoadingDevice = true;
|
||||
|
||||
try
|
||||
@@ -94,9 +116,132 @@ public partial class BackupManagementStepViewModel : WizardStepViewModelBase
|
||||
}
|
||||
|
||||
IsLoadingDevice = false;
|
||||
Firmware = await TryReadFirmwareAsync(_session.Client);
|
||||
await LoadBackupsAsync();
|
||||
}
|
||||
|
||||
private static async Task<FirmwareInfo?> TryReadFirmwareAsync(IRouterOsClient client)
|
||||
{
|
||||
try
|
||||
{
|
||||
var firmware = await RouterMaintenanceService.ReadFirmwareAsync(client);
|
||||
return firmware.IsRouterBoard ? firmware : null;
|
||||
}
|
||||
catch (RouterOsException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private bool CanRunMaintenance => !IsRestoring && _session.Client is not null;
|
||||
|
||||
[RelayCommand(CanExecute = nameof(CanRunMaintenance))]
|
||||
private Task RebootAsync() => RunWithReconnectAsync(
|
||||
"Das Gerät startet neu …",
|
||||
client => RouterMaintenanceService.RebootAsync(client),
|
||||
"Das Gerät wurde neu gestartet und ist wieder verbunden.");
|
||||
|
||||
private bool CanUpgradeFirmware => CanRunMaintenance && Firmware?.IsUpgradeAvailable == true;
|
||||
|
||||
/// <summary>Firmware einspielen und neu starten — sie wird erst nach dem Neustart aktiv.</summary>
|
||||
[RelayCommand(CanExecute = nameof(CanUpgradeFirmware))]
|
||||
private Task UpgradeFirmwareAsync() => RunWithReconnectAsync(
|
||||
"Firmware wird eingespielt, danach startet das Gerät neu …",
|
||||
async client =>
|
||||
{
|
||||
await RouterMaintenanceService.UpgradeFirmwareAsync(client);
|
||||
await RouterMaintenanceService.RebootAsync(client);
|
||||
},
|
||||
"Die Firmware wurde aktualisiert, das Gerät ist wieder verbunden.");
|
||||
|
||||
private bool CanFactoryReset => CanRunMaintenance && ConfirmFactoryReset;
|
||||
|
||||
/// <summary>
|
||||
/// Sichert zuerst den aktuellen Zustand (zusätzlich legt RouterOS selbst eins an), setzt dann zurück
|
||||
/// und beendet die Verbindung: danach gelten Standardadresse und Standard-Zugangsdaten, ein
|
||||
/// automatisches Wiederverbinden mit den alten Daten würde ins Leere laufen.
|
||||
/// </summary>
|
||||
[RelayCommand(CanExecute = nameof(CanFactoryReset))]
|
||||
private async Task FactoryResetAsync()
|
||||
{
|
||||
if (_session.Client is not { } client)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
SetBusy(true);
|
||||
try
|
||||
{
|
||||
RestoreProgressText = "Sicherung des aktuellen Zustands wird erstellt …";
|
||||
await RouterBackupService.CreateBackupAsync(client, Device?.BoardModel, Device?.Architecture, Device?.SerialNumber);
|
||||
|
||||
RestoreProgressText = "Gerät wird auf Werkseinstellungen zurückgesetzt …";
|
||||
await RouterMaintenanceService.FactoryResetAsync(client);
|
||||
await _session.EndConnectionAsync();
|
||||
FactoryResetDone = true;
|
||||
}
|
||||
catch (RouterOsException ex)
|
||||
{
|
||||
ErrorMessage = ex.Message;
|
||||
}
|
||||
finally
|
||||
{
|
||||
RestoreProgressText = null;
|
||||
ConfirmFactoryReset = false;
|
||||
SetBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Führt eine Aktion aus, nach der das Gerät neu startet, verbindet danach selbst wieder und liest alles neu ein.</summary>
|
||||
private async Task RunWithReconnectAsync(string progressText, Func<IRouterOsClient, Task> action, string successMessage)
|
||||
{
|
||||
if (_session.Client is not { } client)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
SetBusy(true);
|
||||
ErrorMessage = null;
|
||||
MaintenanceMessage = null;
|
||||
try
|
||||
{
|
||||
RestoreProgressText = progressText;
|
||||
await action(client);
|
||||
|
||||
RestoreProgressText = "Warte, bis das Gerät wieder erreichbar ist …";
|
||||
if (await _session.ReconnectAsync(TimeSpan.FromSeconds(15)))
|
||||
{
|
||||
SetBusy(false);
|
||||
await OnActivatedAsync();
|
||||
MaintenanceMessage = successMessage;
|
||||
}
|
||||
else
|
||||
{
|
||||
ErrorMessage = _session.State.StatusText;
|
||||
}
|
||||
}
|
||||
catch (RouterOsException ex)
|
||||
{
|
||||
ErrorMessage = ex.Message;
|
||||
}
|
||||
finally
|
||||
{
|
||||
RestoreProgressText = null;
|
||||
SetBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
private void SetBusy(bool busy)
|
||||
{
|
||||
IsRestoring = busy;
|
||||
_session.IsDeviceBusy = busy;
|
||||
CreateBackupNowCommand.NotifyCanExecuteChanged();
|
||||
RebootCommand.NotifyCanExecuteChanged();
|
||||
UpgradeFirmwareCommand.NotifyCanExecuteChanged();
|
||||
FactoryResetCommand.NotifyCanExecuteChanged();
|
||||
ApplyRestoreCommand.NotifyCanExecuteChanged();
|
||||
}
|
||||
|
||||
[RelayCommand]
|
||||
private Task Refresh() => LoadBackupsAsync();
|
||||
|
||||
@@ -141,10 +286,9 @@ public partial class BackupManagementStepViewModel : WizardStepViewModelBase
|
||||
return;
|
||||
}
|
||||
|
||||
IsRestoring = true;
|
||||
SetBusy(true);
|
||||
ErrorMessage = null;
|
||||
CreateBackupMessage = null;
|
||||
CreateBackupNowCommand.NotifyCanExecuteChanged();
|
||||
|
||||
try
|
||||
{
|
||||
@@ -163,8 +307,7 @@ public partial class BackupManagementStepViewModel : WizardStepViewModelBase
|
||||
}
|
||||
finally
|
||||
{
|
||||
IsRestoring = false;
|
||||
CreateBackupNowCommand.NotifyCanExecuteChanged();
|
||||
SetBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -186,9 +329,9 @@ public partial class BackupManagementStepViewModel : WizardStepViewModelBase
|
||||
return;
|
||||
}
|
||||
|
||||
IsRestoring = true;
|
||||
SetBusy(true);
|
||||
ErrorMessage = null;
|
||||
CreateBackupNowCommand.NotifyCanExecuteChanged();
|
||||
MaintenanceMessage = null;
|
||||
|
||||
try
|
||||
{
|
||||
@@ -199,8 +342,18 @@ public partial class BackupManagementStepViewModel : WizardStepViewModelBase
|
||||
await BackupRestoreService.RestoreAsync(
|
||||
_session.Client, SelectedBackup.Backup, Device?.BoardModel, Device?.Architecture, Device?.SerialNumber, ConfirmRiskyBackup, CancellationToken.None);
|
||||
|
||||
RestoreProgressText = null;
|
||||
RestoreFinished = true;
|
||||
|
||||
// Gerät startet nach dem Zurückspielen neu — danach selbst wieder verbinden (Mac v1.6.0).
|
||||
RestoreProgressText = "Warte, bis das Gerät nach dem Neustart wieder erreichbar ist …";
|
||||
if (await _session.ReconnectAsync(TimeSpan.FromSeconds(20)))
|
||||
{
|
||||
SetBusy(false);
|
||||
await OnActivatedAsync();
|
||||
MaintenanceMessage = "Das Backup wurde zurückgespielt, das Gerät ist wieder verbunden.";
|
||||
}
|
||||
|
||||
RestoreProgressText = null;
|
||||
}
|
||||
catch (RouterOsException ex)
|
||||
{
|
||||
@@ -212,8 +365,8 @@ public partial class BackupManagementStepViewModel : WizardStepViewModelBase
|
||||
}
|
||||
finally
|
||||
{
|
||||
IsRestoring = false;
|
||||
CreateBackupNowCommand.NotifyCanExecuteChanged();
|
||||
RestoreProgressText = null;
|
||||
SetBusy(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -120,15 +120,29 @@ public partial class UpdateStepViewModel : WizardStepViewModelBase
|
||||
|
||||
try
|
||||
{
|
||||
_session.IsDeviceBusy = true;
|
||||
await RouterOsUpdateService.StartUpdateAsync(_session.Client);
|
||||
IsUpdateStarted = true;
|
||||
|
||||
// Herunterladen + Neustart dauern; danach von selbst wieder verbinden (Mac v1.6.0).
|
||||
if (await _session.ReconnectAsync(TimeSpan.FromSeconds(30)))
|
||||
{
|
||||
await RecheckAsync();
|
||||
}
|
||||
}
|
||||
catch (RouterOsException ex)
|
||||
catch (RouterOsException ex) when (!ex.IsConnectionLost)
|
||||
{
|
||||
ErrorMessage = ex.Message;
|
||||
}
|
||||
catch (RouterOsException)
|
||||
{
|
||||
// Erwartet: das Gerät startet für das Update neu.
|
||||
IsUpdateStarted = true;
|
||||
await _session.ReconnectAsync(TimeSpan.FromSeconds(30));
|
||||
}
|
||||
finally
|
||||
{
|
||||
_session.IsDeviceBusy = false;
|
||||
IsUpdating = false;
|
||||
StartUpdateCommand.NotifyCanExecuteChanged();
|
||||
}
|
||||
|
||||
@@ -72,6 +72,62 @@ public sealed class WizardSession
|
||||
/// </summary>
|
||||
public RouterOsUpdateInfo? UpdateInfo { get; set; }
|
||||
|
||||
/// <summary>Verbindungsstatus für die Sidebar (Wiederverbinden nach Neustart/Abbruch).</summary>
|
||||
public ConnectionState State { get; } = new();
|
||||
|
||||
/// <summary>Während Backup, Restore, Werksreset oder Anwenden pausiert die Herzschlag-Prüfung (Mac v1.6.0).</summary>
|
||||
public bool IsDeviceBusy { get; set; }
|
||||
|
||||
/// <summary>Die Verbindung ist endgültig vorbei (z. B. nach Werksreset) — die Sidebar zeigt wieder „Nicht verbunden".</summary>
|
||||
public event EventHandler? ConnectionEnded;
|
||||
|
||||
public async Task EndConnectionAsync()
|
||||
{
|
||||
await DisposeClientAsync();
|
||||
Device = null;
|
||||
State.StatusText = null;
|
||||
ConnectionEnded?.Invoke(this, EventArgs.Empty);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Baut die Verbindung mit den zuletzt genutzten Zugangsdaten neu auf, z. B. nach einem Neustart.
|
||||
/// <paramref name="initialDelay"/> gibt dem Gerät Zeit, tatsächlich herunterzufahren — sonst würde man
|
||||
/// sich noch mit dem alten, gerade abschaltenden System verbinden. Gibt false zurück, wenn das Gerät
|
||||
/// nach etwa 5 Minuten noch nicht erreichbar ist.
|
||||
/// </summary>
|
||||
public async Task<bool> ReconnectAsync(TimeSpan initialDelay)
|
||||
{
|
||||
if (Credentials is not { } credentials || State.IsReconnecting)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
State.IsReconnecting = true;
|
||||
State.StatusText = "Warte auf das Gerät …";
|
||||
await DisposeClientAsync();
|
||||
|
||||
try
|
||||
{
|
||||
Client = await RouterOsReconnector.ReconnectAsync(
|
||||
ct => RouterOsClientFactory.ConnectAsync(credentials, ct),
|
||||
initialDelay,
|
||||
retryDelay: TimeSpan.FromSeconds(5),
|
||||
maxAttempts: 60,
|
||||
attempt => State.StatusText = $"Verbindung wird wiederhergestellt … (Versuch {attempt})");
|
||||
State.StatusText = null;
|
||||
return true;
|
||||
}
|
||||
catch (RouterOsException)
|
||||
{
|
||||
State.StatusText = "Gerät nicht erreichbar. Bitte über „Wechseln“ neu verbinden.";
|
||||
return false;
|
||||
}
|
||||
finally
|
||||
{
|
||||
State.IsReconnecting = false;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task DisposeClientAsync()
|
||||
{
|
||||
if (Client is not null)
|
||||
|
||||
@@ -33,8 +33,8 @@
|
||||
<RadioButton Grid.Column="0" GroupName="AppArea" VerticalAlignment="Top" Margin="0,2,12,0"
|
||||
IsChecked="{Binding IsBackupManagement}" />
|
||||
<StackPanel Grid.Column="1">
|
||||
<TextBlock Text="Backup verwalten" FontWeight="SemiBold" />
|
||||
<TextBlock Text="Direkt zu vorhandenen Backups auf diesem Gerät — auflisten, neu erstellen oder ein Backup zurückspielen. Überspringt den restlichen Einrichtungs-Assistenten komplett." TextWrapping="Wrap" Opacity="0.8" Margin="0,4,0,0" />
|
||||
<TextBlock Text="Backup & Wartung" FontWeight="SemiBold" />
|
||||
<TextBlock Text="Backups auflisten, erstellen oder zurückspielen, das Gerät neu starten, die Firmware aktualisieren oder auf Werkseinstellungen zurücksetzen. Überspringt den restlichen Einrichtungs-Assistenten komplett." TextWrapping="Wrap" Opacity="0.8" Margin="0,4,0,0" />
|
||||
</StackPanel>
|
||||
</Grid>
|
||||
</Border>
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:ui="http://schemas.lepo.co/wpfui/2022/xaml"
|
||||
xmlns:controls="clr-namespace:MikrotikInstaller.App.Views.Controls"
|
||||
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
|
||||
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
|
||||
mc:Ignorable="d"
|
||||
@@ -25,7 +26,10 @@
|
||||
<TextBlock Text="{Binding ErrorMessage}" TextWrapping="Wrap" Foreground="{StaticResource MikrotikRedBrush}" Margin="0,0,0,16"
|
||||
Visibility="{Binding ErrorMessage, Converter={StaticResource StringToVisibilityConverter}}" />
|
||||
|
||||
<StackPanel Visibility="{Binding RestoreFinished, Converter={StaticResource BoolToVisibilityConverter}, ConverterParameter=Invert}">
|
||||
<TextBlock Text="{Binding MaintenanceMessage}" TextWrapping="Wrap" Foreground="{StaticResource MikrotikAccentBrush}" FontWeight="SemiBold" Margin="0,0,0,16"
|
||||
Visibility="{Binding MaintenanceMessage, Converter={StaticResource StringToVisibilityConverter}}" />
|
||||
|
||||
<StackPanel Visibility="{Binding ShowMainContent, Converter={StaticResource BoolToVisibilityConverter}}">
|
||||
<StackPanel Orientation="Horizontal" Margin="0,0,0,12">
|
||||
<TextBlock Text="Vorhandene Backups auf diesem Gerät" FontSize="16" FontWeight="SemiBold" VerticalAlignment="Center" />
|
||||
<ui:Button Content="Aktualisieren" Appearance="Secondary" Margin="12,0,0,0"
|
||||
@@ -131,6 +135,56 @@
|
||||
<ui:ProgressRing IsIndeterminate="True" Width="20" Height="20" Margin="0,0,12,0" />
|
||||
<TextBlock Text="{Binding RestoreProgressText}" VerticalAlignment="Center" TextWrapping="Wrap" />
|
||||
</StackPanel>
|
||||
|
||||
<!-- Wartung (Issue #28, #44): Neustart, RouterBOARD-Firmware, Werksreset. -->
|
||||
<TextBlock Text="Wartung" FontSize="16" FontWeight="SemiBold" Margin="0,32,0,12" />
|
||||
|
||||
<Border BorderBrush="{DynamicResource DividerStrokeColorDefaultBrush}" BorderThickness="1" CornerRadius="6" Padding="16" Margin="0,0,0,12">
|
||||
<StackPanel>
|
||||
<StackPanel Orientation="Horizontal">
|
||||
<TextBlock Text="Neu starten" FontWeight="SemiBold" VerticalAlignment="Center" />
|
||||
<controls:InfoHint Text="Startet den Router neu. Die Verbindung bricht kurz ab, der Assistent verbindet sich danach von selbst wieder." />
|
||||
</StackPanel>
|
||||
<ui:Button Content="Jetzt neu starten" Appearance="Secondary" Margin="0,8,0,0" Command="{Binding RebootCommand}">
|
||||
<ui:Button.Icon>
|
||||
<ui:SymbolIcon Symbol="ArrowClockwise24" />
|
||||
</ui:Button.Icon>
|
||||
</ui:Button>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
|
||||
<Border BorderBrush="{DynamicResource DividerStrokeColorDefaultBrush}" BorderThickness="1" CornerRadius="6" Padding="16" Margin="0,0,0,12"
|
||||
Visibility="{Binding Firmware, Converter={StaticResource NullToVisibilityConverter}}">
|
||||
<StackPanel>
|
||||
<StackPanel Orientation="Horizontal">
|
||||
<TextBlock Text="RouterBOARD-Firmware" FontWeight="SemiBold" VerticalAlignment="Center" />
|
||||
<controls:InfoHint Text="Die Firmware ist das Startprogramm der Hardware, getrennt von RouterOS. Eine neue Version kommt mit einem RouterOS-Update mit und wird erst nach Einspielen und Neustart aktiv." />
|
||||
</StackPanel>
|
||||
<TextBlock Margin="0,4,0,0">
|
||||
<Run Text="Installiert: " Foreground="{DynamicResource TextFillColorSecondaryBrush}" />
|
||||
<Run Text="{Binding Firmware.CurrentFirmware, Mode=OneWay}" />
|
||||
<Run Text=" Verfügbar: " Foreground="{DynamicResource TextFillColorSecondaryBrush}" />
|
||||
<Run Text="{Binding Firmware.UpgradeFirmware, Mode=OneWay}" />
|
||||
</TextBlock>
|
||||
<ui:Button Content="Firmware aktualisieren und neu starten" Appearance="Secondary" Margin="0,8,0,0" Command="{Binding UpgradeFirmwareCommand}" />
|
||||
</StackPanel>
|
||||
</Border>
|
||||
|
||||
<Border BorderBrush="{StaticResource MikrotikRedBrush}" BorderThickness="1" CornerRadius="6" Padding="16">
|
||||
<StackPanel>
|
||||
<TextBlock Text="Werkseinstellungen wiederherstellen" FontWeight="SemiBold" Foreground="{StaticResource MikrotikRedBrush}" />
|
||||
<TextBlock TextWrapping="Wrap" Margin="0,4,0,8"
|
||||
Text="Notfallschalter: setzt das Gerät auf die MikroTik-Werkseinstellungen zurück. Vorher wird eine Sicherung erstellt. Danach ist das Gerät meist nur noch unter 192.168.88.1 mit dem Benutzer „admin“ und dem Passwort vom Aufkleber (oder leer) erreichbar." />
|
||||
<CheckBox Content="Ich habe verstanden, dass die aktuelle Konfiguration dabei gelöscht wird." IsChecked="{Binding ConfirmFactoryReset}" Margin="0,0,0,8" />
|
||||
<ui:Button Content="Auf Werkseinstellungen zurücksetzen" Appearance="Danger" Command="{Binding FactoryResetCommand}" />
|
||||
</StackPanel>
|
||||
</Border>
|
||||
</StackPanel>
|
||||
|
||||
<StackPanel Visibility="{Binding FactoryResetDone, Converter={StaticResource BoolToVisibilityConverter}}">
|
||||
<TextBlock Text="Das Gerät wird zurückgesetzt." FontWeight="SemiBold" Foreground="{StaticResource MikrotikAccentBrush}" Margin="0,0,0,8" />
|
||||
<TextBlock TextWrapping="Wrap" Opacity="0.8"
|
||||
Text="Die Verbindung wurde beendet. Nach dem Neustart ist das Gerät in der Regel unter 192.168.88.1 erreichbar — verbinde dich im ersten Schritt neu. Vor dem Zurücksetzen wurde eine Sicherung erstellt, die du danach unter „Backup & Wartung“ zurückspielen kannst." />
|
||||
</StackPanel>
|
||||
|
||||
<StackPanel Visibility="{Binding RestoreFinished, Converter={StaticResource BoolToVisibilityConverter}}">
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
using MikrotikInstaller.Core.Connectivity;
|
||||
using MikrotikInstaller.Core.Tests.Configuration;
|
||||
|
||||
namespace MikrotikInstaller.Core.Tests.Connectivity;
|
||||
|
||||
public class RouterOsReconnectorTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task ReconnectAsync_RetriesUntilDeviceAnswers()
|
||||
{
|
||||
var attempts = new List<int>();
|
||||
var calls = 0;
|
||||
|
||||
var client = await RouterOsReconnector.ReconnectAsync(
|
||||
_ => ++calls < 3
|
||||
? throw new RouterOsException("noch nicht da") { IsConnectionLost = true }
|
||||
: Task.FromResult<IRouterOsClient>(new RecordingRouterOsClient()),
|
||||
TimeSpan.Zero, TimeSpan.Zero, maxAttempts: 10, attempts.Add);
|
||||
|
||||
Assert.NotNull(client);
|
||||
Assert.Equal([1, 2, 3], attempts);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ReconnectAsync_GivesUpAfterMaxAttempts()
|
||||
{
|
||||
await Assert.ThrowsAsync<RouterOsException>(() => RouterOsReconnector.ReconnectAsync(
|
||||
_ => throw new RouterOsException("weg"), TimeSpan.Zero, TimeSpan.Zero, maxAttempts: 3));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
using MikrotikInstaller.Core.Connectivity;
|
||||
using MikrotikInstaller.Core.Maintenance;
|
||||
using MikrotikInstaller.Core.Tests.Configuration;
|
||||
|
||||
namespace MikrotikInstaller.Core.Tests.Maintenance;
|
||||
|
||||
public class RouterMaintenanceServiceTests
|
||||
{
|
||||
[Theory]
|
||||
[InlineData("yes", "7.12", "7.15.2", true)]
|
||||
[InlineData("yes", "7.15.2", "7.15.2", false)]
|
||||
[InlineData("no", null, null, false)]
|
||||
public async Task ReadFirmwareAsync_DetectsAvailableUpgrade(string routerboard, string? current, string? upgrade, bool expected)
|
||||
{
|
||||
var row = new Dictionary<string, string> { ["routerboard"] = routerboard };
|
||||
if (current is not null)
|
||||
{
|
||||
row["current-firmware"] = current;
|
||||
}
|
||||
|
||||
if (upgrade is not null)
|
||||
{
|
||||
row["upgrade-firmware"] = upgrade;
|
||||
}
|
||||
|
||||
var client = new RecordingRouterOsClient();
|
||||
client.GetResponses["/system/routerboard"] = [row];
|
||||
|
||||
var info = await RouterMaintenanceService.ReadFirmwareAsync(client);
|
||||
|
||||
Assert.Equal(expected, info.IsUpgradeAvailable);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task FactoryResetAsync_RestoresVendorDefaultsWithBackup()
|
||||
{
|
||||
var client = new RecordingRouterOsClient();
|
||||
|
||||
await RouterMaintenanceService.FactoryResetAsync(client);
|
||||
|
||||
var call = Assert.Single(client.ExecuteCalls);
|
||||
Assert.Equal("/system/reset-configuration", call.Path);
|
||||
Assert.Equal("no", call.Parameters!["no-defaults"]);
|
||||
Assert.Equal("no", call.Parameters!["skip-backup"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RebootAsync_ConnectionDropIsSuccess_RejectionIsNot()
|
||||
{
|
||||
await RouterMaintenanceService.RebootAsync(new ThrowingClient(new RouterOsException("weg") { IsConnectionLost = true }));
|
||||
await Assert.ThrowsAsync<RouterOsException>(() =>
|
||||
RouterMaintenanceService.RebootAsync(new ThrowingClient(new RouterOsException("keine Rechte"))));
|
||||
}
|
||||
|
||||
private sealed class ThrowingClient(RouterOsException error) : IRouterOsClient
|
||||
{
|
||||
public RouterOsProtocol Protocol => RouterOsProtocol.Rest;
|
||||
|
||||
public Task<IReadOnlyList<IReadOnlyDictionary<string, string>>> GetAsync(string path, CancellationToken cancellationToken = default) => throw error;
|
||||
|
||||
public Task<string> AddAsync(string path, IReadOnlyDictionary<string, string> parameters, CancellationToken cancellationToken = default) => throw error;
|
||||
|
||||
public Task SetAsync(string path, string id, IReadOnlyDictionary<string, string> parameters, CancellationToken cancellationToken = default) => throw error;
|
||||
|
||||
public Task RemoveAsync(string path, string id, CancellationToken cancellationToken = default) => throw error;
|
||||
|
||||
public Task ExecuteAsync(string path, IReadOnlyDictionary<string, string>? parameters = null, CancellationToken cancellationToken = default) => Task.FromException(error);
|
||||
|
||||
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
|
||||
}
|
||||
}
|
||||
@@ -210,12 +210,12 @@ public sealed class BinaryRouterOsClient : IRouterOsClient
|
||||
{
|
||||
// Nach einem Zeitlimit mitten in einer Antwort ist die Reihenfolge nicht mehr verlässlich.
|
||||
_isBroken = true;
|
||||
throw new RouterOsException("Das Gerät hat nicht rechtzeitig geantwortet.");
|
||||
throw new RouterOsException("Das Gerät hat nicht rechtzeitig geantwortet.") { IsConnectionLost = true };
|
||||
}
|
||||
catch (IOException ex)
|
||||
{
|
||||
_isBroken = true;
|
||||
throw new RouterOsException("Die Verbindung zum Gerät wurde unterbrochen.", ex);
|
||||
throw new RouterOsException("Die Verbindung zum Gerät wurde unterbrochen.", ex) { IsConnectionLost = true };
|
||||
}
|
||||
finally
|
||||
{
|
||||
|
||||
@@ -138,6 +138,15 @@ public sealed class DemoRouterOsClient : IRouterOsClient
|
||||
});
|
||||
}
|
||||
|
||||
// Simuliert "/system/routerboard/upgrade": die mitgelieferte Firmware gilt danach als installiert.
|
||||
if (Normalize(path) == "/system/routerboard/upgrade" && _data.TryGetValue("/system/routerboard", out var boards))
|
||||
{
|
||||
foreach (var board in boards.Where(b => b.ContainsKey("upgrade-firmware")))
|
||||
{
|
||||
board["current-firmware"] = board["upgrade-firmware"];
|
||||
}
|
||||
}
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
@@ -254,6 +263,9 @@ public sealed class DemoRouterOsClient : IRouterOsClient
|
||||
if (profile.IsRouterBoard)
|
||||
{
|
||||
row["model"] = profile.BoardModel;
|
||||
// Ältere Firmware als die mit RouterOS mitgelieferte — damit "Firmware aktualisieren" etwas zu tun hat.
|
||||
row["current-firmware"] = "7.12.1";
|
||||
row["upgrade-firmware"] = "7.15.2";
|
||||
}
|
||||
|
||||
if (profile.SerialNumber is not null)
|
||||
|
||||
@@ -146,11 +146,11 @@ public sealed class RestRouterOsClient : IRouterOsClient
|
||||
}
|
||||
catch (OperationCanceledException ex) when (!cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
throw new RouterOsException("Das Gerät hat nicht rechtzeitig geantwortet.", ex);
|
||||
throw new RouterOsException("Das Gerät hat nicht rechtzeitig geantwortet.", ex) { IsConnectionLost = true };
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
throw new RouterOsException("Die Verbindung zum Gerät wurde unterbrochen.", ex);
|
||||
throw new RouterOsException("Die Verbindung zum Gerät wurde unterbrochen.", ex) { IsConnectionLost = true };
|
||||
}
|
||||
|
||||
if (!response.IsSuccessStatusCode)
|
||||
|
||||
@@ -10,4 +10,10 @@ public sealed class RouterOsException : Exception
|
||||
: base(userFriendlyMessage, inner)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Die Verbindung selbst ist weg (Zeitüberschreitung, Abbruch) — anders als eine Ablehnung durch das
|
||||
/// Gerät. Nach Neustart/Werksreset erwartet, sonst Anlass zum automatischen Wiederverbinden.
|
||||
/// </summary>
|
||||
public bool IsConnectionLost { get; init; }
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
namespace MikrotikInstaller.Core.Connectivity;
|
||||
|
||||
/// <summary>
|
||||
/// Stellt eine verlorene Verbindung wieder her, z. B. nach Neustart, Werksreset, Update oder Restore.
|
||||
/// Versucht es alle <c>retryDelay</c> erneut, bis es klappt oder <c>maxAttempts</c> erreicht sind.
|
||||
/// Ein Verbindungsversuch gilt erst als geglückt, wenn das Gerät auch antwortet — direkt nach dem
|
||||
/// Hochfahren nimmt RouterOS Verbindungen teils schon an, beantwortet aber noch keine Abfrage (Mac v1.11.1).
|
||||
/// </summary>
|
||||
public static class RouterOsReconnector
|
||||
{
|
||||
public static async Task<IRouterOsClient> ReconnectAsync(
|
||||
Func<CancellationToken, Task<IRouterOsClient>> connect,
|
||||
TimeSpan initialDelay,
|
||||
TimeSpan retryDelay,
|
||||
int maxAttempts,
|
||||
Action<int>? onAttempt = null,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
await Task.Delay(initialDelay, cancellationToken);
|
||||
|
||||
for (var attempt = 1; ; attempt++)
|
||||
{
|
||||
onAttempt?.Invoke(attempt);
|
||||
IRouterOsClient? client = null;
|
||||
try
|
||||
{
|
||||
client = await connect(cancellationToken);
|
||||
await client.GetAsync("/system/identity", cancellationToken);
|
||||
return client;
|
||||
}
|
||||
catch (RouterOsException) when (attempt < maxAttempts)
|
||||
{
|
||||
if (client is not null)
|
||||
{
|
||||
await client.DisposeAsync();
|
||||
}
|
||||
}
|
||||
|
||||
await Task.Delay(retryDelay, cancellationToken);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
using MikrotikInstaller.Core.Connectivity;
|
||||
|
||||
namespace MikrotikInstaller.Core.Maintenance;
|
||||
|
||||
/// <summary>Stand der RouterBOARD-Firmware (Bootloader) — nur auf echter RouterBOARD-Hardware vorhanden, nicht z. B. auf einem CHR.</summary>
|
||||
public sealed record FirmwareInfo(bool IsRouterBoard, string? CurrentFirmware, string? UpgradeFirmware)
|
||||
{
|
||||
/// <summary>Die neue Firmware kommt mit einem RouterOS-Update mit und wird erst durch "upgrade" + Neustart aktiv.</summary>
|
||||
public bool IsUpgradeAvailable =>
|
||||
IsRouterBoard && !string.IsNullOrWhiteSpace(UpgradeFirmware) && !string.IsNullOrWhiteSpace(CurrentFirmware)
|
||||
&& !string.Equals(CurrentFirmware, UpgradeFirmware, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Einmalige Systemaktionen: Neustart, Werksreset, RouterBOARD-Firmware-Update. Bei Neustart und
|
||||
/// Werksreset reißt die Verbindung oft schon ab, bevor das Gerät antwortet — das ist hier der Erfolgsfall,
|
||||
/// kein Fehler. Eine echte Ablehnung durch das Gerät (z. B. fehlende Rechte) wird weitergereicht.
|
||||
/// </summary>
|
||||
public static class RouterMaintenanceService
|
||||
{
|
||||
public static async Task<FirmwareInfo> ReadFirmwareAsync(IRouterOsClient client, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var row = (await client.GetAsync("/system/routerboard", cancellationToken)).FirstOrDefault();
|
||||
if (row is null)
|
||||
{
|
||||
return new FirmwareInfo(false, null, null);
|
||||
}
|
||||
|
||||
var isRouterBoard = row.GetValueOrDefault("routerboard") is "yes" or "true";
|
||||
return new FirmwareInfo(isRouterBoard, row.GetValueOrDefault("current-firmware"), row.GetValueOrDefault("upgrade-firmware"));
|
||||
}
|
||||
|
||||
/// <summary>Spielt die mitgelieferte Firmware ein. Wird erst nach einem Neustart aktiv (nicht automatisch).</summary>
|
||||
public static Task UpgradeFirmwareAsync(IRouterOsClient client, CancellationToken cancellationToken = default) =>
|
||||
client.ExecuteAsync("/system/routerboard/upgrade", cancellationToken: cancellationToken);
|
||||
|
||||
public static Task RebootAsync(IRouterOsClient client, CancellationToken cancellationToken = default) =>
|
||||
IgnoreConnectionLossAsync(client.ExecuteAsync("/system/reboot", cancellationToken: cancellationToken));
|
||||
|
||||
/// <summary>
|
||||
/// Setzt auf die MikroTik-Werkseinstellungen zurück (nicht auf eine leere Konfiguration:
|
||||
/// <c>no-defaults=no</c>) und lässt RouterOS vorher selbst ein Backup ablegen (<c>skip-backup=no</c>).
|
||||
/// Danach ist das Gerät meist nur noch unter seiner Standardadresse (192.168.88.1) erreichbar.
|
||||
/// </summary>
|
||||
public static Task FactoryResetAsync(IRouterOsClient client, CancellationToken cancellationToken = default) =>
|
||||
IgnoreConnectionLossAsync(client.ExecuteAsync("/system/reset-configuration", new Dictionary<string, string>
|
||||
{
|
||||
["no-defaults"] = "no",
|
||||
["skip-backup"] = "no",
|
||||
}, cancellationToken));
|
||||
|
||||
private static async Task IgnoreConnectionLossAsync(Task command)
|
||||
{
|
||||
try
|
||||
{
|
||||
await command;
|
||||
}
|
||||
catch (RouterOsException ex) when (ex.IsConnectionLost)
|
||||
{
|
||||
// Erwartet: das Gerät startet bereits neu.
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user