Files
simapi-net/Synapse/EventClient.cs
T

34 lines
953 B
C#
Raw Normal View History

2023-10-20 12:33:18 +08:00
using System.Text.Json;
2024-07-26 05:03:28 +08:00
using System.Threading;
2023-10-20 12:33:18 +08:00
using Microsoft.Extensions.Logging;
2024-07-26 05:03:28 +08:00
using MQTTnet;
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
{
2024-07-26 08:11:21 +08:00
private bool FireEvent(string eventName, object? param)
2023-10-20 12:33:18 +08:00
{
2024-07-26 08:11:21 +08:00
string paramJson;
if (param is string strParam)
{
paramJson = strParam;
}
else
{
paramJson = SimApiUtil.Json(param);
2024-07-26 08:11:21 +08:00
}
2024-07-26 08:11:21 +08:00
var topic = $"{Options.SysName}/event/{Options.AppName}/{eventName}";
2024-07-26 05:03:28 +08:00
var message = new MqttApplicationMessageBuilder()
.WithTopic(topic)
.WithPayload(paramJson)
2024-07-26 08:11:21 +08:00
.WithRetainFlag(false)
2024-07-26 05:03:28 +08:00
.Build();
if (!Client!.IsConnected) return false;
2024-07-26 08:11:21 +08:00
Client.PublishAsync(message, CancellationToken.None).Wait();
logger.LogDebug("Synapse Event Publish: {Event}@{App} {Json}", eventName, Options.AppName, paramJson);
2024-07-26 05:03:28 +08:00
return true;
2023-10-20 12:33:18 +08:00
}
}