Files
simapi-net/Synapse/EventServer.cs
T

49 lines
1.9 KiB
C#
Raw Normal View History

2023-10-20 12:33:18 +08:00
using System;
using System.Linq;
using System.Text.Json;
2024-07-26 05:03:28 +08:00
using System.Threading.Tasks;
2023-10-20 12:33:18 +08:00
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
2024-07-26 05:03:28 +08:00
using MQTTnet;
using MQTTnet.Protocol;
2023-10-23 17:39:27 +08:00
using SimApi.Helpers;
2023-10-20 12:33:18 +08:00
namespace SimApi;
public partial class Synapse
{
private void RunEventServer()
{
2024-07-26 05:03:28 +08:00
var esTopicPrefix = $"{Options.SysName}/{Options.AppName}/event/";
var eventSubOpts = MqttFactory.CreateSubscribeOptionsBuilder()
.WithTopicFilter(o =>
o.WithTopic($"$queue/{esTopicPrefix}+").WithRetainHandling(MqttRetainHandling.SendAtSubscribe))
.Build();
Client.ApplicationMessageReceivedAsync += e =>
2023-10-20 12:33:18 +08:00
{
2024-07-26 05:03:28 +08:00
if (!e.ApplicationMessage.Topic.StartsWith(esTopicPrefix)) return Task.CompletedTask;
var reqBody = e.ApplicationMessage.ConvertPayloadToString();
var eventName = e.ApplicationMessage.Topic.Replace(esTopicPrefix, string.Empty);
logger.LogDebug("Synapse Event Receive: {AppName}.{EventName}\n{Body}",
Options.AppName, eventName, reqBody);
2023-10-20 12:33:18 +08:00
2024-07-26 05:03:28 +08:00
var method = EventRegistry.FirstOrDefault(x => x.Key == eventName);
if (method == null) return Task.CompletedTask;
var callClass = Sp.CreateScope().ServiceProvider.GetRequiredService(method!.Class);
2023-10-20 14:13:53 +08:00
var mt = callClass.GetType().GetMethod(method.Method);
2024-07-26 05:03:28 +08:00
var pt = mt!.GetParameters()[0].ParameterType;
2023-10-20 14:13:53 +08:00
try
2023-10-20 12:33:18 +08:00
{
2023-10-20 14:13:53 +08:00
mt.Invoke(callClass, pt == typeof(string)
? new object[] { reqBody }
2023-10-23 17:39:27 +08:00
: new[] { JsonSerializer.Deserialize(reqBody, pt, SimApiUtil.JsonOption) });
2023-10-20 14:13:53 +08:00
}
2024-07-26 05:03:28 +08:00
catch (Exception ex)
2023-10-20 14:13:53 +08:00
{
2024-07-26 05:03:28 +08:00
logger.LogError("SynapseEvent Processor Error: {Err}", ex.InnerException);
2023-10-20 12:33:18 +08:00
}
2024-07-26 05:03:28 +08:00
return Task.CompletedTask;
2023-10-20 12:33:18 +08:00
};
2024-07-26 05:03:28 +08:00
Client.SubscribeAsync(eventSubOpts).Wait();
2023-10-20 12:33:18 +08:00
}
}