借助网络配置,控制Modbus工具的日志显示,避免卡死界面
智能大石头 authored at 2021-12-11 22:09:19
3.92 KiB
XCoder
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Avalonia.Controls;
using Avalonia.Threading;
using NewLife;
using NewLife.XCoder.Services;
using NewLife.XCoder.Tools.Can;

namespace NewLife.XCoder.Tools.Can;

/// <summary>CAN 调试工具</summary>
public partial class CanToolView : UserControl
{
    private readonly List<CanChannelInfo> _channels = [];
    private ICanChannel? _channel;

    /// <summary>实例化</summary>
    public CanToolView()
    {
        InitializeComponent();

        foreach (var info in CanChannelFactory.Discover())
        {
            _channels.Add(info);
            ChannelBox.Items.Add($"{info.Name}({info.Kind})");
        }
        if (_channels.Count > 0) ChannelBox.SelectedIndex = 0;

        OpenButton.Click += (_, _) => Open();
        CloseButton.Click += (_, _) => Close();
        SendButton.Click += (_, _) => Send();
        ClearButton.Click += (_, _) => LogBox.Text = "";
        ExportButton.Click += (_, _) => _ = ExportAsync();

        DetachedFromVisualTree += (_, _) => Close();
    }

    private void Open()
    {
        if (_channel != null) return;

        var index = ChannelBox.SelectedIndex;
        if (index < 0 || index >= _channels.Count) return;

        ICanChannel channel;
        try
        {
            channel = CanChannelFactory.Create(_channels[index]);
            channel.Open(BitrateBox.Text.ToInt());
        }
        catch (Exception ex)
        {
            SetStatus("打开失败:" + ex.Message, true);
            return;
        }

        channel.Received += OnReceived;
        _channel = channel;

        OpenButton.IsEnabled = false;
        CloseButton.IsEnabled = true;
        SetStatus($"已打开:{channel.Name} @ {BitrateBox.Text} bps", false);
    }

    private void Close()
    {
        var channel = _channel;
        if (channel == null) return;

        _channel = null;
        channel.Received -= OnReceived;
        try { channel.Close(); } catch { }
        try { channel.Dispose(); } catch { }

        OpenButton.IsEnabled = true;
        CloseButton.IsEnabled = false;
        SetStatus("已关闭", false);
    }

    private void Send()
    {
        var channel = _channel;
        if (channel == null)
        {
            SetStatus("请先打开通道", true);
            return;
        }

        CanFrame frame;
        try
        {
            frame = new CanFrame(
                CanChannelFactory.ParseId(IdBox.Text),
                CanChannelFactory.ParseData(DataBox.Text),
                ExtendedBox.IsChecked == true,
                RemoteBox.IsChecked == true);
        }
        catch (Exception ex)
        {
            SetStatus("报文格式错误:" + ex.Message, true);
            return;
        }

        try
        {
            channel.Send(frame);
            Append($"TX {frame}");
            SetStatus("已发送", false);
        }
        catch (Exception ex)
        {
            SetStatus("发送失败:" + ex.Message, true);
        }
    }

    private void OnReceived(Object? sender, CanFrame frame) => Dispatcher.UIThread.Post(() => Append($"RX {frame}"));

    private void Append(String line)
    {
        var text = $"{DateTime.Now:HH:mm:ss.fff} {line}";
        LogBox.Text = LogBox.Text.IsNullOrEmpty() ? text : LogBox.Text + Environment.NewLine + text;
    }

    private async Task ExportAsync()
    {
        if (LogBox.Text.IsNullOrEmpty())
        {
            SetStatus("没有可导出的记录", true);
            return;
        }

        var name = await TextLogExporter.SaveAsync(this, "导出 CAN 收发记录", "can-log.txt", LogBox.Text);
        SetStatus(name == null ? "已取消" : "已导出:" + name, false);
    }

    private void SetStatus(String text, Boolean error)
    {
        StatusText.Text = NewLife.XCoder.Services.LocalizationService.Translate(text);
        StatusText.Classes.Set("error", error);
        StatusText.Classes.Set("ok", !error);
    }
}