Procházet zdrojové kódy

Refactor the feature of selecting local ip

SenGao před 3 týdny
rodič
revize
96afcc9d4a

+ 3 - 3
Test/Program.cs

@@ -42,9 +42,9 @@ internal class Program
         //TestFins test = new();
         //test.TestFinsP();
 
-        //TestClass test = new();
-        //test.RunOnce();
-        //Thread.Sleep(-1);
+        TestClass test = new();
+        test.RunOnce();
+        Thread.Sleep(-1);
 
         ConfigConverter converter = new();
         converter.Convert();

+ 0 - 3
Tools/AlarmInfoServerSim/AlarmInfoServerSim.csproj

@@ -24,9 +24,6 @@
   </ItemGroup>
 
   <ItemGroup>
-    <None Update="Settings\Base\BasicInfo.xml">
-      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
-    </None>
     <None Update="Settings\Hardwares\HTR1 - U2.json">
       <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
     </None>

+ 2 - 0
Tools/AlarmInfoServerSim/Services/IInfoSendingService.cs

@@ -7,8 +7,10 @@ namespace AlarmInfoServerSim.Services;
 public interface IInfoSendingService
 {
     void Open();
+    void Close();
     void Send(byte tag, ST_ALARM alarm);
 
+    event EventHandler<bool>? TcpServerStatusChanged;
     event EventHandler<(bool, TcpConnection)>? ConnectionChanged;
     event EventHandler<(ushort, TlvData)>? DataReceived;
 }

+ 4 - 11
Tools/AlarmInfoServerSim/Services/ILogService.cs

@@ -1,15 +1,8 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
+namespace AlarmInfoServerSim.Services;
 
-namespace AlarmInfoServerSim.Services
+public interface ILogService
 {
-    public interface ILogService
-    {
-        void Log(string message);
+    void Log(string content);
 
-        event EventHandler<string>? LogReceived;
-    }
+    event EventHandler<string>? LogReceived;
 }

+ 7 - 2
Tools/AlarmInfoServerSim/Services/ISharedConfig.cs

@@ -1,11 +1,16 @@
 using ConfigOperator;
 using RealtimeData;
+using System.Net;
 
 namespace AlarmInfoServerSim.Services;
 
 public interface ISharedConfig
 {
-    BasicInfo? BasicInfo { get; }
+    Hardwares Hardwares { get; }
 
-    Hardwares? Hardwares { get; }
+    List<IPAddress> IPAddresses { get; }
+
+    IPAddress? SelectedIPAddress { get; set; }
+
+    int? SelectedPort { get; set; }
 }

+ 30 - 17
Tools/AlarmInfoServerSim/Services/InfoSendingService.cs

@@ -1,5 +1,4 @@
 using RTCommunicatorBase;
-using System.Text;
 using TLVProtocal;
 using UniversalNetFrame451.IO;
 
@@ -12,6 +11,7 @@ public class InfoSendingService : IInfoSendingService, ITlvProvider, IDisposable
     private readonly ITlvCommunicatorServer _server;
 
     private bool _isConnected;
+    private bool _isTcpServerOpened;
     private bool disposedValue;
 
     public InfoSendingService(ILogService logService, ISharedConfig sharedConfig)
@@ -20,41 +20,53 @@ public class InfoSendingService : IInfoSendingService, ITlvProvider, IDisposable
         _sharedConfig = sharedConfig;
 
         _server = TlvFactory.GetTlvServer();
-        if (!_server.Initialize(this))
-        {
-            throw new InvalidOperationException("Failed to initialize tcp server");
-        }
-
-        Open();
     }
 
+    public event EventHandler<bool>? TcpServerStatusChanged;
     public event EventHandler<(bool, TcpConnection)>? ConnectionChanged;
-
     public event EventHandler<(ushort, TlvData)>? DataReceived;
+    
 
     public void Open()
     {
-        if(_sharedConfig.BasicInfo is null)
+        if (_sharedConfig.SelectedIPAddress is null || _sharedConfig.SelectedPort is null)
         {
-            _logService.Log("Cannot find BasicInfo file! Please make sure it is existing!");
+            _logService.Log("Failed to open Tcp server because IP or Port is not correct");
             return;
         }
 
-        if (!_server.Open(_sharedConfig.BasicInfo.RTServerAddress, _sharedConfig.BasicInfo.RTServerPort))
+        if (!_server.Initialize(this))
         {
-            _logService.Log($"Failed to start TCP server in {_sharedConfig.BasicInfo.RTServerAddress}:{_sharedConfig.BasicInfo.RTServerPort}");
+            _logService.Log("Failed to initialize Tcp server");
+            return;
         }
+
+        if (!_server.Open(_sharedConfig.SelectedIPAddress.ToString(), (ushort)_sharedConfig.SelectedPort.Value))
+        {
+            _logService.Log($"Failed to start TCP server in {_sharedConfig.SelectedIPAddress.ToString()}:{_sharedConfig.SelectedPort.Value}");
+            return;
+        }
+
+        _isTcpServerOpened = true;
+        TcpServerStatusChanged?.Invoke(null, _isTcpServerOpened);
+    }
+
+    public void Close()
+    {
+        _server.Dispose();
+        _isTcpServerOpened = false;
+        TcpServerStatusChanged?.Invoke(null, _isTcpServerOpened);
     }
 
     public void Send(byte tag, ST_ALARM alarm)
     {
-        if(!_isConnected)
+        if (!_isTcpServerOpened || !_isConnected)
         {
-            _logService.Log("Cannot send information due to disconnected status");
+            _logService.Log("Cannot send information due to deactivated Tcp server or disconnected status");
             return;
         }
 
-        if(!_server.Send(tag, alarm))
+        if (!_server.Send(tag, alarm))
         {
             _logService.Log("Cannot send information due to unknown reason");
         }
@@ -80,9 +92,9 @@ public class InfoSendingService : IInfoSendingService, ITlvProvider, IDisposable
             return;
         }
 
-        if(data.Tag==1)
+        if (data.Tag == 1)
         {
-            DataReceived?.Invoke(null,(data.Tag, data));
+            DataReceived?.Invoke(null, (data.Tag, data));
         }
     }
 
@@ -99,6 +111,7 @@ public class InfoSendingService : IInfoSendingService, ITlvProvider, IDisposable
             {
                 // TODO: dispose managed state (managed objects)
                 _server.Dispose();
+                _isTcpServerOpened = false;
             }
 
             // TODO: free unmanaged resources (unmanaged objects) and override finalizer

+ 7 - 19
Tools/AlarmInfoServerSim/Services/LogService.cs

@@ -1,24 +1,12 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
+namespace AlarmInfoServerSim.Services;
 
-namespace AlarmInfoServerSim.Services
+public class LogService : ILogService
 {
-    public class LogService : ILogService
-    {
-        public LogService() 
-        {
-
-        }
+    public event EventHandler<string>? LogReceived;
 
-        public void Log(string message)
-        {
-            string logFormat = $"[{DateTime.Now.ToString()}] Content: {message} ";
-            LogReceived?.Invoke(null, logFormat);
-        }
-
-        public event EventHandler<string>? LogReceived;
+    public void Log(string content)
+    {
+        string log = $"[{DateTime.Now.ToString()}] Content: {content} ";
+        LogReceived?.Invoke(null, log);
     }
 }

+ 30 - 13
Tools/AlarmInfoServerSim/Services/SharedConfig.cs

@@ -1,32 +1,49 @@
 using ConfigOperator;
 using RealtimeData;
 using System.IO;
+using System.Net;
+using System.Net.NetworkInformation;
 
 namespace AlarmInfoServerSim.Services;
 
 public class SharedConfig : ISharedConfig
 {
-    private BasicInfo? _basicInfo;
-    private Hardwares? _hardwares;
+    private Hardwares _hardwares;
+    private List<IPAddress> _iPAddress;
+    private IPAddress? _selectedIPAddress;
+    private int? _selectedPort;
+
     public SharedConfig()
     {
-        string basicInfoPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Settings", "Base", "BasicInfo.xml");
-        if (!BaseConfigFileLoader.Load(basicInfoPath, out _basicInfo) || _basicInfo is null)
+        string hardwaresPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Settings", "Hardwares");
+        _hardwares = new();
+        HardwareFileLoader hardwareFileLoader = new(_hardwares);
+        if (!hardwareFileLoader.Load(hardwaresPath))
         {
-            //log
+            throw new InvalidOperationException("Failed to Load correct hardware configs!");
         }
 
-        string hardwaresPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Settings", "Hardwares");
-        _hardwares = new Hardwares();
-        HardwareFileLoader hardwareFileLoader = new HardwareFileLoader(_hardwares);
-        if (!hardwareFileLoader.Load(hardwaresPath))
+        _iPAddress = new();
+        foreach (var netInterface in NetworkInterface.GetAllNetworkInterfaces())
         {
-            _hardwares = null;
-            //log
+            if (netInterface.OperationalStatus == OperationalStatus.Up)
+            {
+                foreach (var ipInfo in netInterface.GetIPProperties().UnicastAddresses)
+                {
+                    if (ipInfo.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
+                    {
+                        _iPAddress.Add(ipInfo.Address);
+                    }
+                }
+            }
         }
     }
 
-    public BasicInfo? BasicInfo => _basicInfo;
+    public Hardwares Hardwares => _hardwares;
+
+    public List<IPAddress> IPAddresses => _iPAddress;
+
+    public IPAddress? SelectedIPAddress { get => _selectedIPAddress; set => _selectedIPAddress = value; }
 
-    public Hardwares? Hardwares => _hardwares;
+    public int? SelectedPort { get => _selectedPort; set => _selectedPort = value; }
 }

+ 0 - 13
Tools/AlarmInfoServerSim/Settings/Base/BasicInfo.xml

@@ -1,13 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<BasicInfo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
-	<DBConnectionString>Database=postgres;Password=123456;Host=localhost;Username=postgres;Persist Security Info=True</DBConnectionString>
-	<ServerAddress>127.0.0.1</ServerAddress>
-	<ServerPort>55004</ServerPort>
-	<SelectedDisplay>2</SelectedDisplay>
-	<RTServerAddress>127.0.0.1</RTServerAddress>
-	<RTServerPort>50052</RTServerPort>
-	<GasPanelWindowName>FurnaceGasPanel</GasPanelWindowName>
-	<DBClearTime>2025-05-27T11:28:46.4646633+08:00</DBClearTime>
-	<DBKeepRange>180</DBKeepRange>
-	<AlarmDelaySeconds>30</AlarmDelaySeconds>
-</BasicInfo>

+ 1 - 1
Tools/AlarmInfoServerSim/ViewModels/LogBarViewModel.cs

@@ -21,7 +21,7 @@ public partial class LogBarViewModel : ObservableObject
 
     private void OnLogReceived(object? sender, string e)
     {
-        App.Current.Dispatcher.BeginInvoke(() =>
+        App.Current.Dispatcher.Invoke(() =>
         {
             if(Logs.Count>=50)
             {

+ 59 - 12
Tools/AlarmInfoServerSim/ViewModels/StatusBarViewModel.cs

@@ -1,5 +1,7 @@
 using AlarmInfoServerSim.Services;
 using CommunityToolkit.Mvvm.ComponentModel;
+using CommunityToolkit.Mvvm.Input;
+using System.Net;
 
 namespace AlarmInfoServerSim.ViewModels;
 
@@ -10,16 +12,25 @@ public partial class StatusBarViewModel : ObservableObject
     private readonly IInfoSendingService _infoSendingService;
 
     [ObservableProperty]
-    private string _localIp;
+    private List<IPAddress> _iPAddresses;
 
     [ObservableProperty]
-    private string _localPort;
+    private bool _isSelectingEnable;
 
     [ObservableProperty]
-    private string _remoteIp;
+    private IPAddress _selectedIP;
 
     [ObservableProperty]
-    private string _remotePort;
+    private int _selectedPort;
+
+    [ObservableProperty]
+    private string _buttonContent;
+
+    [ObservableProperty]
+    private IPAddress _remoteIp;
+
+    [ObservableProperty]
+    private int _remotePort;
 
     [ObservableProperty]
     private string _status;
@@ -29,15 +40,51 @@ public partial class StatusBarViewModel : ObservableObject
         _logService = logService;
         _sharedConfig = sharedConfig;
         _infoSendingService = sendInfoService;
+        _infoSendingService.TcpServerStatusChanged += OnTcpServerStatusChanged;
         _infoSendingService.ConnectionChanged += OnConnectionChanged;
 
-        _localIp = _sharedConfig.BasicInfo!.RTServerAddress!;
-        _localPort = _sharedConfig.BasicInfo!.RTServerPort!.ToString();
-        _remoteIp = "Unknown";
-        _remotePort = "Unknown";
+
+        _iPAddresses = _sharedConfig.IPAddresses;
+        _isSelectingEnable=true;
+        _selectedIP = IPAddress.None;
+        _selectedPort = -1;
+        _buttonContent = "Open";
+        _remoteIp =IPAddress.None;
+        _remotePort = -1;
         _status = "Disconnected";
+    }
 
+    [RelayCommand]
+    private void OpenOrClose()
+    {
+        if (ButtonContent == "Open")
+        {
+            if (SelectedIP == IPAddress.None || SelectedPort < 0)
+            {
+                _logService.Log($"IP or Port is not correct");
+                return;
+            }
+            _sharedConfig.SelectedIPAddress = SelectedIP;
+            _sharedConfig.SelectedPort = SelectedPort;
+            _infoSendingService.Open();
+            return;
+        }
+
+        if (ButtonContent == "Close")
+        {
+            _infoSendingService.Close();
+            return;
+        }
+    }
 
+    private void OnTcpServerStatusChanged(object? sender, bool e)
+    {
+        App.Current.Dispatcher.Invoke(() =>
+        {
+            ButtonContent = e ? "Close" : "Open";
+            IsSelectingEnable = !e;
+        });
+        
     }
 
     private void OnConnectionChanged(object? sender, (bool, UniversalNetFrame451.IO.TcpConnection) e)
@@ -47,15 +94,15 @@ public partial class StatusBarViewModel : ObservableObject
             if (e.Item1)
             {
                 Status = "Connected";
-                RemoteIp = e.Item2.RemoteEndPoint.Address.ToString();
-                RemotePort = e.Item2.RemoteEndPoint.Port.ToString();
+                RemoteIp = e.Item2.RemoteEndPoint.Address;
+                RemotePort = e.Item2.RemoteEndPoint.Port;
                 _logService.Log($"Get a connection from {RemoteIp}:{RemotePort}");
             }
             else
             {
                 Status = "Disconnected";
-                RemoteIp = "Unknown";
-                RemotePort = "Unknown";
+                RemoteIp = IPAddress.None;
+                RemotePort = -1;
                 _logService.Log($"The connection lost");
             }
         });

+ 2 - 1
Tools/AlarmInfoServerSim/ViewModels/WorkAreaViewModel.cs

@@ -116,6 +116,8 @@ public partial class WorkAreaViewModel : ObservableObject
 
     private void OnDataReceived(object? sender, (ushort, TLVProtocal.TlvData) e)
     {
+        string fileName = Encoding.UTF8.GetString(e.Item2.RawData);
+
         App.Current.Dispatcher.Invoke(() =>
         {
             if (ReceivedTlvData.Count >= 50)
@@ -123,7 +125,6 @@ public partial class WorkAreaViewModel : ObservableObject
                 ReceivedTlvData.RemoveAt(ReceivedTlvData.Count - 1);
             }
 
-            string fileName = Encoding.UTF8.GetString(e.Item2.RawData);
             ReceivedTlvData.Insert(0, e.Item2.DateTime.ToString() + $" {fileName}");
         });
     }

+ 6 - 5
Tools/AlarmInfoServerSim/Views/StatusBar.xaml

@@ -14,18 +14,19 @@
             <RowDefinition Height="25"/>
         </Grid.RowDefinitions>
         <Grid.ColumnDefinitions>
-            <ColumnDefinition Width="*"/>
-            <ColumnDefinition Width="200"/>
-            <ColumnDefinition Width="*"/>
+            <ColumnDefinition Width="195"/>
+            <ColumnDefinition Width="195"/>
+            <ColumnDefinition Width="195"/>
         </Grid.ColumnDefinitions>
         <StackPanel Grid.Row="0" Grid.Column="0" Orientation="Horizontal">
             <Label VerticalAlignment="Center" HorizontalAlignment="Center">Local IP: </Label>
-            <Label Content="{Binding LocalIp}" HorizontalAlignment="Center" VerticalAlignment="Center"></Label>
+            <ComboBox IsEnabled="{Binding IsSelectingEnable}" SelectedItem="{Binding SelectedIP}" ItemsSource="{Binding IPAddresses}" HorizontalAlignment="Center" VerticalAlignment="Center" Width="100" Margin="10,0,0,0" />
         </StackPanel>
         <StackPanel Grid.Row="0" Grid.Column="1" Orientation="Horizontal">
             <Label HorizontalAlignment="Center" VerticalAlignment="Center">Local Port:</Label>
-            <Label Content="{Binding LocalPort}" HorizontalAlignment="Center" VerticalAlignment="Center"></Label>
+            <TextBox Text="{Binding SelectedPort}" HorizontalAlignment="Center" VerticalAlignment="Center" Width="50" Margin="10,0,0,0" />
         </StackPanel>
+        <Button Grid.Row="0" Grid.Column="2" Content="{Binding ButtonContent}" Command="{Binding OpenOrCloseCommand}" HorizontalAlignment="Center" VerticalAlignment="Center" Width="50" Height="20"/>
         <StackPanel Grid.Row="1" Grid.Column="0" Orientation="Horizontal">
             <Label HorizontalAlignment="Center" VerticalAlignment="Center">Remote IP:</Label>
             <Label Content="{Binding RemoteIp}" HorizontalAlignment="Center" VerticalAlignment="Center"></Label>

+ 1 - 1
Tools/AlarmInfoServerSim/Views/WorkArea.xaml

@@ -8,7 +8,7 @@
              prism:ViewModelLocator.AutoWireViewModel="True"
              Width="600" Height="350"
              mc:Ignorable="d">
-    <Grid Background="#FFCECECE" Margin="5,0,5,0">
+    <Grid Background="#FFCECECE" Margin="5,1,5,0">
         <Grid.ColumnDefinitions>
             <ColumnDefinition Width="300" />
             <ColumnDefinition Width="*"/>