You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

107 lines
3.2 KiB

using EC.Util.Common;
using MQTTnet;
using MQTTnet.Client;
using MQTTnet.Protocol;
using MQTTnet.Server;
using System.Text;
namespace JiLinApp.Biz.TransmitAlarm;
public class AlarmMqttService : IAlarmService
{
#region Fields
private MqttConfig Config { get; }
private MqttServer Server { get; }
private IMqttClient Client { get; }
#endregion Fields
public AlarmMqttService(MqttConfig config)
{
MqttFactory factory = new();
MqttServerOptions options = new MqttServerOptionsBuilder()
.WithDefaultEndpoint()
.WithDefaultEndpointPort(config.Port)
.Build();
MqttServer server = factory.CreateMqttServer(options);
server.ValidatingConnectionAsync += Server_ValidatingConnectionAsync;
server.ClientConnectedAsync += Server_ClientConnectedAsync;
server.ClientDisconnectedAsync += Server_ClientDisconnectedAsync;
server.ClientAcknowledgedPublishPacketAsync += Server_ClientAcknowledgedPublishPacketAsync;
IMqttClient client = factory.CreateMqttClient();
Config = config;
Server = server;
Client = client;
}
~AlarmMqttService()
{
Close();
}
#region Base
public void Start()
{
Server.StartAsync().Wait();
MqttClientOptions mqttClientOptions = new MqttClientOptionsBuilder()
.WithTcpServer("127.0.0.1", Config.Port)
.WithClientId(Config.ClientId)
.WithCredentials(Config.UserName, Config.Password)
.Build();
Client.ConnectAsync(mqttClientOptions, CancellationToken.None);
}
public void Close()
{
Client.DisconnectAsync().Wait();
Server.StopAsync().Wait();
}
public void SendAlarmMessage(AlarmMessage msg)
{
MqttApplicationMessage mqttMsg = new MqttApplicationMessageBuilder()
.WithTopic(Config.TransmitTopic)
.WithPayload(JsonUtil.ToJson(msg))
.Build();
Client.PublishAsync(mqttMsg, CancellationToken.None).Wait();
}
#endregion Base
#region Server Event
private Task Server_ValidatingConnectionAsync(ValidatingConnectionEventArgs arg)
{
if (arg.ClientId.Length == 0) arg.ReasonCode = MqttConnectReasonCode.ClientIdentifierNotValid;
else if (arg.UserName != Config.UserName) arg.ReasonCode = MqttConnectReasonCode.BadUserNameOrPassword;
else if (arg.Password != Config.Password) arg.ReasonCode = MqttConnectReasonCode.BadUserNameOrPassword;
return Task.CompletedTask;
}
private Task Server_ClientConnectedAsync(ClientConnectedEventArgs arg)
{
return Task.CompletedTask;
}
private Task Server_ClientDisconnectedAsync(ClientDisconnectedEventArgs arg)
{
return Task.CompletedTask;
}
private Task Server_ClientAcknowledgedPublishPacketAsync(ClientAcknowledgedPublishPacketEventArgs arg)
{
string clientId = arg.ClientId;
ushort packetIdentifier = arg.PublishPacket.PacketIdentifier;
string topic = arg.PublishPacket.Topic;
string msg = Encoding.UTF8.GetString(arg.PublishPacket.Payload);
return Task.CompletedTask;
}
#endregion Server Event
}