Код: Выделить всё
public class BrokerService : IBrokerService
{
private readonly IConfiguration _configuration;
private readonly ILogger
_logger;
private readonly MqttServer _mqttServer;
private readonly bool _debugMqtt;
private bool _started;
private readonly IWebHostEnvironment _environment;
private readonly SemaphoreSlim _semaphore = new(1, 1);
public BrokerService(IConfiguration configuration, ILogger
logger, IWebHostEnvironment environment)
{
_logger = logger;
_environment = environment;
_configuration = configuration;
if (!int.TryParse(configuration["Communication:Port"], out int port))
port = Constants.DefaultPort;
_debugMqtt = configuration["Communication:Debug"] == "1";
var options = new MqttServerOptionsBuilder()
//Set endpoint to localhost
.WithDefaultEndpoint()
.WithDefaultEndpointPort(port);
// Create a new mqtt server
_mqttServer = new MqttFactory().CreateMqttServer(options.Build());
_mqttServer.InterceptingPublishAsync += Server_InterceptingPublishAsync;
}
public async Task StartAsync()
{
if (!_started)
{
await _mqttServer.StartAsync();
_started = true;
}
}
private async Task Server_InterceptingPublishAsync(InterceptingPublishEventArgs arg)
{
var payload = arg.ApplicationMessage?.PayloadSegment == null ? null : Encoding.UTF8.GetString(arg.ApplicationMessage?.PayloadSegment.ToArray() ?? []);
await DebugMqttToFile(arg.ClientId, arg.ApplicationMessage?.Topic, payload, arg.ApplicationMessage?.QualityOfServiceLevel, arg.ApplicationMessage?.Retain ?? false);
}
private async Task DebugMqttToFile(string clientId, string? topic, string? payload, MQTTnet.Protocol.MqttQualityOfServiceLevel? qos, bool retain)
{
if (_debugMqtt)
{
try
{
string fileName = $"mqtt_{DateTime.Today:yyyyMMdd}.log";
string path = Path.Combine(_environment.ContentRootPath, "logs");
string body = payload ?? string.Empty;
if (body == string.Empty || body.Last() != '\n')
body = string.Concat(body, "\n");
string contents = $"{DateTime.Now:dd/MM/yyyy HH:mm:ss}\t{clientId}\t{topic}\t{(payload ?? string.Empty).Length}\t{qos}\t{retain}\n{body}";
await _semaphore.WaitAsync();
await File.AppendAllTextAsync(Path.Combine(path, fileName), contents);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error al almacenar lo que llegó por MQTT.");
}
finally
{
_semaphore.Release();
}
}
}
}
Вот как я его настроил:
Но когда я нажимаю " Подключите кнопку, возникает ошибка.
Я знаю, что порт MQTT прослушивает, потому что я могу проверить его по Telnet.
Подробнее здесь: https://stackoverflow.com/questions/794 ... loped-in-c
Мобильная версия