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;
|
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<User> Users { get; set; }
|
||||||
|
public DbSet<Device> Devices { get; set; }
|
||||||
}
|
}
|
||||||
@@ -5,11 +5,13 @@
|
|||||||
@using Elektrifikatsiya.Services
|
@using Elektrifikatsiya.Services
|
||||||
@using Elektrifikatsiya.Services.Implementations
|
@using Elektrifikatsiya.Services.Implementations
|
||||||
@using Elektrifikatsiya.Utilities
|
@using Elektrifikatsiya.Utilities
|
||||||
|
@using FluentResults;
|
||||||
@inject IVersionProvider VersionProvider
|
@inject IVersionProvider VersionProvider
|
||||||
@inject IDeviceManagmentService DeviceManagmentService
|
@inject IDeviceManagmentService DeviceManagmentService
|
||||||
@inject IAuthenticationService AuthenticationService
|
@inject IAuthenticationService AuthenticationService
|
||||||
|
@inject IMessageService MessageService
|
||||||
|
|
||||||
<Div >
|
<Div>
|
||||||
<Row Style="height:50%; width:100%" Padding="Padding.Is3.OnDesktop.Is0">
|
<Row Style="height:50%; width:100%" Padding="Padding.Is3.OnDesktop.Is0">
|
||||||
<Row Style="height:90%; width:100%">
|
<Row Style="height:90%; width:100%">
|
||||||
<Column ColumnSize="ColumnSize.Is4.OnDesktop.Is1"></Column>
|
<Column ColumnSize="ColumnSize.Is4.OnDesktop.Is1"></Column>
|
||||||
@@ -23,7 +25,7 @@
|
|||||||
Add a plug via wifi
|
Add a plug via wifi
|
||||||
</BarBrand>
|
</BarBrand>
|
||||||
</Bar>
|
</Bar>
|
||||||
<ListView Class="w-100"
|
<ListView Class="w-100"
|
||||||
TItem="IPAddress"
|
TItem="IPAddress"
|
||||||
Data="@ipAddresses"
|
Data="@ipAddresses"
|
||||||
TextField="@((_)=>(""))"
|
TextField="@((_)=>(""))"
|
||||||
@@ -42,7 +44,7 @@
|
|||||||
</Row>
|
</Row>
|
||||||
</Column>
|
</Column>
|
||||||
<Column ColumnSize="ColumnSize.Is4.Is2.WithOffset">
|
<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>
|
<Button Position="Position.Absolute.Top.Is50.Start.Is50.Translate.Middle" Color="Color.Dark" Clicked="@(()=>RegisterDevice(context.Item))" Outline>
|
||||||
<BarIcon IconName="IconName.Add" />
|
<BarIcon IconName="IconName.Add" />
|
||||||
</Button>
|
</Button>
|
||||||
</Column>
|
</Column>
|
||||||
@@ -71,13 +73,21 @@
|
|||||||
<ListGroup Style="width:100%; border-radius: 0px 0px">
|
<ListGroup Style="width:100%; border-radius: 0px 0px">
|
||||||
<ListGroupItem Color="Color.Default">
|
<ListGroupItem Color="Color.Default">
|
||||||
<Form>
|
<Form>
|
||||||
|
<Validation @ref="ipValidation" Validator="ValidateIPv4">
|
||||||
<Field Horizontal>
|
<Field Horizontal>
|
||||||
<FieldBody ColumnSize="ColumnSize.Is12">
|
<FieldBody ColumnSize="ColumnSize.Is12">
|
||||||
<TextEdit Placeholder="Enter the Device IP here" />
|
<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>
|
<br>
|
||||||
<Button style="background-color:#1a237e; color:white" Type="ButtonType.Submit" PreventDefaultOnSubmit>CONNECT</Button>
|
<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>
|
</FieldBody>
|
||||||
</Field>
|
</Field>
|
||||||
|
</Validation>
|
||||||
</Form>
|
</Form>
|
||||||
</ListGroupItem>
|
</ListGroupItem>
|
||||||
</ListGroup>
|
</ListGroup>
|
||||||
@@ -90,13 +100,55 @@
|
|||||||
@code {
|
@code {
|
||||||
List<IPAddress> ipAddresses = new List<IPAddress>();
|
List<IPAddress> ipAddresses = new List<IPAddress>();
|
||||||
|
|
||||||
|
Validation? ipValidation;
|
||||||
|
|
||||||
|
string ipText = null!;
|
||||||
|
|
||||||
protected override void OnInitialized()
|
protected override void OnInitialized()
|
||||||
{
|
{
|
||||||
ipAddresses.AddRange(MdnsDiscovery.GetChachedDevices());
|
MdnsDiscovery.OnDeviceFound += async ipAddress =>
|
||||||
MdnsDiscovery.OnDeviceFound += address =>
|
|
||||||
{
|
{
|
||||||
ipAddresses.Add(address);
|
if (!ipAddresses.Contains(ipAddress))
|
||||||
InvokeAsync(StateHasChanged);
|
{
|
||||||
|
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 Blazorise.Material;
|
||||||
|
|
||||||
using Elektrifikatsiya.Database;
|
using Elektrifikatsiya.Database;
|
||||||
using Elektrifikatsiya.Models;
|
|
||||||
using Elektrifikatsiya.Services;
|
using Elektrifikatsiya.Services;
|
||||||
using Elektrifikatsiya.Services.Implementations;
|
using Elektrifikatsiya.Services.Implementations;
|
||||||
|
|
||||||
@@ -22,8 +21,7 @@ builder.Services.AddTransient<IDeviceManagmentService, DeviceManagmentService>()
|
|||||||
builder.Services.AddScoped<IAuthenticationService, AuthenticationService>();
|
builder.Services.AddScoped<IAuthenticationService, AuthenticationService>();
|
||||||
builder.Services.AddScoped<IAuthorizationService, AuthorizationService>();
|
builder.Services.AddScoped<IAuthorizationService, AuthorizationService>();
|
||||||
builder.Services.AddScoped<ICookieService, CookieService>();
|
builder.Services.AddScoped<ICookieService, CookieService>();
|
||||||
builder.Services.AddDbContext<UserDatabaseContext>(options => options.UseSqlite("Data Source=./UserDatabase.sqlite"));
|
builder.Services.AddDbContext<MainDatabaseContext>(options => options.UseSqlite("Data Source=./MainDatabase.sqlite"));
|
||||||
builder.Services.AddDbContext<DeviceManagmentDatabaseContext>((options) => options.UseSqlite("Data Source=./DeviceManagement.sqlite"));
|
|
||||||
builder.Services.AddBootstrapProviders();
|
builder.Services.AddBootstrapProviders();
|
||||||
builder.Services.AddHttpClient<IDeviceManagmentService, DeviceManagmentService>();
|
builder.Services.AddHttpClient<IDeviceManagmentService, DeviceManagmentService>();
|
||||||
builder.Services.AddBlazorise(options =>
|
builder.Services.AddBlazorise(options =>
|
||||||
@@ -53,10 +51,7 @@ app.MapFallbackToPage("/_Host");
|
|||||||
app.MapControllers();
|
app.MapControllers();
|
||||||
|
|
||||||
IServiceScope serviceScope = app.Services.GetRequiredService<IServiceScopeFactory>().CreateScope();
|
IServiceScope serviceScope = app.Services.GetRequiredService<IServiceScopeFactory>().CreateScope();
|
||||||
serviceScope.ServiceProvider.GetRequiredService<UserDatabaseContext>().Database.EnsureCreated();
|
serviceScope.ServiceProvider.GetRequiredService<MainDatabaseContext>().Database.EnsureCreated();
|
||||||
|
|
||||||
AsyncServiceScope scope = app.Services.CreateAsyncScope();
|
|
||||||
scope.ServiceProvider.GetRequiredService<DeviceManagmentDatabaseContext>().Database.EnsureCreated();
|
|
||||||
|
|
||||||
app.Run();
|
app.Run();
|
||||||
|
|
||||||
|
|||||||
+13
-13
@@ -12,13 +12,13 @@ namespace Elektrifikatsiya.Services.Implementations;
|
|||||||
|
|
||||||
public class AuthenticationService : IAuthenticationService
|
public class AuthenticationService : IAuthenticationService
|
||||||
{
|
{
|
||||||
private readonly UserDatabaseContext userDatabaseContext;
|
private readonly MainDatabaseContext mainDatabaseContext;
|
||||||
private readonly IHttpContextAccessor httpContextAccessor;
|
private readonly IHttpContextAccessor httpContextAccessor;
|
||||||
private readonly ICookieService cookieService;
|
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.httpContextAccessor = httpContextAccessor;
|
||||||
this.cookieService = cookieService;
|
this.cookieService = cookieService;
|
||||||
}
|
}
|
||||||
@@ -32,8 +32,8 @@ public class AuthenticationService : IAuthenticationService
|
|||||||
return getUserResult.ToResult();
|
return getUserResult.ToResult();
|
||||||
}
|
}
|
||||||
|
|
||||||
_ = userDatabaseContext.Users.Remove(getUserResult.Value);
|
_ = mainDatabaseContext.Users.Remove(getUserResult.Value);
|
||||||
return (await Result.Try(() => userDatabaseContext.SaveChangesAsync())).ToResult();
|
return (await Result.Try(() => mainDatabaseContext.SaveChangesAsync())).ToResult();
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<Result<User>> GetUserAsync()
|
public async Task<Result<User>> GetUserAsync()
|
||||||
@@ -45,7 +45,7 @@ public class AuthenticationService : IAuthenticationService
|
|||||||
return Result.Fail("Token is not valid!");
|
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))
|
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)
|
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)
|
if (user is null)
|
||||||
{
|
{
|
||||||
@@ -79,7 +79,7 @@ public class AuthenticationService : IAuthenticationService
|
|||||||
user.LastLoginDate = DateTime.UtcNow;
|
user.LastLoginDate = DateTime.UtcNow;
|
||||||
user.SessionToken = newToken;
|
user.SessionToken = newToken;
|
||||||
|
|
||||||
_ = await userDatabaseContext.SaveChangesAsync();
|
_ = await mainDatabaseContext.SaveChangesAsync();
|
||||||
|
|
||||||
await cookieService.WriteCookieAsync("token", newToken, 7);
|
await cookieService.WriteCookieAsync("token", newToken, 7);
|
||||||
|
|
||||||
@@ -97,7 +97,7 @@ public class AuthenticationService : IAuthenticationService
|
|||||||
return Result.Ok();
|
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)
|
if (user is null)
|
||||||
{
|
{
|
||||||
@@ -106,7 +106,7 @@ public class AuthenticationService : IAuthenticationService
|
|||||||
|
|
||||||
user.SessionToken = null;
|
user.SessionToken = null;
|
||||||
|
|
||||||
_ = await userDatabaseContext.SaveChangesAsync();
|
_ = await mainDatabaseContext.SaveChangesAsync();
|
||||||
|
|
||||||
return Result.Ok();
|
return Result.Ok();
|
||||||
}
|
}
|
||||||
@@ -121,14 +121,14 @@ public class AuthenticationService : IAuthenticationService
|
|||||||
}
|
}
|
||||||
|
|
||||||
User user = new User(name, BC.HashPassword(password), role);
|
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)
|
public Task<Result<bool>> UserExistsAsync(string name)
|
||||||
{
|
{
|
||||||
return Result.Try(() =>
|
return Result.Try(() =>
|
||||||
userDatabaseContext.Users.AnyAsync(u => u.Name.Equals(name, StringComparison.InvariantCultureIgnoreCase)));
|
mainDatabaseContext.Users.AnyAsync(u => u.Name.Equals(name, StringComparison.InvariantCultureIgnoreCase)));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+9
-9
@@ -81,7 +81,7 @@ public class DeviceManagmentService : IDeviceManagmentService
|
|||||||
public async Task<Result<Device>> RegisterDevice(IPAddress ip, User user, string? name = null, string room = "default")
|
public async Task<Result<Device>> RegisterDevice(IPAddress ip, User user, string? name = null, string room = "default")
|
||||||
{
|
{
|
||||||
using IServiceScope scope = serviceScopeFactory.CreateScope();
|
using IServiceScope scope = serviceScopeFactory.CreateScope();
|
||||||
DeviceManagmentDatabaseContext deviceManagmentDatabaseContext = scope.ServiceProvider.GetRequiredService<DeviceManagmentDatabaseContext>();
|
MainDatabaseContext mainDatabaseContext = scope.ServiceProvider.GetRequiredService<MainDatabaseContext>();
|
||||||
|
|
||||||
ShellyResponse? shellyResponse = null;
|
ShellyResponse? shellyResponse = null;
|
||||||
|
|
||||||
@@ -108,8 +108,8 @@ public class DeviceManagmentService : IDeviceManagmentService
|
|||||||
|
|
||||||
Device device = new Device(mac, name ?? mac, ip, user, room);
|
Device device = new Device(mac, name ?? mac, ip, user, room);
|
||||||
|
|
||||||
_ = deviceManagmentDatabaseContext.Add(device);
|
_ = mainDatabaseContext.Add(device);
|
||||||
Result saveDatabaseChangesResult = await Result.Try(Task () => deviceManagmentDatabaseContext.SaveChangesAsync());
|
Result saveDatabaseChangesResult = await Result.Try(Task () => mainDatabaseContext.SaveChangesAsync());
|
||||||
|
|
||||||
if (saveDatabaseChangesResult.IsFailed)
|
if (saveDatabaseChangesResult.IsFailed)
|
||||||
{
|
{
|
||||||
@@ -122,7 +122,7 @@ public class DeviceManagmentService : IDeviceManagmentService
|
|||||||
public async Task<Result> UnregisterDevice(string macAdress)
|
public async Task<Result> UnregisterDevice(string macAdress)
|
||||||
{
|
{
|
||||||
using IServiceScope scope = serviceScopeFactory.CreateScope();
|
using IServiceScope scope = serviceScopeFactory.CreateScope();
|
||||||
DeviceManagmentDatabaseContext deviceManagmentDatabaseContext = scope.ServiceProvider.GetRequiredService<DeviceManagmentDatabaseContext>();
|
MainDatabaseContext mainDatabaseContext = scope.ServiceProvider.GetRequiredService<MainDatabaseContext>();
|
||||||
|
|
||||||
Result<Device> getDeviceResult = GetDevice(macAdress);
|
Result<Device> getDeviceResult = GetDevice(macAdress);
|
||||||
|
|
||||||
@@ -138,15 +138,15 @@ public class DeviceManagmentService : IDeviceManagmentService
|
|||||||
return untrackDeviceResult;
|
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)
|
public async Task<Result> UpdateDevice(Device device)
|
||||||
{
|
{
|
||||||
using IServiceScope scope = serviceScopeFactory.CreateScope();
|
using IServiceScope scope = serviceScopeFactory.CreateScope();
|
||||||
DeviceManagmentDatabaseContext deviceManagmentDatabaseContext = scope.ServiceProvider.GetRequiredService<DeviceManagmentDatabaseContext>();
|
MainDatabaseContext mainDatabaseContext = scope.ServiceProvider.GetRequiredService<MainDatabaseContext>();
|
||||||
|
|
||||||
Result result = deviceStatusService.UpdateDeviceStatus(device);
|
Result result = deviceStatusService.UpdateDeviceStatus(device);
|
||||||
|
|
||||||
@@ -155,8 +155,8 @@ public class DeviceManagmentService : IDeviceManagmentService
|
|||||||
return result;
|
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.Database;
|
||||||
using Elektrifikatsiya.Models;
|
using Elektrifikatsiya.Models;
|
||||||
|
|
||||||
using FluentResults;
|
using FluentResults;
|
||||||
|
|
||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
using System.Threading.Tasks;
|
|
||||||
|
|
||||||
namespace Elektrifikatsiya.Services.Implementations;
|
namespace Elektrifikatsiya.Services.Implementations;
|
||||||
|
|
||||||
@@ -23,21 +24,21 @@ public class UpdateService : IHostedService, IDisposable
|
|||||||
public async Task StartAsync(CancellationToken cancellationToken)
|
public async Task StartAsync(CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
IServiceScope serviceScope = serviceScopeFactory.CreateScope();
|
IServiceScope serviceScope = serviceScopeFactory.CreateScope();
|
||||||
DeviceManagmentDatabaseContext deviceManagmentDatabaseContext = serviceScope.ServiceProvider.GetRequiredService<DeviceManagmentDatabaseContext>();
|
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);
|
_ = 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.");
|
logger.LogInformation("Update service started.");
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task Update()
|
private void Update()
|
||||||
{
|
{
|
||||||
Result<List<Device>> getDeviceStatusResult = deviceStatusService.GetDevices();
|
Result<List<Device>> getDeviceStatusResult = deviceStatusService.GetDevices();
|
||||||
|
|
||||||
@@ -46,7 +47,7 @@ public class UpdateService : IHostedService, IDisposable
|
|||||||
logger.LogError("Updating devices failed!");
|
logger.LogError("Updating devices failed!");
|
||||||
}
|
}
|
||||||
|
|
||||||
foreach(Device device in getDeviceStatusResult.Value)
|
foreach (Device device in getDeviceStatusResult.Value)
|
||||||
{
|
{
|
||||||
//TODO: Some update magic
|
//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;
|
using Tmds.MDns;
|
||||||
|
|
||||||
@@ -9,17 +13,56 @@ public static class MdnsDiscovery
|
|||||||
public static event Action<IPAddress> OnDeviceFound = null!;
|
public static event Action<IPAddress> OnDeviceFound = null!;
|
||||||
|
|
||||||
private static readonly ServiceBrowser serviceBrowser = new ServiceBrowser();
|
private static readonly ServiceBrowser serviceBrowser = new ServiceBrowser();
|
||||||
|
private static readonly HttpClient client = new();
|
||||||
|
private static readonly MemoryCache memoryCache = new MemoryCache(new MemoryCacheOptions());
|
||||||
|
|
||||||
static MdnsDiscovery()
|
static MdnsDiscovery()
|
||||||
{
|
{
|
||||||
serviceBrowser.StartBrowse("_http._tcp");
|
serviceBrowser.StartBrowse("_http._tcp");
|
||||||
serviceBrowser.ServiceAdded += (_, eventArgs) => OnDeviceFound?.Invoke(eventArgs.Announcement.Addresses.First());
|
serviceBrowser.ServiceAdded += async (_, eventArgs) => await AddDevice(eventArgs.Announcement);
|
||||||
serviceBrowser.ServiceChanged += (_, eventArgs) => OnDeviceFound?.Invoke(eventArgs.Announcement.Addresses.First());
|
serviceBrowser.ServiceChanged += async (_, eventArgs) => await AddDevice(eventArgs.Announcement);
|
||||||
serviceBrowser.ServiceRemoved += (_, eventArgs) => OnDeviceFound?.Invoke(eventArgs.Announcement.Addresses.First());
|
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