mirror of
https://github.com/Stefan-5422/-T5-Elektrifikatsiya.git
synced 2026-09-04 00:45:58 +02:00
Improve device discovery service and add page
This commit is contained in:
@@ -1,14 +0,0 @@
|
||||
using Elektrifikatsiya.Models;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Elektrifikatsiya.Database
|
||||
{
|
||||
public class DeviceManagmentDatabaseContext : DbContext
|
||||
{
|
||||
public DbSet<Device> Devices { get; set; }
|
||||
|
||||
public DeviceManagmentDatabaseContext(DbContextOptions<DeviceManagmentDatabaseContext> options) : base(options)
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
+3
-2
@@ -4,11 +4,12 @@ using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Elektrifikatsiya.Database;
|
||||
|
||||
public class UserDatabaseContext : DbContext
|
||||
public class MainDatabaseContext : DbContext
|
||||
{
|
||||
public UserDatabaseContext(DbContextOptions<UserDatabaseContext> dbContextOptions) : base(dbContextOptions)
|
||||
public MainDatabaseContext(DbContextOptions<MainDatabaseContext> dbContextOptions) : base(dbContextOptions)
|
||||
{
|
||||
}
|
||||
|
||||
public DbSet<User> Users { get; set; }
|
||||
public DbSet<Device> Devices { get; set; }
|
||||
}
|
||||
@@ -5,98 +5,150 @@
|
||||
@using Elektrifikatsiya.Services
|
||||
@using Elektrifikatsiya.Services.Implementations
|
||||
@using Elektrifikatsiya.Utilities
|
||||
@using FluentResults;
|
||||
@inject IVersionProvider VersionProvider
|
||||
@inject IDeviceManagmentService DeviceManagmentService
|
||||
@inject IAuthenticationService AuthenticationService
|
||||
@inject IMessageService MessageService
|
||||
|
||||
<Div >
|
||||
<Row Style="height:50%; width:100%" Padding="Padding.Is3.OnDesktop.Is0">
|
||||
<Row Style="height:90%; width:100%">
|
||||
<Column ColumnSize="ColumnSize.Is4.OnDesktop.Is1"></Column>
|
||||
<Column ColumnSize="ColumnSize.Is4.OnDesktop.Is12">
|
||||
<Bar Breakpoint="Breakpoint.Desktop"
|
||||
Background="Background.White"
|
||||
ThemeContrast="ThemeContrast.None"
|
||||
Shadow="Shadow.Remove"
|
||||
Border="Border.Is1.RoundedTop">
|
||||
<BarBrand>
|
||||
Add a plug via wifi
|
||||
</BarBrand>
|
||||
</Bar>
|
||||
<ListView Class="w-100"
|
||||
TItem="IPAddress"
|
||||
Data="@ipAddresses"
|
||||
TextField="@((_)=>(""))"
|
||||
ValueField="@((_)=>(""))"
|
||||
Mode="ListGroupMode.Static">
|
||||
<ItemTemplate>
|
||||
<ListGroupItem>
|
||||
<Row>
|
||||
<Column ColumnSize="ColumnSize.Is6">
|
||||
<Row>
|
||||
</Row>
|
||||
<Row Width="Width.Is100">
|
||||
<Column>
|
||||
<Small>IP: @context.Item</Small>
|
||||
</Column>
|
||||
</Row>
|
||||
</Column>
|
||||
<Column ColumnSize="ColumnSize.Is4.Is2.WithOffset">
|
||||
<Button Position="Position.Absolute.Top.Is50.Start.Is50.Translate.Middle" Color="Color.Dark" Clicked="@(async () => await DeviceManagmentService.RegisterDevice(context.Item,(await AuthenticationService.GetUserAsync()).ValueOrDefault))" Outline>
|
||||
<BarIcon IconName="IconName.Add" />
|
||||
</Button>
|
||||
</Column>
|
||||
</Row>
|
||||
</ListGroupItem>
|
||||
</ItemTemplate>
|
||||
</ListView>
|
||||
</Column>
|
||||
</Row>
|
||||
</Row>
|
||||
<Row Style="height:50%; width:100%; border-top-style:solid; border-top-color:#1a237e">
|
||||
<Column ColumnSize="ColumnSize.Is4.OnDesktop.Is1"></Column>
|
||||
<Column ColumnSize="ColumnSize.Is4.OnDesktop.Is12">
|
||||
<Row Style="height:15%; width:100%"></Row>
|
||||
<Row Style="height:10%; width:100%">
|
||||
<Bar Breakpoint="Breakpoint.Desktop"
|
||||
Background="Background.White"
|
||||
ThemeContrast="ThemeContrast.None"
|
||||
Shadow="Shadow.Remove"
|
||||
Border="Border.Is1.RoundedTop"
|
||||
Style="width:100%">
|
||||
<BarBrand>
|
||||
Add a plug via IP
|
||||
</BarBrand>
|
||||
</Bar>
|
||||
<ListGroup Style="width:100%; border-radius: 0px 0px">
|
||||
<ListGroupItem Color="Color.Default">
|
||||
<Form>
|
||||
<Field Horizontal>
|
||||
<FieldBody ColumnSize="ColumnSize.Is12">
|
||||
<TextEdit Placeholder="Enter the Device IP here" />
|
||||
<br>
|
||||
<Button style="background-color:#1a237e; color:white" Type="ButtonType.Submit" PreventDefaultOnSubmit>CONNECT</Button>
|
||||
</FieldBody>
|
||||
</Field>
|
||||
</Form>
|
||||
</ListGroupItem>
|
||||
</ListGroup>
|
||||
</Row>
|
||||
<Row Style="height:75%; width:100%"></Row>
|
||||
</Column>
|
||||
</Row>
|
||||
<Div>
|
||||
<Row Style="height:50%; width:100%" Padding="Padding.Is3.OnDesktop.Is0">
|
||||
<Row Style="height:90%; width:100%">
|
||||
<Column ColumnSize="ColumnSize.Is4.OnDesktop.Is1"></Column>
|
||||
<Column ColumnSize="ColumnSize.Is4.OnDesktop.Is12">
|
||||
<Bar Breakpoint="Breakpoint.Desktop"
|
||||
Background="Background.White"
|
||||
ThemeContrast="ThemeContrast.None"
|
||||
Shadow="Shadow.Remove"
|
||||
Border="Border.Is1.RoundedTop">
|
||||
<BarBrand>
|
||||
Add a plug via wifi
|
||||
</BarBrand>
|
||||
</Bar>
|
||||
<ListView Class="w-100"
|
||||
TItem="IPAddress"
|
||||
Data="@ipAddresses"
|
||||
TextField="@((_)=>(""))"
|
||||
ValueField="@((_)=>(""))"
|
||||
Mode="ListGroupMode.Static">
|
||||
<ItemTemplate>
|
||||
<ListGroupItem>
|
||||
<Row>
|
||||
<Column ColumnSize="ColumnSize.Is6">
|
||||
<Row>
|
||||
</Row>
|
||||
<Row Width="Width.Is100">
|
||||
<Column>
|
||||
<Small>IP: @context.Item</Small>
|
||||
</Column>
|
||||
</Row>
|
||||
</Column>
|
||||
<Column ColumnSize="ColumnSize.Is4.Is2.WithOffset">
|
||||
<Button Position="Position.Absolute.Top.Is50.Start.Is50.Translate.Middle" Color="Color.Dark" Clicked="@(()=>RegisterDevice(context.Item))" Outline>
|
||||
<BarIcon IconName="IconName.Add" />
|
||||
</Button>
|
||||
</Column>
|
||||
</Row>
|
||||
</ListGroupItem>
|
||||
</ItemTemplate>
|
||||
</ListView>
|
||||
</Column>
|
||||
</Row>
|
||||
</Row>
|
||||
<Row Style="height:50%; width:100%; border-top-style:solid; border-top-color:#1a237e">
|
||||
<Column ColumnSize="ColumnSize.Is4.OnDesktop.Is1"></Column>
|
||||
<Column ColumnSize="ColumnSize.Is4.OnDesktop.Is12">
|
||||
<Row Style="height:15%; width:100%"></Row>
|
||||
<Row Style="height:10%; width:100%">
|
||||
<Bar Breakpoint="Breakpoint.Desktop"
|
||||
Background="Background.White"
|
||||
ThemeContrast="ThemeContrast.None"
|
||||
Shadow="Shadow.Remove"
|
||||
Border="Border.Is1.RoundedTop"
|
||||
Style="width:100%">
|
||||
<BarBrand>
|
||||
Add a plug via IP
|
||||
</BarBrand>
|
||||
</Bar>
|
||||
<ListGroup Style="width:100%; border-radius: 0px 0px">
|
||||
<ListGroupItem Color="Color.Default">
|
||||
<Form>
|
||||
<Validation @ref="ipValidation" Validator="ValidateIPv4">
|
||||
<Field Horizontal>
|
||||
<FieldBody ColumnSize="ColumnSize.Is12">
|
||||
<TextEdit @bind-Text="ipText" Placeholder="Enter the Device IP here">
|
||||
<Feedback>
|
||||
<ValidationNone>Please enter a ip address.</ValidationNone>
|
||||
<ValidationSuccess>Ip address is valid.</ValidationSuccess>
|
||||
<ValidationError>Ip address is not valid!</ValidationError>
|
||||
</Feedback>
|
||||
</TextEdit>
|
||||
<br>
|
||||
<Button style="background-color:#1a237e; color:white" Type="ButtonType.Submit" Disabled="ipValidation?.Status != ValidationStatus.Success" Clicked="@(async (_)=> await RegisterDevice(IPAddress.Parse(ipText!)))" PreventDefaultOnSubmit>CONNECT</Button>
|
||||
</FieldBody>
|
||||
</Field>
|
||||
</Validation>
|
||||
</Form>
|
||||
</ListGroupItem>
|
||||
</ListGroup>
|
||||
</Row>
|
||||
<Row Style="height:75%; width:100%"></Row>
|
||||
</Column>
|
||||
</Row>
|
||||
</Div>
|
||||
|
||||
@code {
|
||||
List<IPAddress> ipAddresses = new List<IPAddress>();
|
||||
List<IPAddress> ipAddresses = new List<IPAddress>();
|
||||
|
||||
protected override void OnInitialized()
|
||||
{
|
||||
ipAddresses.AddRange(MdnsDiscovery.GetChachedDevices());
|
||||
MdnsDiscovery.OnDeviceFound += address =>
|
||||
{
|
||||
ipAddresses.Add(address);
|
||||
InvokeAsync(StateHasChanged);
|
||||
};
|
||||
}
|
||||
Validation? ipValidation;
|
||||
|
||||
string ipText = null!;
|
||||
|
||||
protected override void OnInitialized()
|
||||
{
|
||||
MdnsDiscovery.OnDeviceFound += async ipAddress =>
|
||||
{
|
||||
if (!ipAddresses.Contains(ipAddress))
|
||||
{
|
||||
ipAddresses.Add(ipAddress);
|
||||
await InvokeAsync(StateHasChanged);
|
||||
}
|
||||
};
|
||||
|
||||
MdnsDiscovery.FetchChachedDevices();
|
||||
}
|
||||
|
||||
private async Task RegisterDevice(IPAddress ipAddress)
|
||||
{
|
||||
Result<Device> result = await DeviceManagmentService.RegisterDevice(ipAddress, (await AuthenticationService.GetUserAsync()).ValueOrDefault);
|
||||
|
||||
if (result.IsSuccess)
|
||||
{
|
||||
await MessageService.Success("Device added!");
|
||||
}
|
||||
else
|
||||
{
|
||||
await MessageService.Error(string.Join(',', result.Errors.Select(e => e.Message)), "Adding device failed!");
|
||||
}
|
||||
}
|
||||
|
||||
public void ValidateIPv4(ValidatorEventArgs e)
|
||||
{
|
||||
string? input = Convert.ToString(e.Value);
|
||||
|
||||
if (string.IsNullOrWhiteSpace(input))
|
||||
{
|
||||
e.Status = ValidationStatus.None;
|
||||
return;
|
||||
}
|
||||
|
||||
string[] splitValues = input.Split('.');
|
||||
if (splitValues.Length != 4)
|
||||
{
|
||||
e.Status = ValidationStatus.Error;
|
||||
return;
|
||||
}
|
||||
|
||||
e.Status = splitValues.All(r => byte.TryParse(r, out _)) ? ValidationStatus.Success : ValidationStatus.Error;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,7 +4,6 @@ using Blazorise.Icons.Material;
|
||||
using Blazorise.Material;
|
||||
|
||||
using Elektrifikatsiya.Database;
|
||||
using Elektrifikatsiya.Models;
|
||||
using Elektrifikatsiya.Services;
|
||||
using Elektrifikatsiya.Services.Implementations;
|
||||
|
||||
@@ -22,13 +21,12 @@ builder.Services.AddTransient<IDeviceManagmentService, DeviceManagmentService>()
|
||||
builder.Services.AddScoped<IAuthenticationService, AuthenticationService>();
|
||||
builder.Services.AddScoped<IAuthorizationService, AuthorizationService>();
|
||||
builder.Services.AddScoped<ICookieService, CookieService>();
|
||||
builder.Services.AddDbContext<UserDatabaseContext>(options => options.UseSqlite("Data Source=./UserDatabase.sqlite"));
|
||||
builder.Services.AddDbContext<DeviceManagmentDatabaseContext>((options) => options.UseSqlite("Data Source=./DeviceManagement.sqlite"));
|
||||
builder.Services.AddDbContext<MainDatabaseContext>(options => options.UseSqlite("Data Source=./MainDatabase.sqlite"));
|
||||
builder.Services.AddBootstrapProviders();
|
||||
builder.Services.AddHttpClient<IDeviceManagmentService, DeviceManagmentService>();
|
||||
builder.Services.AddBlazorise(options =>
|
||||
{
|
||||
options.Immediate = true;
|
||||
options.Immediate = true;
|
||||
});
|
||||
|
||||
AddBlazorise(builder.Services);
|
||||
@@ -38,9 +36,9 @@ WebApplication app = builder.Build();
|
||||
// Configure the HTTP request pipeline.
|
||||
if (!app.Environment.IsDevelopment())
|
||||
{
|
||||
_ = app.UseExceptionHandler("/Error");
|
||||
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
|
||||
_ = app.UseHsts();
|
||||
_ = app.UseExceptionHandler("/Error");
|
||||
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
|
||||
_ = app.UseHsts();
|
||||
}
|
||||
|
||||
app.UseHttpsRedirection();
|
||||
@@ -53,16 +51,13 @@ app.MapFallbackToPage("/_Host");
|
||||
app.MapControllers();
|
||||
|
||||
IServiceScope serviceScope = app.Services.GetRequiredService<IServiceScopeFactory>().CreateScope();
|
||||
serviceScope.ServiceProvider.GetRequiredService<UserDatabaseContext>().Database.EnsureCreated();
|
||||
|
||||
AsyncServiceScope scope = app.Services.CreateAsyncScope();
|
||||
scope.ServiceProvider.GetRequiredService<DeviceManagmentDatabaseContext>().Database.EnsureCreated();
|
||||
serviceScope.ServiceProvider.GetRequiredService<MainDatabaseContext>().Database.EnsureCreated();
|
||||
|
||||
app.Run();
|
||||
|
||||
void AddBlazorise(IServiceCollection services)
|
||||
{
|
||||
_ = services.AddBlazorise();
|
||||
_ = services.AddMaterialProviders();
|
||||
_ = services.AddMaterialIcons();
|
||||
_ = services.AddBlazorise();
|
||||
_ = services.AddMaterialProviders();
|
||||
_ = services.AddMaterialIcons();
|
||||
}
|
||||
+13
-13
@@ -12,13 +12,13 @@ namespace Elektrifikatsiya.Services.Implementations;
|
||||
|
||||
public class AuthenticationService : IAuthenticationService
|
||||
{
|
||||
private readonly UserDatabaseContext userDatabaseContext;
|
||||
private readonly MainDatabaseContext mainDatabaseContext;
|
||||
private readonly IHttpContextAccessor httpContextAccessor;
|
||||
private readonly ICookieService cookieService;
|
||||
|
||||
public AuthenticationService(UserDatabaseContext userDatabaseContext, IHttpContextAccessor httpContextAccessor, ICookieService cookieService)
|
||||
public AuthenticationService(MainDatabaseContext mainDatabaseContext, IHttpContextAccessor httpContextAccessor, ICookieService cookieService)
|
||||
{
|
||||
this.userDatabaseContext = userDatabaseContext;
|
||||
this.mainDatabaseContext = mainDatabaseContext;
|
||||
this.httpContextAccessor = httpContextAccessor;
|
||||
this.cookieService = cookieService;
|
||||
}
|
||||
@@ -32,8 +32,8 @@ public class AuthenticationService : IAuthenticationService
|
||||
return getUserResult.ToResult();
|
||||
}
|
||||
|
||||
_ = userDatabaseContext.Users.Remove(getUserResult.Value);
|
||||
return (await Result.Try(() => userDatabaseContext.SaveChangesAsync())).ToResult();
|
||||
_ = mainDatabaseContext.Users.Remove(getUserResult.Value);
|
||||
return (await Result.Try(() => mainDatabaseContext.SaveChangesAsync())).ToResult();
|
||||
}
|
||||
|
||||
public async Task<Result<User>> GetUserAsync()
|
||||
@@ -45,7 +45,7 @@ public class AuthenticationService : IAuthenticationService
|
||||
return Result.Fail("Token is not valid!");
|
||||
}
|
||||
|
||||
User? user = await userDatabaseContext.Users.FirstOrDefaultAsync(u => u.SessionToken == token);
|
||||
User? user = await mainDatabaseContext.Users.FirstOrDefaultAsync(u => u.SessionToken == token);
|
||||
|
||||
if (user is null || DateTime.UtcNow - user.LastLoginDate > TimeSpan.FromDays(7))
|
||||
{
|
||||
@@ -62,7 +62,7 @@ public class AuthenticationService : IAuthenticationService
|
||||
|
||||
public async Task<Result> LoginUserAsync(string name, string password)
|
||||
{
|
||||
User? user = await userDatabaseContext.Users.FirstOrDefaultAsync(u => u.Name.Equals(name, StringComparison.InvariantCultureIgnoreCase));
|
||||
User? user = await mainDatabaseContext.Users.FirstOrDefaultAsync(u => u.Name.Equals(name, StringComparison.InvariantCultureIgnoreCase));
|
||||
|
||||
if (user is null)
|
||||
{
|
||||
@@ -79,7 +79,7 @@ public class AuthenticationService : IAuthenticationService
|
||||
user.LastLoginDate = DateTime.UtcNow;
|
||||
user.SessionToken = newToken;
|
||||
|
||||
_ = await userDatabaseContext.SaveChangesAsync();
|
||||
_ = await mainDatabaseContext.SaveChangesAsync();
|
||||
|
||||
await cookieService.WriteCookieAsync("token", newToken, 7);
|
||||
|
||||
@@ -97,7 +97,7 @@ public class AuthenticationService : IAuthenticationService
|
||||
return Result.Ok();
|
||||
}
|
||||
|
||||
User? user = await userDatabaseContext.Users.FirstOrDefaultAsync(u => u.SessionToken == token);
|
||||
User? user = await mainDatabaseContext.Users.FirstOrDefaultAsync(u => u.SessionToken == token);
|
||||
|
||||
if (user is null)
|
||||
{
|
||||
@@ -106,7 +106,7 @@ public class AuthenticationService : IAuthenticationService
|
||||
|
||||
user.SessionToken = null;
|
||||
|
||||
_ = await userDatabaseContext.SaveChangesAsync();
|
||||
_ = await mainDatabaseContext.SaveChangesAsync();
|
||||
|
||||
return Result.Ok();
|
||||
}
|
||||
@@ -121,14 +121,14 @@ public class AuthenticationService : IAuthenticationService
|
||||
}
|
||||
|
||||
User user = new User(name, BC.HashPassword(password), role);
|
||||
_ = userDatabaseContext.Users.Add(user);
|
||||
_ = mainDatabaseContext.Users.Add(user);
|
||||
|
||||
return (await Result.Try(() => userDatabaseContext.SaveChangesAsync())).ToResult();
|
||||
return (await Result.Try(() => mainDatabaseContext.SaveChangesAsync())).ToResult();
|
||||
}
|
||||
|
||||
public Task<Result<bool>> UserExistsAsync(string name)
|
||||
{
|
||||
return Result.Try(() =>
|
||||
userDatabaseContext.Users.AnyAsync(u => u.Name.Equals(name, StringComparison.InvariantCultureIgnoreCase)));
|
||||
mainDatabaseContext.Users.AnyAsync(u => u.Name.Equals(name, StringComparison.InvariantCultureIgnoreCase)));
|
||||
}
|
||||
}
|
||||
+112
-112
@@ -10,153 +10,153 @@ namespace Elektrifikatsiya.Services.Implementations;
|
||||
|
||||
public class DeviceManagmentService : IDeviceManagmentService
|
||||
{
|
||||
private readonly IServiceScopeFactory serviceScopeFactory;
|
||||
private readonly IDeviceStatusService deviceStatusService;
|
||||
private readonly ILogger<DeviceManagmentService> logger;
|
||||
private readonly HttpClient httpClient;
|
||||
private readonly IServiceScopeFactory serviceScopeFactory;
|
||||
private readonly IDeviceStatusService deviceStatusService;
|
||||
private readonly ILogger<DeviceManagmentService> logger;
|
||||
private readonly HttpClient httpClient;
|
||||
|
||||
public DeviceManagmentService(IServiceScopeFactory serviceScopeFactory, IDeviceStatusService deviceStatusService, ILogger<DeviceManagmentService> logger, HttpClient httpClient)
|
||||
{
|
||||
this.serviceScopeFactory = serviceScopeFactory;
|
||||
this.deviceStatusService = deviceStatusService;
|
||||
this.logger = logger;
|
||||
this.httpClient = httpClient;
|
||||
}
|
||||
public DeviceManagmentService(IServiceScopeFactory serviceScopeFactory, IDeviceStatusService deviceStatusService, ILogger<DeviceManagmentService> logger, HttpClient httpClient)
|
||||
{
|
||||
this.serviceScopeFactory = serviceScopeFactory;
|
||||
this.deviceStatusService = deviceStatusService;
|
||||
this.logger = logger;
|
||||
this.httpClient = httpClient;
|
||||
}
|
||||
|
||||
public Result<Device> GetDevice(string macAdress)
|
||||
{
|
||||
Result<List<Device>> getDevicesResult = deviceStatusService.GetDevices();
|
||||
public Result<Device> GetDevice(string macAdress)
|
||||
{
|
||||
Result<List<Device>> getDevicesResult = deviceStatusService.GetDevices();
|
||||
|
||||
if (getDevicesResult.IsFailed)
|
||||
{
|
||||
return getDevicesResult.ToResult();
|
||||
}
|
||||
if (getDevicesResult.IsFailed)
|
||||
{
|
||||
return getDevicesResult.ToResult();
|
||||
}
|
||||
|
||||
Device? device = getDevicesResult.Value.FirstOrDefault(d => d.MacAddress == macAdress);
|
||||
Device? device = getDevicesResult.Value.FirstOrDefault(d => d.MacAddress == macAdress);
|
||||
|
||||
if (device is null)
|
||||
{
|
||||
return Result.Fail("Device does not exist!");
|
||||
}
|
||||
if (device is null)
|
||||
{
|
||||
return Result.Fail("Device does not exist!");
|
||||
}
|
||||
|
||||
return device;
|
||||
}
|
||||
return device;
|
||||
}
|
||||
|
||||
public Result<List<Device>> GetDevices()
|
||||
{
|
||||
Result<List<Device>> getDevicesResult = deviceStatusService.GetDevices();
|
||||
public Result<List<Device>> GetDevices()
|
||||
{
|
||||
Result<List<Device>> getDevicesResult = deviceStatusService.GetDevices();
|
||||
|
||||
if (getDevicesResult.IsFailed)
|
||||
{
|
||||
return getDevicesResult.ToResult();
|
||||
}
|
||||
if (getDevicesResult.IsFailed)
|
||||
{
|
||||
return getDevicesResult.ToResult();
|
||||
}
|
||||
|
||||
return getDevicesResult.Value.ToList();
|
||||
}
|
||||
return getDevicesResult.Value.ToList();
|
||||
}
|
||||
|
||||
public Result<List<Device>> GetDevicesInRoom(string room)
|
||||
{
|
||||
Result<List<Device>> getDevicesResult = deviceStatusService.GetDevices();
|
||||
public Result<List<Device>> GetDevicesInRoom(string room)
|
||||
{
|
||||
Result<List<Device>> getDevicesResult = deviceStatusService.GetDevices();
|
||||
|
||||
if (getDevicesResult.IsFailed)
|
||||
{
|
||||
return getDevicesResult.ToResult();
|
||||
}
|
||||
if (getDevicesResult.IsFailed)
|
||||
{
|
||||
return getDevicesResult.ToResult();
|
||||
}
|
||||
|
||||
return getDevicesResult.Value.Where(d => d.Room == room).ToList();
|
||||
}
|
||||
return getDevicesResult.Value.Where(d => d.Room == room).ToList();
|
||||
}
|
||||
|
||||
public Result<List<Device>> GetDevicesOfUser(int userId)
|
||||
{
|
||||
Result<List<Device>> getDevicesResult = deviceStatusService.GetDevices();
|
||||
public Result<List<Device>> GetDevicesOfUser(int userId)
|
||||
{
|
||||
Result<List<Device>> getDevicesResult = deviceStatusService.GetDevices();
|
||||
|
||||
if (getDevicesResult.IsFailed)
|
||||
{
|
||||
return getDevicesResult.ToResult();
|
||||
}
|
||||
if (getDevicesResult.IsFailed)
|
||||
{
|
||||
return getDevicesResult.ToResult();
|
||||
}
|
||||
|
||||
return getDevicesResult.Value.Where(d => d.User.Id == userId).ToList();
|
||||
}
|
||||
return getDevicesResult.Value.Where(d => d.User.Id == userId).ToList();
|
||||
}
|
||||
|
||||
public async Task<Result<Device>> RegisterDevice(IPAddress ip, User user, string? name = null, string room = "default")
|
||||
{
|
||||
using IServiceScope scope = serviceScopeFactory.CreateScope();
|
||||
DeviceManagmentDatabaseContext deviceManagmentDatabaseContext = scope.ServiceProvider.GetRequiredService<DeviceManagmentDatabaseContext>();
|
||||
public async Task<Result<Device>> RegisterDevice(IPAddress ip, User user, string? name = null, string room = "default")
|
||||
{
|
||||
using IServiceScope scope = serviceScopeFactory.CreateScope();
|
||||
MainDatabaseContext mainDatabaseContext = scope.ServiceProvider.GetRequiredService<MainDatabaseContext>();
|
||||
|
||||
ShellyResponse? shellyResponse = null;
|
||||
ShellyResponse? shellyResponse = null;
|
||||
|
||||
try
|
||||
{
|
||||
shellyResponse = await httpClient.GetFromJsonAsync<ShellyResponse>($"http://{ip}/shelly");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError("HTTP request failed! {message}", ex.Message);
|
||||
}
|
||||
try
|
||||
{
|
||||
shellyResponse = await httpClient.GetFromJsonAsync<ShellyResponse>($"http://{ip}/shelly");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError("HTTP request failed! {message}", ex.Message);
|
||||
}
|
||||
|
||||
if (shellyResponse is null || shellyResponse.Type != "SHPLG-S")
|
||||
{
|
||||
return Result.Fail("Device is not reachable or not a \"SHPLG-S\"!");
|
||||
}
|
||||
if (shellyResponse is null || shellyResponse.Type != "SHPLG-S")
|
||||
{
|
||||
return Result.Fail("Device is not reachable or not a \"SHPLG-S\"!");
|
||||
}
|
||||
|
||||
string mac = shellyResponse.Mac;
|
||||
string mac = shellyResponse.Mac;
|
||||
|
||||
if (!PhysicalAddress.TryParse(mac, out _))
|
||||
{
|
||||
return Result.Fail("Invalid mac address!");
|
||||
}
|
||||
if (!PhysicalAddress.TryParse(mac, out _))
|
||||
{
|
||||
return Result.Fail("Invalid mac address!");
|
||||
}
|
||||
|
||||
Device device = new Device(mac, name ?? mac, ip, user, room);
|
||||
Device device = new Device(mac, name ?? mac, ip, user, room);
|
||||
|
||||
_ = deviceManagmentDatabaseContext.Add(device);
|
||||
Result saveDatabaseChangesResult = await Result.Try(Task () => deviceManagmentDatabaseContext.SaveChangesAsync());
|
||||
_ = mainDatabaseContext.Add(device);
|
||||
Result saveDatabaseChangesResult = await Result.Try(Task () => mainDatabaseContext.SaveChangesAsync());
|
||||
|
||||
if (saveDatabaseChangesResult.IsFailed)
|
||||
{
|
||||
return saveDatabaseChangesResult;
|
||||
}
|
||||
if (saveDatabaseChangesResult.IsFailed)
|
||||
{
|
||||
return saveDatabaseChangesResult;
|
||||
}
|
||||
|
||||
return deviceStatusService.TrackDevice(device);
|
||||
}
|
||||
return deviceStatusService.TrackDevice(device);
|
||||
}
|
||||
|
||||
public async Task<Result> UnregisterDevice(string macAdress)
|
||||
{
|
||||
using IServiceScope scope = serviceScopeFactory.CreateScope();
|
||||
DeviceManagmentDatabaseContext deviceManagmentDatabaseContext = scope.ServiceProvider.GetRequiredService<DeviceManagmentDatabaseContext>();
|
||||
public async Task<Result> UnregisterDevice(string macAdress)
|
||||
{
|
||||
using IServiceScope scope = serviceScopeFactory.CreateScope();
|
||||
MainDatabaseContext mainDatabaseContext = scope.ServiceProvider.GetRequiredService<MainDatabaseContext>();
|
||||
|
||||
Result<Device> getDeviceResult = GetDevice(macAdress);
|
||||
Result<Device> getDeviceResult = GetDevice(macAdress);
|
||||
|
||||
if (getDeviceResult.IsFailed)
|
||||
{
|
||||
return getDeviceResult.ToResult();
|
||||
}
|
||||
if (getDeviceResult.IsFailed)
|
||||
{
|
||||
return getDeviceResult.ToResult();
|
||||
}
|
||||
|
||||
Result untrackDeviceResult = deviceStatusService.UntrackDevice(macAdress);
|
||||
Result untrackDeviceResult = deviceStatusService.UntrackDevice(macAdress);
|
||||
|
||||
if (untrackDeviceResult.IsFailed)
|
||||
{
|
||||
return untrackDeviceResult;
|
||||
}
|
||||
if (untrackDeviceResult.IsFailed)
|
||||
{
|
||||
return untrackDeviceResult;
|
||||
}
|
||||
|
||||
_ = deviceManagmentDatabaseContext.Remove(getDeviceResult.Value);
|
||||
_ = mainDatabaseContext.Remove(getDeviceResult.Value);
|
||||
|
||||
return await Result.Try(Task () => deviceManagmentDatabaseContext.SaveChangesAsync());
|
||||
}
|
||||
return await Result.Try(Task () => mainDatabaseContext.SaveChangesAsync());
|
||||
}
|
||||
|
||||
public async Task<Result> UpdateDevice(Device device)
|
||||
{
|
||||
using IServiceScope scope = serviceScopeFactory.CreateScope();
|
||||
DeviceManagmentDatabaseContext deviceManagmentDatabaseContext = scope.ServiceProvider.GetRequiredService<DeviceManagmentDatabaseContext>();
|
||||
public async Task<Result> UpdateDevice(Device device)
|
||||
{
|
||||
using IServiceScope scope = serviceScopeFactory.CreateScope();
|
||||
MainDatabaseContext mainDatabaseContext = scope.ServiceProvider.GetRequiredService<MainDatabaseContext>();
|
||||
|
||||
Result result = deviceStatusService.UpdateDeviceStatus(device);
|
||||
Result result = deviceStatusService.UpdateDeviceStatus(device);
|
||||
|
||||
if (result.IsFailed)
|
||||
{
|
||||
return result;
|
||||
}
|
||||
if (result.IsFailed)
|
||||
{
|
||||
return result;
|
||||
}
|
||||
|
||||
_ = deviceManagmentDatabaseContext.Update(device);
|
||||
_ = mainDatabaseContext.Update(device);
|
||||
|
||||
return await Result.Try(Task () => deviceManagmentDatabaseContext.SaveChangesAsync());
|
||||
}
|
||||
return await Result.Try(Task () => mainDatabaseContext.SaveChangesAsync());
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,9 @@
|
||||
using Elektrifikatsiya.Database;
|
||||
using Elektrifikatsiya.Models;
|
||||
|
||||
using FluentResults;
|
||||
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Elektrifikatsiya.Services.Implementations;
|
||||
|
||||
@@ -22,22 +23,22 @@ public class UpdateService : IHostedService, IDisposable
|
||||
|
||||
public async Task StartAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
IServiceScope serviceScope = serviceScopeFactory.CreateScope();
|
||||
DeviceManagmentDatabaseContext deviceManagmentDatabaseContext = serviceScope.ServiceProvider.GetRequiredService<DeviceManagmentDatabaseContext>();
|
||||
IServiceScope serviceScope = serviceScopeFactory.CreateScope();
|
||||
MainDatabaseContext mainDatabaseContext = serviceScope.ServiceProvider.GetRequiredService<MainDatabaseContext>();
|
||||
|
||||
logger.LogInformation("Starting update service...");
|
||||
logger.LogInformation("Starting update service...");
|
||||
|
||||
foreach (Device device in await deviceManagmentDatabaseContext.Devices.AsNoTracking().ToListAsync(cancellationToken))
|
||||
foreach (Device device in await mainDatabaseContext.Devices.AsNoTracking().ToListAsync(cancellationToken))
|
||||
{
|
||||
_ = deviceStatusService.TrackDevice(device);
|
||||
}
|
||||
|
||||
timer = new Timer(async (_) => await Update(), null, TimeSpan.Zero, TimeSpan.FromSeconds(15));
|
||||
timer = new Timer((_) => Update(), null, TimeSpan.Zero, TimeSpan.FromSeconds(15));
|
||||
|
||||
logger.LogInformation("Update service started.");
|
||||
}
|
||||
|
||||
private async Task Update()
|
||||
private void Update()
|
||||
{
|
||||
Result<List<Device>> getDeviceStatusResult = deviceStatusService.GetDevices();
|
||||
|
||||
@@ -46,7 +47,7 @@ public class UpdateService : IHostedService, IDisposable
|
||||
logger.LogError("Updating devices failed!");
|
||||
}
|
||||
|
||||
foreach(Device device in getDeviceStatusResult.Value)
|
||||
foreach (Device device in getDeviceStatusResult.Value)
|
||||
{
|
||||
//TODO: Some update magic
|
||||
}
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
using System.Net;
|
||||
using Elektrifikatsiya.Models;
|
||||
|
||||
using Microsoft.Extensions.Caching.Memory;
|
||||
|
||||
using System.Net;
|
||||
|
||||
using Tmds.MDns;
|
||||
|
||||
@@ -9,17 +13,56 @@ public static class MdnsDiscovery
|
||||
public static event Action<IPAddress> OnDeviceFound = null!;
|
||||
|
||||
private static readonly ServiceBrowser serviceBrowser = new ServiceBrowser();
|
||||
private static readonly HttpClient client = new();
|
||||
private static readonly MemoryCache memoryCache = new MemoryCache(new MemoryCacheOptions());
|
||||
|
||||
static MdnsDiscovery()
|
||||
{
|
||||
serviceBrowser.StartBrowse("_http._tcp");
|
||||
serviceBrowser.ServiceAdded += (_, eventArgs) => OnDeviceFound?.Invoke(eventArgs.Announcement.Addresses.First());
|
||||
serviceBrowser.ServiceChanged += (_, eventArgs) => OnDeviceFound?.Invoke(eventArgs.Announcement.Addresses.First());
|
||||
serviceBrowser.ServiceRemoved += (_, eventArgs) => OnDeviceFound?.Invoke(eventArgs.Announcement.Addresses.First());
|
||||
serviceBrowser.ServiceAdded += async (_, eventArgs) => await AddDevice(eventArgs.Announcement);
|
||||
serviceBrowser.ServiceChanged += async (_, eventArgs) => await AddDevice(eventArgs.Announcement);
|
||||
serviceBrowser.ServiceRemoved += async (_, eventArgs) => await AddDevice(eventArgs.Announcement);
|
||||
}
|
||||
|
||||
public static IEnumerable<IPAddress> GetChachedDevices()
|
||||
public static void FetchChachedDevices()
|
||||
{
|
||||
return serviceBrowser.Services.Select(s => s.Addresses.First());
|
||||
serviceBrowser.Services.ToList().ForEach(async d => await AddDevice(d));
|
||||
}
|
||||
|
||||
private static async Task AddDevice(ServiceAnnouncement announcement)
|
||||
{
|
||||
IPAddress ipAddress = announcement.Addresses.First();
|
||||
|
||||
if (!memoryCache.TryGetValue(ipAddress.ToString(), out bool isShellyDevice))
|
||||
{
|
||||
isShellyDevice = await IsShellyDevice(ipAddress);
|
||||
_ = memoryCache.Set(ipAddress.ToString(), isShellyDevice, TimeSpan.FromHours(1));
|
||||
}
|
||||
|
||||
if (isShellyDevice)
|
||||
{
|
||||
OnDeviceFound?.Invoke(ipAddress);
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task<bool> IsShellyDevice(IPAddress ipAddress)
|
||||
{
|
||||
ShellyResponse? shellyResponse;
|
||||
|
||||
try
|
||||
{
|
||||
shellyResponse = await client.GetFromJsonAsync<ShellyResponse>($"http://{ipAddress}/shelly");
|
||||
}
|
||||
catch (HttpRequestException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (shellyResponse is null || shellyResponse.Type != "SHPLG-S")
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user