mirror of
https://github.com/Stefan-5422/-T5-Elektrifikatsiya.git
synced 2026-09-10 07:36:02 +02:00
Merge branch 'Development' of https://github.com/Stefan-5422/-T5-Elektrifikatsiya into Development
This commit is contained in:
@@ -1 +0,0 @@
|
|||||||
|
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
<Bar Breakpoint="Breakpoint.Desktop" NavigationBreakpoint="Breakpoint.Tablet" ThemeContrast="ThemeContrast.Dark"
|
@using Elektrifikatsiya.Models;
|
||||||
|
<Bar Breakpoint="Breakpoint.Desktop" NavigationBreakpoint="Breakpoint.Tablet" ThemeContrast="ThemeContrast.Dark"
|
||||||
Mode="BarMode.VerticalInline" CollapseMode="BarCollapseMode.Small">
|
Mode="BarMode.VerticalInline" CollapseMode="BarCollapseMode.Small">
|
||||||
<BarToggler TextColor="TextColor.Primary" />
|
<BarToggler TextColor="TextColor.Primary" />
|
||||||
<BarBrand>
|
<BarBrand>
|
||||||
@@ -15,14 +16,18 @@
|
|||||||
<BarLink To="/" TextColor="TextColor.White">
|
<BarLink To="/" TextColor="TextColor.White">
|
||||||
<BarIcon Style="color:white" IconName="IconName.Dashboard" />
|
<BarIcon Style="color:white" IconName="IconName.Dashboard" />
|
||||||
Dashboard
|
Dashboard
|
||||||
</BarLink>
|
|
||||||
</BarItem>
|
|
||||||
<BarItem>
|
|
||||||
<BarLink To="/admin" TextColor="TextColor.White">
|
|
||||||
<BarIcon Style="color:white" IconName="IconName.ShieldAlt" />
|
|
||||||
Admin
|
|
||||||
</BarLink>
|
</BarLink>
|
||||||
</BarItem>
|
</BarItem>
|
||||||
|
<Protected RequiredRole="Role.Admin">
|
||||||
|
<Authorized>
|
||||||
|
<BarItem>
|
||||||
|
<BarLink To="/admin" TextColor="TextColor.White">
|
||||||
|
<BarIcon Style="color:white" IconName="IconName.ShieldAlt" />
|
||||||
|
Admin
|
||||||
|
</BarLink>
|
||||||
|
</BarItem>
|
||||||
|
</Authorized>
|
||||||
|
</Protected>
|
||||||
<BarItem>
|
<BarItem>
|
||||||
<BarLink To="/settings" TextColor="TextColor.White">
|
<BarLink To="/settings" TextColor="TextColor.White">
|
||||||
<BarIcon Style="color:white" IconName="IconName.Wrench" />
|
<BarIcon Style="color:white" IconName="IconName.Wrench" />
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
@page "/Admin"
|
@page "/Admin"
|
||||||
@using Blazorise.Components;
|
@using Blazorise.Components;
|
||||||
|
@using Elektrifikatsiya.Components
|
||||||
@using Elektrifikatsiya.Models;
|
@using Elektrifikatsiya.Models;
|
||||||
@using Elektrifikatsiya.Database;
|
@using Elektrifikatsiya.Database;
|
||||||
@using System.Net
|
@using System.Net
|
||||||
|
|||||||
@@ -12,6 +12,7 @@
|
|||||||
@inject IDeviceStatusService DeviceStatusService;
|
@inject IDeviceStatusService DeviceStatusService;
|
||||||
@inject IDeviceManagmentService DeviceManagmentService;
|
@inject IDeviceManagmentService DeviceManagmentService;
|
||||||
@inject IEventService EventService;
|
@inject IEventService EventService;
|
||||||
|
@inject IAuthenticationService AuthenticationService;
|
||||||
@inject IEnergyPriceService EnergyPriceService;
|
@inject IEnergyPriceService EnergyPriceService;
|
||||||
@inject MainDatabaseContext MainDatabaseContext;
|
@inject MainDatabaseContext MainDatabaseContext;
|
||||||
|
|
||||||
|
|||||||
@@ -8,94 +8,94 @@ namespace Elektrifikatsiya.Pages;
|
|||||||
|
|
||||||
public partial class Dashboard
|
public partial class Dashboard
|
||||||
{
|
{
|
||||||
private readonly List<string> labels = new List<string>();
|
private readonly List<string> labels = new List<string>();
|
||||||
|
|
||||||
//TODO: insert new event here if plug produces one
|
//TODO: insert new event here if plug produces one
|
||||||
private List<Event> events = new List<Event>() { new Event("Text", "Text", DateTime.Today, null) };
|
private List<Event> events = new List<Event>() { new Event("Text", "Text", DateTime.Today, null) };
|
||||||
|
|
||||||
//code for graph
|
//code for graph
|
||||||
private LineChart<double> lineChart;
|
private LineChart<double> lineChart;
|
||||||
|
|
||||||
//TODO: insert new Device here if user adds one
|
//TODO: insert new Device here if user adds one
|
||||||
private List<Device> plugs = new List<Device>();
|
private List<Device> plugs = new List<Device>();
|
||||||
|
|
||||||
protected override async Task OnAfterRenderAsync(bool firstRender)
|
protected override async Task OnAfterRenderAsync(bool firstRender)
|
||||||
{
|
{
|
||||||
if (firstRender)
|
if (firstRender)
|
||||||
{
|
{
|
||||||
await HandleRedraw();
|
await HandleRedraw();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
protected override void OnInitialized()
|
protected override async Task OnInitializedAsync()
|
||||||
{
|
{
|
||||||
plugs = DeviceStatusService.GetDevices().ValueOrDefault ?? new List<Device>();
|
plugs = DeviceManagmentService.GetDevices((await AuthenticationService.GetUserAsync()).ValueOrDefault).ValueOrDefault ?? new List<Device>();
|
||||||
events = EventService.Events;
|
events = EventService.Events;
|
||||||
|
|
||||||
EventService.OnEventCalled += (__, e) =>
|
EventService.OnEventCalled += (__, e) =>
|
||||||
{
|
{
|
||||||
_ = InvokeAsync(StateHasChanged);
|
_ = InvokeAsync(StateHasChanged);
|
||||||
};
|
};
|
||||||
DeviceStatusService.OnDeviceStatusChanged += (__, e) =>
|
DeviceStatusService.OnDeviceStatusChanged += (__, e) =>
|
||||||
{
|
{
|
||||||
_ = InvokeAsync(StateHasChanged);
|
_ = InvokeAsync(StateHasChanged);
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task<List<double>> GetData()
|
private async Task<List<double>> GetData()
|
||||||
{
|
{
|
||||||
if (plugs.Count == 0)
|
if (plugs.Count == 0)
|
||||||
{
|
{
|
||||||
return new();
|
return new();
|
||||||
}
|
}
|
||||||
PrometheusQuery promQueryer = new PrometheusQuery("http://localhost:9090");
|
PrometheusQuery promQueryer = new PrometheusQuery("http://localhost:9090");
|
||||||
|
|
||||||
string plugnames = "";
|
string plugnames = "";
|
||||||
foreach (Device device in plugs)
|
foreach (Device device in plugs)
|
||||||
{
|
{
|
||||||
plugnames += $"shellyplug-s-{device.MacAddress}/relay/0|";
|
plugnames += $"shellyplug-s-{device.MacAddress}/relay/0|";
|
||||||
}
|
}
|
||||||
plugnames = plugnames[0..^1];
|
plugnames = plugnames[0..^1];
|
||||||
|
|
||||||
double energyPrice = MainDatabaseContext.EnergyPriceChanges.OrderByDescending(e => e.DateTime).FirstOrDefault()?.EnergyPrice ?? 0;
|
double energyPrice = MainDatabaseContext.EnergyPriceChanges.OrderByDescending(e => e.DateTime).FirstOrDefault()?.EnergyPrice ?? 0;
|
||||||
|
|
||||||
PrometheusDataWrapper? deviceData = (await promQueryer.Query($$"""sum(power{sensor=~"{{plugnames}}"})[1h:1m]"""))?.Data;
|
PrometheusDataWrapper? deviceData = (await promQueryer.Query($$"""sum(power{sensor=~"{{plugnames}}"})[1h:1m]"""))?.Data;
|
||||||
//PrometheusDataWrapper? priceData = (await promQueryer.Query($$"""sum(sum_over_time(power{sensor=~"{{plugnames}}"}[1y])*{{energyPrice}})"""))?.Data;
|
//PrometheusDataWrapper? priceData = (await promQueryer.Query($$"""sum(sum_over_time(power{sensor=~"{{plugnames}}"}[1y])*{{energyPrice}})"""))?.Data;
|
||||||
|
|
||||||
//Console.WriteLine(priceData.VectorTypeToTimestampFloatTuple());
|
//Console.WriteLine(priceData.VectorTypeToTimestampFloatTuple());
|
||||||
|
|
||||||
Random r = new Random(DateTime.Now.Millisecond);
|
Random r = new Random(DateTime.Now.Millisecond);
|
||||||
|
|
||||||
return deviceData?.MatrixTypeToTimestampFloatTuple().ValueOrDefault?.Select(x =>
|
return deviceData?.MatrixTypeToTimestampFloatTuple().ValueOrDefault?.Select(x =>
|
||||||
{
|
{
|
||||||
labels.Add(DateTimeOffset.FromUnixTimeSeconds(long.Parse($"1{x.Item1}0")).UtcDateTime.ToLocalTime().ToShortTimeString());
|
labels.Add(DateTimeOffset.FromUnixTimeSeconds(long.Parse($"1{x.Item1}0")).UtcDateTime.ToLocalTime().ToShortTimeString());
|
||||||
return x.Item2;
|
return x.Item2;
|
||||||
}).ToList() ?? new List<double>();
|
}).ToList() ?? new List<double>();
|
||||||
}
|
}
|
||||||
|
|
||||||
//TODO: insert dataset of current and last voltage usages
|
//TODO: insert dataset of current and last voltage usages
|
||||||
private async Task<LineChartDataset<double>> GetLineChartDataset()
|
private async Task<LineChartDataset<double>> GetLineChartDataset()
|
||||||
{
|
{
|
||||||
return new LineChartDataset<double>
|
return new LineChartDataset<double>
|
||||||
{
|
{
|
||||||
Label = "Wattage",
|
Label = "Wattage",
|
||||||
Data = await GetData(),
|
Data = await GetData(),
|
||||||
Fill = true,
|
Fill = true,
|
||||||
PointRadius = 3,
|
PointRadius = 3,
|
||||||
CubicInterpolationMode = "monotone",
|
CubicInterpolationMode = "monotone",
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task HandleRedraw()
|
private async Task HandleRedraw()
|
||||||
{
|
{
|
||||||
labels.Clear();
|
labels.Clear();
|
||||||
await lineChart.Clear();
|
await lineChart.Clear();
|
||||||
await lineChart.AddLabelsDatasetsAndUpdate(labels, await GetLineChartDataset());
|
await lineChart.AddLabelsDatasetsAndUpdate(labels, await GetLineChartDataset());
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task Switch(Device device)
|
private async Task Switch(Device device)
|
||||||
{
|
{
|
||||||
device.Enabled = !device.Enabled;
|
device.Enabled = !device.Enabled;
|
||||||
_ = await DeviceManagmentService.UpdateDevice(device);
|
_ = await DeviceManagmentService.UpdateDevice(device);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -10,6 +10,7 @@
|
|||||||
|
|
||||||
@inject IDeviceManagmentService DeviceManagmentService
|
@inject IDeviceManagmentService DeviceManagmentService
|
||||||
@inject IMessageService MessageService
|
@inject IMessageService MessageService
|
||||||
|
@inject IAuthenticationService AuthenticationService
|
||||||
@inject MainDatabaseContext MainDatabaseContext
|
@inject MainDatabaseContext MainDatabaseContext
|
||||||
|
|
||||||
<Div>
|
<Div>
|
||||||
@@ -157,9 +158,9 @@
|
|||||||
Device? SelectedDevice = null;
|
Device? SelectedDevice = null;
|
||||||
Device? DeviceCopy = null;
|
Device? DeviceCopy = null;
|
||||||
|
|
||||||
protected override void OnInitialized()
|
protected override async Task OnInitializedAsync()
|
||||||
{
|
{
|
||||||
Result<List<Device>> getDevicesResult = DeviceManagmentService.GetDevices();
|
Result<List<Device>> getDevicesResult = DeviceManagmentService.GetDevices((await AuthenticationService.GetUserAsync()).ValueOrDefault);
|
||||||
|
|
||||||
if (getDevicesResult.IsSuccess)
|
if (getDevicesResult.IsSuccess)
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -8,17 +8,17 @@ namespace Elektrifikatsiya.Services;
|
|||||||
|
|
||||||
public interface IDeviceManagmentService
|
public interface IDeviceManagmentService
|
||||||
{
|
{
|
||||||
public Task<Result<Device>> RegisterDevice(IPAddress ip, User user, string? name = null, string room = "default");
|
public Task<Result<Device>> RegisterDevice(IPAddress ip, User user, string? name = null, string room = "default");
|
||||||
|
|
||||||
public Task<Result> UnregisterDevice(string macAdress);
|
public Task<Result> UnregisterDevice(string macAdress);
|
||||||
|
|
||||||
public Result<Device> GetDevice(string macAdress);
|
public Result<Device> GetDevice(string macAdress);
|
||||||
|
|
||||||
public Result<List<Device>> GetDevices();
|
public Result<List<Device>> GetDevices(User user);
|
||||||
|
|
||||||
public Result<List<Device>> GetDevicesInRoom(string room);
|
public Result<List<Device>> GetDevicesInRoom(string room);
|
||||||
|
|
||||||
public Result<List<Device>> GetDevicesOfUser(int userId);
|
public Result<List<Device>> GetDevicesOfUser(int userId);
|
||||||
|
|
||||||
public Task<Result> UpdateDevice(Device device);
|
public Task<Result> UpdateDevice(Device device);
|
||||||
}
|
}
|
||||||
+122
-122
@@ -15,168 +15,168 @@ 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 IHiveMQClient hiveMQClient;
|
private readonly IHiveMQClient hiveMQClient;
|
||||||
private readonly HttpClient httpClient;
|
private readonly HttpClient httpClient;
|
||||||
|
|
||||||
public DeviceManagmentService(IServiceScopeFactory serviceScopeFactory, IDeviceStatusService deviceStatusService, ILogger<DeviceManagmentService> logger, IHiveMQClient hiveMQClient, HttpClient httpClient)
|
public DeviceManagmentService(IServiceScopeFactory serviceScopeFactory, IDeviceStatusService deviceStatusService, ILogger<DeviceManagmentService> logger, IHiveMQClient hiveMQClient, HttpClient httpClient)
|
||||||
{
|
{
|
||||||
this.serviceScopeFactory = serviceScopeFactory;
|
this.serviceScopeFactory = serviceScopeFactory;
|
||||||
this.deviceStatusService = deviceStatusService;
|
this.deviceStatusService = deviceStatusService;
|
||||||
this.logger = logger;
|
this.logger = logger;
|
||||||
this.hiveMQClient = hiveMQClient;
|
this.hiveMQClient = hiveMQClient;
|
||||||
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(User user)
|
||||||
{
|
{
|
||||||
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.Where(d => d.User.Id == user.Id || user.Role == Role.Admin).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();
|
||||||
MainDatabaseContext mainDatabaseContext = scope.ServiceProvider.GetRequiredService<MainDatabaseContext>();
|
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);
|
||||||
|
|
||||||
mainDatabaseContext.Entry(user).State = EntityState.Unchanged;
|
mainDatabaseContext.Entry(user).State = EntityState.Unchanged;
|
||||||
|
|
||||||
_ = mainDatabaseContext.Add(device);
|
_ = mainDatabaseContext.Add(device);
|
||||||
Result saveDatabaseChangesResult = await Result.Try(Task () => mainDatabaseContext.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();
|
||||||
MainDatabaseContext mainDatabaseContext = scope.ServiceProvider.GetRequiredService<MainDatabaseContext>();
|
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;
|
||||||
}
|
}
|
||||||
|
|
||||||
_ = mainDatabaseContext.Remove(getDeviceResult.Value);
|
_ = mainDatabaseContext.Remove(getDeviceResult.Value);
|
||||||
|
|
||||||
return await Result.Try(Task () => mainDatabaseContext.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();
|
||||||
MainDatabaseContext mainDatabaseContext = scope.ServiceProvider.GetRequiredService<MainDatabaseContext>();
|
MainDatabaseContext mainDatabaseContext = scope.ServiceProvider.GetRequiredService<MainDatabaseContext>();
|
||||||
|
|
||||||
Result<Device> getDeviceResult = GetDevice(device.MacAddress);
|
Result<Device> getDeviceResult = GetDevice(device.MacAddress);
|
||||||
|
|
||||||
if (getDeviceResult.IsFailed)
|
if (getDeviceResult.IsFailed)
|
||||||
{
|
{
|
||||||
return getDeviceResult.ToResult();
|
return getDeviceResult.ToResult();
|
||||||
}
|
}
|
||||||
|
|
||||||
Result updateDeviceResult = deviceStatusService.UpdateDeviceStatus(device);
|
Result updateDeviceResult = deviceStatusService.UpdateDeviceStatus(device);
|
||||||
|
|
||||||
if (updateDeviceResult.IsFailed)
|
if (updateDeviceResult.IsFailed)
|
||||||
{
|
{
|
||||||
return updateDeviceResult;
|
return updateDeviceResult;
|
||||||
}
|
}
|
||||||
|
|
||||||
PublishResult res = await hiveMQClient.PublishAsync($"shellies/shellyplug-s-{device.MacAddress}/relay/0/command", device.Enabled ? "on" : "off");
|
PublishResult res = await hiveMQClient.PublishAsync($"shellies/shellyplug-s-{device.MacAddress}/relay/0/command", device.Enabled ? "on" : "off");
|
||||||
|
|
||||||
device.User = mainDatabaseContext.Users.First(u => u.Id == device.User.Id);
|
device.User = mainDatabaseContext.Users.First(u => u.Id == device.User.Id);
|
||||||
|
|
||||||
_ = mainDatabaseContext.Update(device);
|
_ = mainDatabaseContext.Update(device);
|
||||||
|
|
||||||
return await Result.Try(Task () => mainDatabaseContext.SaveChangesAsync());
|
return await Result.Try(Task () => mainDatabaseContext.SaveChangesAsync());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,55 +1,53 @@
|
|||||||
using Elektrifikatsiya.Models;
|
using Elektrifikatsiya.Models;
|
||||||
using FluentResults;
|
|
||||||
using System.Reflection;
|
using System.Reflection;
|
||||||
|
|
||||||
namespace Elektrifikatsiya.Services.Implementations
|
namespace Elektrifikatsiya.Services.Implementations;
|
||||||
|
|
||||||
|
public class EventService : IEventService
|
||||||
{
|
{
|
||||||
public class EventService : IEventService
|
public event EventHandler<EventServiceEventArgs>? OnEventCalled;
|
||||||
|
|
||||||
|
public List<Event> Events { get; } = new();
|
||||||
|
|
||||||
|
public EventService(IDeviceStatusService deviceStatusService, IDeviceManagmentService deviceManagmentService)
|
||||||
{
|
{
|
||||||
private readonly ILogger<EventService> logger;
|
List<Device> deviceList = deviceStatusService.GetDevices().ValueOrDefault.Select(x => x.CopyDevice()).ToList();
|
||||||
public event EventHandler<EventServiceEventArgs> OnEventCalled;
|
|
||||||
public List<Event> Events { get; } = new();
|
|
||||||
|
|
||||||
public EventService(ILogger<EventService> logger, IDeviceStatusService deviceStatusService, IDeviceManagmentService deviceManagmentService)
|
deviceStatusService.OnDeviceStatusChanged += (_, e) =>
|
||||||
{
|
{
|
||||||
this.logger = logger;
|
bool newDevice = true;
|
||||||
List<Device> deviceList = deviceManagmentService.GetDevices().ValueOrDefault.Select(x=>x.CopyDevice()).ToList();
|
Device currentDevice = deviceManagmentService.GetDevice(e.MacAddress).ValueOrDefault;
|
||||||
|
|
||||||
deviceStatusService.OnDeviceStatusChanged += (_, e) =>
|
for (int i = 0; i < deviceList.Count; i++)
|
||||||
{
|
{
|
||||||
bool newDevice = true;
|
if (deviceList[i].MacAddress == currentDevice.MacAddress)
|
||||||
Device currentDevice = deviceManagmentService.GetDevice(e.MacAddress).ValueOrDefault;
|
|
||||||
|
|
||||||
for (int i = 0; i < deviceList.Count; i++)
|
|
||||||
{
|
{
|
||||||
if (deviceList[i].MacAddress == currentDevice.MacAddress)
|
PropertyInfo[] properties = typeof(Device).GetProperties();
|
||||||
|
|
||||||
|
foreach (PropertyInfo property in properties)
|
||||||
{
|
{
|
||||||
PropertyInfo[] properties = typeof(Device).GetProperties();
|
object? currentvalue = property.GetValue(deviceList[i], null);
|
||||||
|
object? newvalue = property.GetValue(currentDevice, null);
|
||||||
foreach(PropertyInfo property in properties) {
|
if (newvalue is not null && !newvalue?.ToString()?.Equals(currentvalue?.ToString()) == true)
|
||||||
var currentvalue = property.GetValue(deviceList[i], null);
|
{
|
||||||
var newvalue = property.GetValue(currentDevice, null);
|
string eventName = $"Plug {deviceList[i].Name} changed: {property.Name}";
|
||||||
if(newvalue is not null && !newvalue.ToString().Equals(currentvalue.ToString()))
|
string description = $"Changed {property.Name} of plug [{currentvalue}] to [{newvalue}]";
|
||||||
{
|
DateTime dateTime = DateTime.Now;
|
||||||
string eventName = $"Plug {deviceList[i].Name} changed: {property.Name}";
|
|
||||||
string description = $"Changed {property.Name} of plug [{currentvalue}] to [{newvalue}]";
|
|
||||||
DateTime dateTime = DateTime.Now;
|
|
||||||
|
|
||||||
Event newEvent = new Event(eventName, description, dateTime, currentDevice);
|
|
||||||
Events.Insert(0,newEvent);
|
|
||||||
OnEventCalled?.Invoke(this, new EventServiceEventArgs(newEvent));
|
|
||||||
}
|
|
||||||
|
|
||||||
|
Event newEvent = new Event(eventName, description, dateTime, currentDevice);
|
||||||
|
Events.Insert(0, newEvent);
|
||||||
|
OnEventCalled?.Invoke(this, new EventServiceEventArgs(newEvent));
|
||||||
}
|
}
|
||||||
deviceList[i].OverwiteDevice(currentDevice);
|
|
||||||
newDevice = false; break;
|
|
||||||
}
|
}
|
||||||
|
deviceList[i].OverwiteDevice(currentDevice);
|
||||||
|
newDevice = false; break;
|
||||||
}
|
}
|
||||||
if (newDevice)
|
}
|
||||||
{
|
if (newDevice)
|
||||||
deviceList.Add(deviceManagmentService.GetDevice(e.MacAddress).ValueOrDefault);
|
{
|
||||||
}
|
deviceList.Add(deviceManagmentService.GetDevice(e.MacAddress).ValueOrDefault);
|
||||||
};
|
}
|
||||||
}
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -4,20 +4,20 @@ namespace Elektrifikatsiya.Utilities;
|
|||||||
|
|
||||||
public class EmailSettings
|
public class EmailSettings
|
||||||
{
|
{
|
||||||
public string User { get; set; }
|
public string User { get; set; }
|
||||||
public string DefaultEmail { get; set; }
|
public string DefaultEmail { get; set; }
|
||||||
public string Key { get; set; }
|
public string Key { get; set; }
|
||||||
public Dictionary<string, string> Templates { get; set; }
|
public Dictionary<string, string> Templates { get; set; }
|
||||||
public string SmtpServer { get; set; }
|
public string SmtpServer { get; set; }
|
||||||
public int SmtpPort { get; set; }
|
public int SmtpPort { get; set; }
|
||||||
|
|
||||||
public Dictionary<string, HandlebarsTemplate<object, object>> CompiledTemplates = new();
|
public Dictionary<string, HandlebarsTemplate<object, object>> CompiledTemplates { get; } = new();
|
||||||
|
|
||||||
public void CompileTemplates()
|
public void CompileTemplates()
|
||||||
{
|
{
|
||||||
foreach ((string templateName, string templatePath) in Templates)
|
foreach ((string templateName, string templatePath) in Templates)
|
||||||
{
|
{
|
||||||
CompiledTemplates.Add(templateName, Handlebars.Compile(File.ReadAllText(templatePath)));
|
CompiledTemplates.Add(templateName, Handlebars.Compile(File.ReadAllText(templatePath)));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Reference in New Issue
Block a user