Improve device discovery service and add page

This commit is contained in:
Stone_Red
2023-03-15 10:35:34 +01:00
parent 70c9d54623
commit 40b9d9aa61
8 changed files with 334 additions and 256 deletions
@@ -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)
{
}
}
}
@@ -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,98 +5,150 @@
@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>
<Column ColumnSize="ColumnSize.Is4.OnDesktop.Is12"> <Column ColumnSize="ColumnSize.Is4.OnDesktop.Is12">
<Bar Breakpoint="Breakpoint.Desktop" <Bar Breakpoint="Breakpoint.Desktop"
Background="Background.White" Background="Background.White"
ThemeContrast="ThemeContrast.None" ThemeContrast="ThemeContrast.None"
Shadow="Shadow.Remove" Shadow="Shadow.Remove"
Border="Border.Is1.RoundedTop"> Border="Border.Is1.RoundedTop">
<BarBrand> <BarBrand>
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="@((_)=>(""))"
ValueField="@((_)=>(""))" ValueField="@((_)=>(""))"
Mode="ListGroupMode.Static"> Mode="ListGroupMode.Static">
<ItemTemplate> <ItemTemplate>
<ListGroupItem> <ListGroupItem>
<Row> <Row>
<Column ColumnSize="ColumnSize.Is6"> <Column ColumnSize="ColumnSize.Is6">
<Row> <Row>
</Row> </Row>
<Row Width="Width.Is100"> <Row Width="Width.Is100">
<Column> <Column>
<Small>IP: @context.Item</Small> <Small>IP: @context.Item</Small>
</Column> </Column>
</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>
</Row> </Row>
</ListGroupItem> </ListGroupItem>
</ItemTemplate> </ItemTemplate>
</ListView> </ListView>
</Column> </Column>
</Row> </Row>
</Row> </Row>
<Row Style="height:50%; width:100%; border-top-style:solid; border-top-color:#1a237e"> <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.Is1"></Column>
<Column ColumnSize="ColumnSize.Is4.OnDesktop.Is12"> <Column ColumnSize="ColumnSize.Is4.OnDesktop.Is12">
<Row Style="height:15%; width:100%"></Row> <Row Style="height:15%; width:100%"></Row>
<Row Style="height:10%; width:100%"> <Row Style="height:10%; width:100%">
<Bar Breakpoint="Breakpoint.Desktop" <Bar Breakpoint="Breakpoint.Desktop"
Background="Background.White" Background="Background.White"
ThemeContrast="ThemeContrast.None" ThemeContrast="ThemeContrast.None"
Shadow="Shadow.Remove" Shadow="Shadow.Remove"
Border="Border.Is1.RoundedTop" Border="Border.Is1.RoundedTop"
Style="width:100%"> Style="width:100%">
<BarBrand> <BarBrand>
Add a plug via IP Add a plug via IP
</BarBrand> </BarBrand>
</Bar> </Bar>
<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>
<Field Horizontal> <Validation @ref="ipValidation" Validator="ValidateIPv4">
<FieldBody ColumnSize="ColumnSize.Is12"> <Field Horizontal>
<TextEdit Placeholder="Enter the Device IP here" /> <FieldBody ColumnSize="ColumnSize.Is12">
<br> <TextEdit @bind-Text="ipText" Placeholder="Enter the Device IP here">
<Button style="background-color:#1a237e; color:white" Type="ButtonType.Submit" PreventDefaultOnSubmit>CONNECT</Button> <Feedback>
</FieldBody> <ValidationNone>Please enter a ip address.</ValidationNone>
</Field> <ValidationSuccess>Ip address is valid.</ValidationSuccess>
</Form> <ValidationError>Ip address is not valid!</ValidationError>
</ListGroupItem> </Feedback>
</ListGroup> </TextEdit>
</Row> <br>
<Row Style="height:75%; width:100%"></Row> <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>
</Column> </FieldBody>
</Row> </Field>
</Validation>
</Form>
</ListGroupItem>
</ListGroup>
</Row>
<Row Style="height:75%; width:100%"></Row>
</Column>
</Row>
</Div> </Div>
@code { @code {
List<IPAddress> ipAddresses = new List<IPAddress>(); List<IPAddress> ipAddresses = new List<IPAddress>();
protected override void OnInitialized() Validation? ipValidation;
{
ipAddresses.AddRange(MdnsDiscovery.GetChachedDevices()); string ipText = null!;
MdnsDiscovery.OnDeviceFound += address =>
{ protected override void OnInitialized()
ipAddresses.Add(address); {
InvokeAsync(StateHasChanged); 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 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,13 +21,12 @@ 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 =>
{ {
options.Immediate = true; options.Immediate = true;
}); });
AddBlazorise(builder.Services); AddBlazorise(builder.Services);
@@ -38,9 +36,9 @@ WebApplication app = builder.Build();
// Configure the HTTP request pipeline. // Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment()) if (!app.Environment.IsDevelopment())
{ {
_ = app.UseExceptionHandler("/Error"); _ = 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. // 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.UseHsts();
} }
app.UseHttpsRedirection(); app.UseHttpsRedirection();
@@ -53,16 +51,13 @@ 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();
void AddBlazorise(IServiceCollection services) void AddBlazorise(IServiceCollection services)
{ {
_ = services.AddBlazorise(); _ = services.AddBlazorise();
_ = services.AddMaterialProviders(); _ = services.AddMaterialProviders();
_ = services.AddMaterialIcons(); _ = services.AddMaterialIcons();
} }
@@ -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)));
} }
} }
@@ -10,153 +10,153 @@ namespace Elektrifikatsiya.Services.Implementations;
public class DeviceManagmentService : IDeviceManagmentService public class DeviceManagmentService : IDeviceManagmentService
{ {
private readonly IServiceScopeFactory serviceScopeFactory; private readonly IServiceScopeFactory serviceScopeFactory;
private readonly IDeviceStatusService deviceStatusService; private readonly IDeviceStatusService deviceStatusService;
private readonly ILogger<DeviceManagmentService> logger; private readonly ILogger<DeviceManagmentService> logger;
private readonly HttpClient httpClient; private readonly HttpClient httpClient;
public DeviceManagmentService(IServiceScopeFactory serviceScopeFactory, IDeviceStatusService deviceStatusService, ILogger<DeviceManagmentService> logger, HttpClient httpClient) public DeviceManagmentService(IServiceScopeFactory serviceScopeFactory, IDeviceStatusService deviceStatusService, ILogger<DeviceManagmentService> logger, HttpClient httpClient)
{ {
this.serviceScopeFactory = serviceScopeFactory; this.serviceScopeFactory = serviceScopeFactory;
this.deviceStatusService = deviceStatusService; this.deviceStatusService = deviceStatusService;
this.logger = logger; this.logger = logger;
this.httpClient = httpClient; this.httpClient = httpClient;
} }
public Result<Device> GetDevice(string macAdress) public Result<Device> GetDevice(string macAdress)
{ {
Result<List<Device>> getDevicesResult = deviceStatusService.GetDevices(); Result<List<Device>> getDevicesResult = deviceStatusService.GetDevices();
if (getDevicesResult.IsFailed) if (getDevicesResult.IsFailed)
{ {
return getDevicesResult.ToResult(); 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) if (device is null)
{ {
return Result.Fail("Device does not exist!"); return Result.Fail("Device does not exist!");
} }
return device; return device;
} }
public Result<List<Device>> GetDevices() public Result<List<Device>> GetDevices()
{ {
Result<List<Device>> getDevicesResult = deviceStatusService.GetDevices(); Result<List<Device>> getDevicesResult = deviceStatusService.GetDevices();
if (getDevicesResult.IsFailed) if (getDevicesResult.IsFailed)
{ {
return getDevicesResult.ToResult(); return getDevicesResult.ToResult();
} }
return getDevicesResult.Value.ToList(); return getDevicesResult.Value.ToList();
} }
public Result<List<Device>> GetDevicesInRoom(string room) public Result<List<Device>> GetDevicesInRoom(string room)
{ {
Result<List<Device>> getDevicesResult = deviceStatusService.GetDevices(); Result<List<Device>> getDevicesResult = deviceStatusService.GetDevices();
if (getDevicesResult.IsFailed) if (getDevicesResult.IsFailed)
{ {
return getDevicesResult.ToResult(); 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) public Result<List<Device>> GetDevicesOfUser(int userId)
{ {
Result<List<Device>> getDevicesResult = deviceStatusService.GetDevices(); Result<List<Device>> getDevicesResult = deviceStatusService.GetDevices();
if (getDevicesResult.IsFailed) if (getDevicesResult.IsFailed)
{ {
return getDevicesResult.ToResult(); 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") 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;
try try
{ {
shellyResponse = await httpClient.GetFromJsonAsync<ShellyResponse>($"http://{ip}/shelly"); shellyResponse = await httpClient.GetFromJsonAsync<ShellyResponse>($"http://{ip}/shelly");
} }
catch (Exception ex) catch (Exception ex)
{ {
logger.LogError("HTTP request failed! {message}", ex.Message); logger.LogError("HTTP request failed! {message}", ex.Message);
} }
if (shellyResponse is null || shellyResponse.Type != "SHPLG-S") if (shellyResponse is null || shellyResponse.Type != "SHPLG-S")
{ {
return Result.Fail("Device is not reachable or not a \"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 _)) if (!PhysicalAddress.TryParse(mac, out _))
{ {
return Result.Fail("Invalid mac address!"); 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); _ = 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)
{ {
return saveDatabaseChangesResult; return saveDatabaseChangesResult;
} }
return deviceStatusService.TrackDevice(device); return deviceStatusService.TrackDevice(device);
} }
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);
if (getDeviceResult.IsFailed) if (getDeviceResult.IsFailed)
{ {
return getDeviceResult.ToResult(); return getDeviceResult.ToResult();
} }
Result untrackDeviceResult = deviceStatusService.UntrackDevice(macAdress); Result untrackDeviceResult = deviceStatusService.UntrackDevice(macAdress);
if (untrackDeviceResult.IsFailed) if (untrackDeviceResult.IsFailed)
{ {
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);
if (result.IsFailed) if (result.IsFailed)
{ {
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;
@@ -22,22 +23,22 @@ 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;
} }
} }