Files
simapi-net/Synapse/Synapse.cs
T

203 lines
6.9 KiB
C#
Raw Normal View History

2023-10-20 12:33:18 +08:00
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
2023-10-20 14:13:53 +08:00
using System.Text.Json;
2024-07-26 05:03:28 +08:00
using System.Threading;
using System.Threading.Tasks;
2023-10-20 12:33:18 +08:00
using Microsoft.Extensions.Logging;
2024-07-26 05:03:28 +08:00
using MQTTnet;
using MQTTnet.Client;
using MQTTnet.Formatter;
2023-10-20 12:33:18 +08:00
using SimApi.Attributes;
using SimApi.Communications;
2024-04-16 06:57:56 +08:00
using SimApi.Configurations;
2023-10-20 12:33:18 +08:00
using SimApi.Helpers;
namespace SimApi;
2024-07-26 05:03:28 +08:00
public partial class Synapse(SimApiOptions simApiOptions, ILogger<Synapse> logger, IServiceProvider sp)
2023-10-20 12:33:18 +08:00
{
2024-07-26 05:03:28 +08:00
private IServiceProvider Sp { get; } = sp;
2023-10-20 12:33:18 +08:00
2024-07-26 05:03:28 +08:00
private SimApiSynapseOptions Options { get; } = simApiOptions.SimApiSynapseOptions;
2023-10-20 12:33:18 +08:00
2024-07-26 05:03:28 +08:00
private MqttFactory MqttFactory { get; } = new();
public IMqttClient Client { get; set; }
2023-10-20 12:33:18 +08:00
private List<RegisterItem> EventRegistry { get; set; }
private List<RegisterItem> RpcRegistry { get; set; }
public void Init()
{
ProcessAttribute();
2024-07-26 05:03:28 +08:00
logger.LogDebug("Synapse初始化配置信息: {Json}", SimApiUtil.Json(Options));
2023-10-20 12:33:18 +08:00
if (string.IsNullOrEmpty(Options.AppName) || string.IsNullOrEmpty(Options.SysName))
{
2024-07-26 05:03:28 +08:00
logger.LogCritical("Synapse初始化失败: AppName 和 SysName 不能为空");
2023-10-20 12:33:18 +08:00
}
2024-04-16 06:57:56 +08:00
2023-10-20 12:33:18 +08:00
Options.AppId ??= Guid.NewGuid().ToString();
2024-07-26 05:03:28 +08:00
logger.LogInformation("Synapse Sys Name: {SysName}\nSynapse App Name: {AppName}\nSynapse App Id: {AppId}",
Options.SysName, Options.AppName, Options.AppId);
2023-10-20 12:33:18 +08:00
CreateConnection();
//事件客户端
if (Options.DisableEventClient)
{
2024-07-26 05:03:28 +08:00
logger.LogWarning("Synapse Event Client Disabled: DisableEventClient set true");
2023-10-20 12:33:18 +08:00
}
else
{
2024-07-26 05:03:28 +08:00
logger.LogInformation("Synapse Event Client Ready");
2023-10-20 12:33:18 +08:00
}
//RPC客户端
if (Options.DisableRpcClient)
{
2024-07-26 05:03:28 +08:00
logger.LogWarning("Synapse Rpc Client Disabled: DisableEventClient set true");
2023-10-20 12:33:18 +08:00
}
else
{
RunRpcClient();
2024-07-26 05:03:28 +08:00
logger.LogInformation("Synapse Rpc Client Ready, Client Timeout: {OptionsRpcTimeout}s", Options.RpcTimeout);
2023-10-20 12:33:18 +08:00
}
2024-04-16 06:57:56 +08:00
2023-10-20 14:13:53 +08:00
if (RpcRegistry.Count > 0)
{
RunRpcServer();
}
2024-04-16 06:57:56 +08:00
2023-10-20 14:13:53 +08:00
if (EventRegistry.Count > 0)
{
RunEventServer();
}
2023-10-20 12:33:18 +08:00
}
public SimApiBaseResponse<T> Rpc<T>(string appName, string method, dynamic param)
{
2024-07-26 05:03:28 +08:00
var res = new SimApiBaseResponse(500, "Synapse Rpc Client Disabled!");
2023-10-20 12:33:18 +08:00
if (Options.DisableRpcClient)
{
2024-07-26 05:03:28 +08:00
logger.LogError("Synapse Rpc Client Disabled!");
2023-10-20 12:33:18 +08:00
}
else
{
2023-10-30 03:45:15 +08:00
var data = FireRpc(appName, method, param);
res = JsonSerializer.Deserialize<SimApiBaseResponse<T>>(data, SimApiUtil.JsonOption);
2023-10-20 12:33:18 +08:00
}
2024-04-16 06:57:56 +08:00
2023-10-20 12:33:18 +08:00
return res as SimApiBaseResponse<T>;
}
public SimApiBaseResponse<object> Rpc(string appName, string method, dynamic param)
{
return Rpc<object>(appName, method, param);
}
public void Event(string eventName, dynamic param)
{
if (Options.DisableEventClient)
{
2024-07-26 05:03:28 +08:00
logger.LogError("Synapse Event Client Disabled!");
2023-10-20 12:33:18 +08:00
}
else
{
FireEvent(eventName, param);
}
}
private void CreateConnection()
{
2024-07-26 05:03:28 +08:00
Client = MqttFactory.CreateMqttClient();
var clientOpts = new MqttClientOptionsBuilder().WithProtocolVersion(MqttProtocolVersion.V500)
.WithWebSocketServer(o => o.WithUri(Options.Websocket))
.WithCredentials(Options.Username, Options.Password)
.WithClientId($"{Options.AppName}:{Options.AppId}")
.Build();
Client!.ConnectAsync(clientOpts, CancellationToken.None).Wait();
Client.ConnectedAsync += _ =>
2023-10-20 12:33:18 +08:00
{
2024-07-26 05:03:28 +08:00
logger.LogInformation("Synapse MQTT[{AppName}:{AppId}] 连接成功...", Options.AppName, Options.AppId);
return Task.CompletedTask;
2023-10-20 12:33:18 +08:00
};
2024-07-26 05:03:28 +08:00
//重连
Client.DisconnectedAsync += async _ =>
2023-10-20 12:33:18 +08:00
{
2024-07-26 05:03:28 +08:00
logger.LogError("Synapse MQTT[{AppName}:{AppId}] 断开连接,开始重连...", Options.AppName, Options.AppId);
await Task.Delay(TimeSpan.FromSeconds(5));
try
2023-10-20 12:33:18 +08:00
{
2024-07-26 05:03:28 +08:00
logger.LogInformation("Synapse MQTT[{AppName}:{AppId}] 开始连接MQTT服务器...", Options.AppName, Options.AppId);
Client.ConnectAsync(clientOpts).Wait();
2023-10-20 12:33:18 +08:00
}
2024-07-26 05:03:28 +08:00
catch
{
logger.LogError("Synapse MQTT[{AppName}:{AppId}] 重连失败...", Options.AppName, Options.AppId);
}
};
2023-10-20 12:33:18 +08:00
}
private void ProcessAttribute()
{
2024-07-26 05:03:28 +08:00
EventRegistry = [];
RpcRegistry = [];
2023-10-20 12:33:18 +08:00
var stackTrace = new StackTrace();
2024-07-26 05:03:28 +08:00
var callingMethod = stackTrace.GetFrame(stackTrace.FrameCount - 1)?.GetMethod();
var assembly = callingMethod?.DeclaringType?.Assembly;
var types = assembly!.GetTypes(); // 获取程序集中的所有类型
2023-10-20 12:33:18 +08:00
foreach (var type in types)
{
var methods = type.GetMethods(); // 获取类型中的所有方法
foreach (var method in methods)
{
if (method.IsDefined(typeof(SynapseEventAttribute), false))
{
var attribute =
(SynapseEventAttribute)Attribute.GetCustomAttribute(method, typeof(SynapseEventAttribute));
if (attribute != null)
{
EventRegistry.Add(new RegisterItem
{
Key = attribute.Name ?? method.Name,
Class = type,
Method = method.Name
});
}
}
2024-04-16 06:57:56 +08:00
2023-10-20 12:33:18 +08:00
if (method.IsDefined(typeof(SynapseRpcAttribute), false))
{
var attribute =
(SynapseRpcAttribute)Attribute.GetCustomAttribute(method, typeof(SynapseRpcAttribute));
if (attribute != null)
{
RpcRegistry.Add(new RegisterItem
{
Key = attribute.Name ?? $"{type.Name}.{method.Name}",
Class = type,
Method = method.Name
});
}
}
}
}
2024-04-16 06:57:56 +08:00
2023-10-20 12:33:18 +08:00
var events = EventRegistry.Aggregate(string.Empty,
(current, ev) => current + $"\n |- {ev.Key} -> {ev.Method}@{ev.Class.Name}");
var rpcList = RpcRegistry.Aggregate(string.Empty,
(current, ev) => current + $"\n |- {ev.Key} -> {ev.Method}@{ev.Class.Name}");
2024-07-26 05:03:28 +08:00
if (EventRegistry.Count > 0) logger.LogInformation(">>> Synapse System 读取Event方法:{Event}", events);
if (RpcRegistry.Count > 0) logger.LogInformation(">>> Synapse System 读取RPC方法:{Rpc}", rpcList);
2023-10-20 12:33:18 +08:00
}
}
public class RegisterItem
{
2024-07-26 05:03:28 +08:00
public string Key { get; init; }
2023-10-20 12:33:18 +08:00
2024-07-26 05:03:28 +08:00
public Type Class { get; init; }
2023-10-20 12:33:18 +08:00
2024-07-26 05:03:28 +08:00
public string Method { get; init; }
2023-10-20 12:33:18 +08:00
}