Skip to content

Commit

Permalink
新增 多程序启动检测
Browse files Browse the repository at this point in the history
  • Loading branch information
MakesYT committed Aug 29, 2024
1 parent 42f371b commit 036abe6
Show file tree
Hide file tree
Showing 8 changed files with 172 additions and 16 deletions.
7 changes: 7 additions & 0 deletions Core.Window/ApplicationService.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using System.IO;
using Avalonia;
using Core.SDKs.Services;
using Core.SDKs.Services.Config;
using Vanara.PInvoke;

namespace Core.Window;
Expand All @@ -14,4 +15,10 @@ public void Restart()
ShowWindowCommand.SW_NORMAL);
System.Environment.Exit(0);
}

public void Stop()
{
ConfigManger.Save();
Environment.Exit(0);
}
}
1 change: 1 addition & 0 deletions Core/Core.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="8.0.0"/>
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="8.0.1"/>
<PackageReference Include="Microsoft.Extensions.Resilience" Version="8.7.0"/>
<PackageReference Include="MQTTnet" Version="4.3.6.1152" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="SharpHook" Version="5.3.7"/>
<PackageReference Include="SharpHook.Reactive" Version="5.3.7"/>
Expand Down
6 changes: 3 additions & 3 deletions Core/SDKs/CustomScenario/CustomScenarioManger.cs
Original file line number Diff line number Diff line change
Expand Up @@ -53,12 +53,12 @@ public static void Init()
});


if (!Directory.Exists(AppDomain.CurrentDomain.BaseDirectory + "customScenarios"))
if (!Directory.Exists($"{AppDomain.CurrentDomain.BaseDirectory}customScenarios"))
{
Directory.CreateDirectory(AppDomain.CurrentDomain.BaseDirectory + "customScenarios");
Directory.CreateDirectory($"{AppDomain.CurrentDomain.BaseDirectory}customScenarios");
}

var info = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory + "customScenarios");
var info = new DirectoryInfo($"{AppDomain.CurrentDomain.BaseDirectory}customScenarios");
foreach (var fileInfo in info.GetFiles())
{
Load(fileInfo);
Expand Down
1 change: 1 addition & 0 deletions Core/SDKs/Services/IApplicationService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,5 @@
public interface IApplicationService
{
public void Restart();
public void Stop();
}
144 changes: 144 additions & 0 deletions Core/SDKs/Services/MQTT/MQTTManager.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
using System.Text;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Threading;
using AvaloniaEdit.Utils;
using log4net;
using MQTTnet;
using MQTTnet.Client;
using MQTTnet.Protocol;
using MQTTnet.Server;
using Newtonsoft.Json.Linq;

namespace Core.SDKs.Services.MQTT;

public enum MqttMsgType
{
重复启动,
下载指定插件
}
public class MqttManager
{

private static readonly ILog Log = LogManager.GetLogger(nameof(MqttManager));
public static MqttServer Server;
private static FileStream fileStream;
public static async Task Init()
{

var mqttFactory = new MqttFactory();
if (File.Exists($"{AppDomain.CurrentDomain.BaseDirectory}.port"))
{
try
{
File.Delete($"{AppDomain.CurrentDomain.BaseDirectory}.port");
}
catch (Exception e)
{
using (FileStream fs = new FileStream($"{AppDomain.CurrentDomain.BaseDirectory}.port", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
byte[] bt = new byte[fs.Length];
fs.Read(bt, 0, bt.Length);
fs.Close();
var i = int.Parse(Encoding.UTF8.GetString(bt));
var options = new MqttClientOptionsBuilder()
.WithTcpServer("localhost", i) // 指定MQTT代理服务器的地址和端口
.Build();
var mqttClient = mqttFactory.CreateMqttClient();
var mqttClientConnectResult = mqttClient.ConnectAsync(options).Result;
if (mqttClientConnectResult.ResultCode == MqttClientConnectResultCode.Success)
{
Log.Debug("MQTT连接成功");
var jObject = new JObject();
jObject.Add("type",(int)MqttMsgType.重复启动);
mqttClient.PublishAsync( new MqttApplicationMessage { Topic = "test", Payload = Encoding.UTF8.GetBytes(jObject.ToString()),QualityOfServiceLevel = MqttQualityOfServiceLevel.ExactlyOnce });
}

ServiceManager.Services.GetService<IApplicationService>().Stop();
return;
}

}

}
int nowPort = 6600;
restart:
var mqttServerOptions = mqttFactory.CreateServerOptionsBuilder()
.WithDefaultEndpoint().WithDefaultEndpointPort(nowPort).Build();
Server = mqttFactory.CreateMqttServer(mqttServerOptions);
Server.ClientConnectedAsync+= Server_ClientConnectedAsync;
Server.ClientDisconnectedAsync+= Server_ClientDisconnectedAsync;
Server.InterceptingPublishAsync += Server_InterceptingPublishAsync;


try
{
await Server.StartAsync();
}
catch (Exception e)
{
Server.ClientConnectedAsync -= Server_ClientConnectedAsync;
Server.ClientDisconnectedAsync -= Server_ClientDisconnectedAsync;
Server.InterceptingPublishAsync -= Server_InterceptingPublishAsync;
nowPort++;
Log.Debug($"MQTT启动失败,尝试启动端口{nowPort}");
goto restart;
}


fileStream = new FileStream($"{AppDomain.CurrentDomain.BaseDirectory}.port",FileMode.CreateNew);
fileStream.Write(Encoding.UTF8.GetBytes(nowPort.ToString()));
fileStream.Flush();
}

private static async Task Server_InterceptingPublishAsync(InterceptingPublishEventArgs arg)
{
var s = Encoding.UTF8.GetString(arg.ApplicationMessage.Payload);
Log.Debug( $"Publish {arg.ApplicationMessage.Topic} {s}");
try
{
var jObject = JObject.Parse(s);
var jToken = jObject["type"];
var o = jToken.ToObject<int>();
switch ((MqttMsgType)o)
{
case MqttMsgType.重复启动:
{
Dispatcher.UIThread.InvokeAsync(() =>
{
if (Application.Current!.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
{
desktop.MainWindow!.Show();
desktop.MainWindow.WindowState = WindowState.Normal;
ServiceManager.Services.GetService<IWindowTool>()
.SetForegroundWindow(desktop.MainWindow.TryGetPlatformHandle().Handle);
}
});

break;
}
case MqttMsgType.下载指定插件:
break;
default:
throw new ArgumentOutOfRangeException();
}
}
catch (Exception e)
{
Log.Error("错误",e);
}

}

private static async Task Server_ClientDisconnectedAsync(ClientDisconnectedEventArgs arg)
{
Log.Debug( $"Client {arg.ClientId} disconnected.");
}

private static async Task Server_ClientConnectedAsync(ClientConnectedEventArgs arg)
{
Log.Debug( $"Client {arg.ClientId} connected.");
}
}
5 changes: 3 additions & 2 deletions Core/ViewModel/MainWindowViewModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,11 @@

using System.Collections.ObjectModel;
using System.Windows.Input;
using AvaloniaEdit.Utils;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using CommunityToolkit.Mvvm.Messaging;
using Core.SDKs.Services;
using Core.SDKs.Services.Config;

#endregion
Expand Down Expand Up @@ -73,8 +75,7 @@ public void ActivateSettingPage()
[RelayCommand]
public void Exit()
{
ConfigManger.Save();
Environment.Exit(0);
ServiceManager.Services.GetService<IApplicationService>().Stop();
}
}

Expand Down
5 changes: 4 additions & 1 deletion KitopiaAvalonia/Windows/MainWindow.axaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
using Core.SDKs.CustomScenario;
using Core.SDKs.Services;
using Core.SDKs.Services.Config;
using Core.SDKs.Services.MQTT;
using Core.SDKs.Services.Plugin;
using Core.ViewModel;
using log4net;
Expand Down Expand Up @@ -58,12 +59,14 @@ public void OnStartup()

CheckAndDeleteLogFiles();
log.Info("启动");

MqttManager.Init();
log.Info("MQTT初始化完成");

HotKeyManager.Init();
log.Debug("注册热键管理器完成");
ConfigManger.Init();
log.Info("配置文件初始化完成");

switch (ConfigManger.Config.themeChoice)
{
case ThemeEnum.跟随系统:
Expand Down
19 changes: 9 additions & 10 deletions KitopiaTest/UnitTest1.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using MQTTnet;
using SharpHook;
using SharpHook.Native;

Expand All @@ -13,16 +14,14 @@ public void Setup()
[Test]
public void Test1()
{
var eventSimulator = new EventSimulator();
eventSimulator.SimulateKeyPress(KeyCode.VcLeftControl);

eventSimulator.SimulateKeyPress(KeyCode.VcLeftAlt);
eventSimulator.SimulateKeyPress(KeyCode.VcA);
Task.Delay(100).GetAwaiter().GetResult();

eventSimulator.SimulateKeyRelease(KeyCode.VcA);
eventSimulator.SimulateKeyRelease(KeyCode.VcLeftAlt);
eventSimulator.SimulateKeyRelease(KeyCode.VcLeftControl);
var mqttFactory = new MqttFactory();
var mqttServerOptions = mqttFactory.CreateServerOptionsBuilder()
.WithDefaultEndpoint().WithDefaultEndpointPort(6600).Build();
var Server = mqttFactory.CreateMqttServer(mqttServerOptions);


Server.StartAsync();
Console.Read();


Assert.Pass();
Expand Down

0 comments on commit 036abe6

Please sign in to comment.