Añadido log en BBDD

main
Gerardo 2025-07-09 01:27:22 +02:00
parent fc92e03b3a
commit cfecf1424d
12 changed files with 221 additions and 3 deletions

View File

@ -39,6 +39,7 @@ namespace Mqtt.App.Application
services.AddTransient<IGetAllUserQuery, GetAllUserQuery>(); services.AddTransient<IGetAllUserQuery, GetAllUserQuery>();
services.AddTransient<IGetUserByPassAndNameQuery, GetUserByPassAndNameQuery>(); services.AddTransient<IGetUserByPassAndNameQuery, GetUserByPassAndNameQuery>();
services.AddHostedService<MqttBackgroundService>();
#endregion #endregion

View File

@ -1,4 +1,5 @@
using System; using Mqtt.App.Application.mqtt;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
@ -10,5 +11,7 @@ namespace Mqtt.App.Application.Interfaces.External
{ {
Task<bool> publishAsync(string topic, string payload); Task<bool> publishAsync(string topic, string payload);
public bool CompruebaKey(string key); public bool CompruebaKey(string key);
Task TastOnReceive(CancellationToken stoppingToken, IMqttLissener lisenner);
} }
} }

View File

@ -1,4 +1,5 @@
using Mqtt.App.Domain.Entities.User; using Mqtt.App.Domain.Entities.Mqtt;
using Mqtt.App.Domain.Entities.User;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
@ -20,5 +21,8 @@ namespace Mqtt.App.Application.Interfaces
public Task<UserEntity> GetUserByPassAndName(string pass, string name); public Task<UserEntity> GetUserByPassAndName(string pass, string name);
public Task<bool> AddMqtt(MqttEntity e);
} }
} }

View File

@ -1,9 +1,11 @@
using AutoMapper; using AutoMapper;
using Mqtt.App.Application.mqtt.commands;
using Mqtt.App.Application.Persistencia.user.commands.CreateUser; using Mqtt.App.Application.Persistencia.user.commands.CreateUser;
using Mqtt.App.Application.Persistencia.user.commands.UpdateUser; using Mqtt.App.Application.Persistencia.user.commands.UpdateUser;
using Mqtt.App.Application.Persistencia.user.Queries.GetAllUser; using Mqtt.App.Application.Persistencia.user.Queries.GetAllUser;
using Mqtt.App.Application.Persistencia.user.Queries.GetUserById; using Mqtt.App.Application.Persistencia.user.Queries.GetUserById;
using Mqtt.App.Application.Persistencia.user.Queries.GetUserByPassAndName; using Mqtt.App.Application.Persistencia.user.Queries.GetUserByPassAndName;
using Mqtt.App.Domain.Entities.Mqtt;
using Mqtt.App.Domain.Entities.User; using Mqtt.App.Domain.Entities.User;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
@ -17,6 +19,8 @@ namespace Mqtt.App.Application.configuration
{ {
public MapperProfile() public MapperProfile()
{ {
CreateMap<MqttEntity, CreateMqttModel>().ReverseMap();
CreateMap<UserEntity, CreateUserModel>().ReverseMap(); CreateMap<UserEntity, CreateUserModel>().ReverseMap();
CreateMap<UserEntity, UpdateUserModel>().ReverseMap(); CreateMap<UserEntity, UpdateUserModel>().ReverseMap();
CreateMap<GetAllUserModel, UserEntity>().ReverseMap(); CreateMap<GetAllUserModel, UserEntity>().ReverseMap();

View File

@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Mqtt.App.Application.mqtt
{
public interface IMqttLissener
{
void onReceived(string topic, string payload);
}
}

View File

@ -0,0 +1,52 @@
using AutoMapper;
using Microsoft.Extensions.Hosting;
using Mqtt.App.Application.Interfaces;
using Mqtt.App.Application.Interfaces.External;
using Mqtt.App.Application.mqtt.commands;
using Mqtt.App.Domain.Entities.Mqtt;
using Mqtt.App.Domain.Entities.User;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace Mqtt.App.Application.mqtt
{
public class MqttBackgroundService : BackgroundService, IMqttLissener
{
private readonly IMqttService _mqttService;
private readonly IPersistenciaService _persistenciaService;
private IMapper _mapper;
public MqttBackgroundService(IPersistenciaService persistenciaService,
IMqttService mqttService,
IMapper mapper)
{
_persistenciaService = persistenciaService;
_mqttService = mqttService;
_mapper = mapper;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
_mqttService.TastOnReceive(stoppingToken, this);
}
}
public void onReceived(string topic, string payload)
{
var model = new CreateMqttModel();
model.Procesa(topic, payload);
var entity = _mapper.Map<MqttEntity>(model);
_persistenciaService.AddMqtt(entity);
}
}
}

View File

@ -0,0 +1,32 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Mqtt.App.Application.mqtt.commands
{
public class CreateMqttModel
{
public Int64 Id { get; set; }
public string Payload { get; set; }
public string Topic { get; set; }
public string KeyTopic { get; set; }
public string TypeTopic { get; set; }
public DateTime Fecha { get; set; }
public bool IsActive { get; set; }
public void Procesa(string topic, string payload)
{
Topic = topic;
Payload = payload;
string ultimaParte = Topic.Split('/').LastOrDefault();
TypeTopic = String.IsNullOrWhiteSpace(ultimaParte) ? "no" : ultimaParte;
KeyTopic = String.IsNullOrWhiteSpace(ultimaParte) ? Topic : Topic.Split("/" + ultimaParte).FirstOrDefault();
Fecha = DateTime.Now;
}
}
}

View File

@ -0,0 +1,20 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Mqtt.App.Domain.Entities.Mqtt
{
public class MqttEntity
{
public Int64 Id { get; set; }
public string Payload { get; set; }
public string Topic { get; set; }
public string KeyTopic { get; set; }
public string TypeTopic { get; set; }
public DateTime Fecha { get; set; }
public bool IsActive { get; set; }
}
}

View File

@ -11,6 +11,8 @@ using System.IdentityModel.Tokens.Jwt;
using Microsoft.AspNetCore.Hosting.Server; using Microsoft.AspNetCore.Hosting.Server;
using Mqtt.App.Application.Interfaces.External; using Mqtt.App.Application.Interfaces.External;
using Microsoft.AspNetCore.DataProtection.KeyManagement; using Microsoft.AspNetCore.DataProtection.KeyManagement;
using Microsoft.Extensions.Logging;
using Mqtt.App.Application.mqtt;
namespace Mqtt.App.External.Mqtt namespace Mqtt.App.External.Mqtt
{ {
public class MqttService: IMqttService public class MqttService: IMqttService
@ -70,6 +72,64 @@ namespace Mqtt.App.External.Mqtt
} }
return res; return res;
} }
public async Task TastOnReceive(CancellationToken stoppingToken, IMqttLissener lisenner)
{
if (_config == null || stoppingToken==null)
return;
string server = _config["ServerMqtt"];
string sttopicFilter = _config["TopicFilterMqtt"];
if (String.IsNullOrWhiteSpace(server) )
return;
bool res = true;
var mqttFactory = new MqttClientFactory();
using (var mqttClient = mqttFactory.CreateMqttClient())
{
var mqttClientOptions = new MqttClientOptionsBuilder().WithTcpServer(server).Build();
// Setup message handling before connecting so that queued messages
// are also handled properly. When there is no event handler attached all
// received messages get lost.
mqttClient.ApplicationMessageReceivedAsync += e =>
{
onReceived(e, lisenner);
return Task.CompletedTask;
};
var conect = await mqttClient.ConnectAsync(mqttClientOptions, CancellationToken.None);
if (conect.ResultCode == MqttClientConnectResultCode.Success)
{
var topicFilter = new MqttTopicFilterBuilder().WithTopic(sttopicFilter).Build();
var subscribeOptions = new MqttClientSubscribeOptionsBuilder().WithTopicFilter(topicFilter).Build();
//var susb = await mqttClient.SubscribeAsync("casa");
var susb = await mqttClient.SubscribeAsync(subscribeOptions);
}
while (!stoppingToken.IsCancellationRequested)
{
await Task.Delay(1000, stoppingToken);
}
await mqttClient.DisconnectAsync();
}
}
public void onReceived(MqttApplicationMessageReceivedEventArgs e, IMqttLissener lisenner)
{
StringBuilder sb = new StringBuilder();
SequenceReader<byte> reader = new SequenceReader<byte>(e.ApplicationMessage.Payload);
while (!reader.End)
{
sb.Append(Encoding.UTF8.GetString(reader.UnreadSpan));
reader.Advance(reader.UnreadSpan.Length);
}
string result = sb.ToString();
lisenner.onReceived(e.ApplicationMessage.Topic, result);
}
} }
} }

View File

@ -13,6 +13,7 @@
"MasterKey": "bdasbvña78678,.p``´dshnihfp", "MasterKey": "bdasbvña78678,.p``´dshnihfp",
"ServerMqtt": "192.168.2.50", "ServerMqtt": "192.168.2.50",
"TopicFormatMqtt": "casa/Api/{0}", "TopicFormatMqtt": "casa/Api/{0}",
"TopicFilterMqtt": "casa/#",
"ApiKeyMqtt": "hola" "ApiKeyMqtt": "hola"

View File

@ -6,6 +6,7 @@ using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using Mqtt.App.Domain.Entities.Mqtt;
namespace Mqtt.App.Persistencia.Configurations namespace Mqtt.App.Persistencia.Configurations
{ {
@ -21,6 +22,21 @@ namespace Mqtt.App.Persistencia.Configurations
}
public UserConfiguration(EntityTypeBuilder<MqttEntity> entityBuilder)
{
entityBuilder.ToTable("UserEntity");
entityBuilder.HasKey(x => x.Id);
entityBuilder.Property(x => x.Payload).IsRequired();
entityBuilder.Property(x => x.Topic).IsRequired();
entityBuilder.Property(x => x.Fecha).IsRequired();
entityBuilder.Property(x => x.IsActive).IsRequired();
entityBuilder.Property(x => x.KeyTopic).IsRequired();
entityBuilder.Property(x => x.TypeTopic).IsRequired();
} }
} }
} }

View File

@ -7,6 +7,7 @@ using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using Mqtt.App.Domain.Entities.Mqtt;
namespace Mqtt.App.Persistencia.Services namespace Mqtt.App.Persistencia.Services
{ {
@ -17,6 +18,8 @@ namespace Mqtt.App.Persistencia.Services
} }
public DbSet<UserEntity> User { get; set; } public DbSet<UserEntity> User { get; set; }
public DbSet<MqttEntity> Mqtt { get; set; }
#region user
public async Task<bool> AddUser(UserEntity user) public async Task<bool> AddUser(UserEntity user)
{ {
User.Add(user); User.Add(user);
@ -73,7 +76,14 @@ namespace Mqtt.App.Persistencia.Services
return enty; return enty;
} }
#endregion
#region mqtt
public async Task<bool> AddMqtt(MqttEntity e)
{
Mqtt.Add(e);
return await BoolAsync();
}
#endregion
private async Task<bool> BoolAsync() private async Task<bool> BoolAsync()
{ {
@ -88,6 +98,8 @@ namespace Mqtt.App.Persistencia.Services
{ {
//configuras entidades relaccionadas con bbdd //configuras entidades relaccionadas con bbdd
new UserConfiguration(model.Entity<UserEntity>()); new UserConfiguration(model.Entity<UserEntity>());
new UserConfiguration(model.Entity<MqttEntity>());
} }
} }
} }