借助网络配置,控制Modbus工具的日志显示,避免卡死界面
智能大石头 authored at 2021-12-11 22:09:19
5.12 KiB
XCoder
using System;
using System.IO;
using System.Threading.Tasks;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using NewLife;
using NewLife.XCoder.Tools.Net;
using Renci.SshNet;

using NewLife.XCoder.Services;

namespace NewLife.XCoder.ViewModels;

/// <summary>SSH 工具 ViewModel</summary>
public partial class SshViewModel : ObservableObject
{
    #region 属性
    private SshClient? _client;

    /// <summary>远程地址</summary>
    [ObservableProperty]
    private String _remoteAddress = "";

    /// <summary>用户名</summary>
    [ObservableProperty]
    private String _userName = "root";

    /// <summary>密码</summary>
    [ObservableProperty]
    private String _password = "";

    /// <summary>端口</summary>
    [ObservableProperty]
    private Int32 _port = 22;

    /// <summary>私钥文件路径(填了就优先用密钥登录,密码可为空)</summary>
    [ObservableProperty]
    private String _privateKeyPath = "";

    /// <summary>是否已连接</summary>
    [ObservableProperty]
    private Boolean _isConnected;

    /// <summary>连接按钮文本</summary>
    [ObservableProperty]
    private String _connectButtonText = LocalizationService.T("打开");

    /// <summary>发送命令文本</summary>
    [ObservableProperty]
    private String _sendText = "";

    /// <summary>接收日志</summary>
    [ObservableProperty]
    private String _receiveLog = "";
    #endregion

    #region 连接/断开
    /// <summary>切换连接状态</summary>
    [RelayCommand]
    private void ToggleConnect()
    {
        if (IsConnected)
            Disconnect();
        else
            Connect();
    }

    private void Connect()
    {
        _client?.Dispose();
        _client = null;

        var remote = RemoteAddress;
        if (remote.IsNullOrEmpty())
        {
            AppendLog("请输入地址,如 192.168.1.10:22 或 user@host");
            return;
        }

        ServerEndpoint endpoint;
        try
        {
            endpoint = EndpointParser.Parse(remote, Port, "ssh");
        }
        catch (ArgumentException ex)
        {
            AppendLog($"地址无效:{ex.Message}");
            return;
        }

        // 地址里带了 user@ 时优先使用它
        var user = endpoint.User.IsNullOrEmpty() ? UserName : endpoint.User;

        try
        {
            var connection = BuildConnectionInfo(endpoint.Host, endpoint.Port, user);
            var client = new SshClient(connection);
            client.ErrorOccurred += (_, e) => AppendLog($"错误: {e.Exception.Message}");
            client.Connect();

            _client = client;
            IsConnected = true;
            ConnectButtonText = LocalizationService.T("关闭");
            AppendLog($"已连接到 {user}@{endpoint.Host}:{endpoint.Port}");
        }
        catch (Exception ex)
        {
            AppendLog($"连接失败: {ex.Message}");
        }
    }

    /// <summary>按密码或私钥构造连接信息</summary>
    private ConnectionInfo BuildConnectionInfo(String host, Int32 port, String user)
    {
        var keyPath = PrivateKeyPath?.Trim();
        if (!keyPath.IsNullOrEmpty())
        {
            if (!File.Exists(keyPath))
                throw new FileNotFoundException($"私钥文件不存在:{keyPath}");

            var key = new PrivateKeyFile(keyPath!);
            var methods = new List<AuthenticationMethod> { new PrivateKeyAuthenticationMethod(user, key) };

            // 同时带上密码,兼容“密钥+口令短语”或密钥失败回退密码的情况
            if (!Password.IsNullOrEmpty()) methods.Add(new PasswordAuthenticationMethod(user, Password));

            return new ConnectionInfo(host, port, user, [.. methods]);
        }

        return new ConnectionInfo(host, port, user, new PasswordAuthenticationMethod(user, Password ?? ""));
    }

    private void Disconnect()
    {
        if (_client != null)
        {
            _client.Dispose();
            _client = null;
        }

        IsConnected = false;
        ConnectButtonText = LocalizationService.T("打开");
        AppendLog("已断开连接");
    }

    /// <summary>发送命令</summary>
    [RelayCommand]
    private void Send()
    {
        var str = SendText;
        if (str.IsNullOrEmpty()) return;

        if (_client == null || !_client.IsConnected)
        {
            AppendLog("未连接到服务器");
            return;
        }

        try
        {
            AppendLog($"> {str}");
            var rs = _client.RunCommand(str);
            if (rs != null)
            {
                if (!rs.Result.IsNullOrEmpty()) AppendLog(rs.Result);
                if (!rs.Error.IsNullOrEmpty()) AppendLog($"错误: {rs.Error}");
            }
        }
        catch (Exception ex)
        {
            AppendLog($"命令执行失败: {ex.Message}");
        }
    }

    /// <summary>清空接收日志</summary>
    [RelayCommand]
    private void ClearLog()
    {
        ReceiveLog = "";
    }

    private void AppendLog(String msg)

    {

        msg = NewLife.XCoder.Services.LocalizationService.Translate(msg);
        ReceiveLog += msg + "\r\n";
    }
    #endregion
}