Merge branch 'Development' of https://github.com/Stefan-5422/-T5-Elektrifikatsiya into Development

This commit is contained in:
Friend2868
2023-06-13 23:41:34 +02:00
10 changed files with 271 additions and 266 deletions
@@ -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">
<BarToggler TextColor="TextColor.Primary" />
<BarBrand>
@@ -15,14 +16,18 @@
<BarLink To="/" TextColor="TextColor.White">
<BarIcon Style="color:white" IconName="IconName.Dashboard" />
Dashboard
</BarLink>
</BarItem>
<BarItem>
<BarLink To="/admin" TextColor="TextColor.White">
<BarIcon Style="color:white" IconName="IconName.ShieldAlt" />
Admin
</BarLink>
</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>
<BarLink To="/settings" TextColor="TextColor.White">
<BarIcon Style="color:white" IconName="IconName.Wrench" />
@@ -1,5 +1,6 @@
@page "/Admin"
@using Blazorise.Components;
@using Elektrifikatsiya.Components
@using Elektrifikatsiya.Models;
@using Elektrifikatsiya.Database;
@using System.Net
@@ -12,6 +12,7 @@
@inject IDeviceStatusService DeviceStatusService;
@inject IDeviceManagmentService DeviceManagmentService;
@inject IEventService EventService;
@inject IAuthenticationService AuthenticationService;
@inject IEnergyPriceService EnergyPriceService;
@inject MainDatabaseContext MainDatabaseContext;
@@ -8,94 +8,94 @@ namespace Elektrifikatsiya.Pages;
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
private List<Event> events = new List<Event>() { new Event("Text", "Text", DateTime.Today, null) };
//TODO: insert new event here if plug produces one
private List<Event> events = new List<Event>() { new Event("Text", "Text", DateTime.Today, null) };
//code for graph
private LineChart<double> lineChart;
//code for graph
private LineChart<double> lineChart;
//TODO: insert new Device here if user adds one
private List<Device> plugs = new List<Device>();
//TODO: insert new Device here if user adds one
private List<Device> plugs = new List<Device>();
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
await HandleRedraw();
}
}
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
await HandleRedraw();
}
}
protected override void OnInitialized()
{
plugs = DeviceStatusService.GetDevices().ValueOrDefault ?? new List<Device>();
events = EventService.Events;
protected override async Task OnInitializedAsync()
{
plugs = DeviceManagmentService.GetDevices((await AuthenticationService.GetUserAsync()).ValueOrDefault).ValueOrDefault ?? new List<Device>();
events = EventService.Events;
EventService.OnEventCalled += (__, e) =>
{
_ = InvokeAsync(StateHasChanged);
};
DeviceStatusService.OnDeviceStatusChanged += (__, e) =>
{
_ = InvokeAsync(StateHasChanged);
};
}
EventService.OnEventCalled += (__, e) =>
{
_ = InvokeAsync(StateHasChanged);
};
DeviceStatusService.OnDeviceStatusChanged += (__, e) =>
{
_ = InvokeAsync(StateHasChanged);
};
}
private async Task<List<double>> GetData()
{
if (plugs.Count == 0)
{
return new();
}
PrometheusQuery promQueryer = new PrometheusQuery("http://localhost:9090");
private async Task<List<double>> GetData()
{
if (plugs.Count == 0)
{
return new();
}
PrometheusQuery promQueryer = new PrometheusQuery("http://localhost:9090");
string plugnames = "";
foreach (Device device in plugs)
{
plugnames += $"shellyplug-s-{device.MacAddress}/relay/0|";
}
plugnames = plugnames[0..^1];
string plugnames = "";
foreach (Device device in plugs)
{
plugnames += $"shellyplug-s-{device.MacAddress}/relay/0|";
}
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? priceData = (await promQueryer.Query($$"""sum(sum_over_time(power{sensor=~"{{plugnames}}"}[1y])*{{energyPrice}})"""))?.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;
//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 =>
{
labels.Add(DateTimeOffset.FromUnixTimeSeconds(long.Parse($"1{x.Item1}0")).UtcDateTime.ToLocalTime().ToShortTimeString());
return x.Item2;
}).ToList() ?? new List<double>();
}
return deviceData?.MatrixTypeToTimestampFloatTuple().ValueOrDefault?.Select(x =>
{
labels.Add(DateTimeOffset.FromUnixTimeSeconds(long.Parse($"1{x.Item1}0")).UtcDateTime.ToLocalTime().ToShortTimeString());
return x.Item2;
}).ToList() ?? new List<double>();
}
//TODO: insert dataset of current and last voltage usages
private async Task<LineChartDataset<double>> GetLineChartDataset()
{
return new LineChartDataset<double>
{
Label = "Wattage",
Data = await GetData(),
Fill = true,
PointRadius = 3,
CubicInterpolationMode = "monotone",
};
}
//TODO: insert dataset of current and last voltage usages
private async Task<LineChartDataset<double>> GetLineChartDataset()
{
return new LineChartDataset<double>
{
Label = "Wattage",
Data = await GetData(),
Fill = true,
PointRadius = 3,
CubicInterpolationMode = "monotone",
};
}
private async Task HandleRedraw()
{
labels.Clear();
await lineChart.Clear();
await lineChart.AddLabelsDatasetsAndUpdate(labels, await GetLineChartDataset());
}
private async Task HandleRedraw()
{
labels.Clear();
await lineChart.Clear();
await lineChart.AddLabelsDatasetsAndUpdate(labels, await GetLineChartDataset());
}
private async Task Switch(Device device)
{
device.Enabled = !device.Enabled;
_ = await DeviceManagmentService.UpdateDevice(device);
}
private async Task Switch(Device device)
{
device.Enabled = !device.Enabled;
_ = await DeviceManagmentService.UpdateDevice(device);
}
}
@@ -10,6 +10,7 @@
@inject IDeviceManagmentService DeviceManagmentService
@inject IMessageService MessageService
@inject IAuthenticationService AuthenticationService
@inject MainDatabaseContext MainDatabaseContext
<Div>
@@ -157,9 +158,9 @@
Device? SelectedDevice = 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)
{
@@ -8,17 +8,17 @@ namespace Elektrifikatsiya.Services;
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);
}
@@ -15,168 +15,168 @@ namespace Elektrifikatsiya.Services.Implementations;
public class DeviceManagmentService : IDeviceManagmentService
{
private readonly IServiceScopeFactory serviceScopeFactory;
private readonly IDeviceStatusService deviceStatusService;
private readonly ILogger<DeviceManagmentService> logger;
private readonly IHiveMQClient hiveMQClient;
private readonly HttpClient httpClient;
private readonly IServiceScopeFactory serviceScopeFactory;
private readonly IDeviceStatusService deviceStatusService;
private readonly ILogger<DeviceManagmentService> logger;
private readonly IHiveMQClient hiveMQClient;
private readonly HttpClient httpClient;
public DeviceManagmentService(IServiceScopeFactory serviceScopeFactory, IDeviceStatusService deviceStatusService, ILogger<DeviceManagmentService> logger, IHiveMQClient hiveMQClient, HttpClient httpClient)
{
this.serviceScopeFactory = serviceScopeFactory;
this.deviceStatusService = deviceStatusService;
this.logger = logger;
this.hiveMQClient = hiveMQClient;
this.httpClient = httpClient;
}
public DeviceManagmentService(IServiceScopeFactory serviceScopeFactory, IDeviceStatusService deviceStatusService, ILogger<DeviceManagmentService> logger, IHiveMQClient hiveMQClient, HttpClient httpClient)
{
this.serviceScopeFactory = serviceScopeFactory;
this.deviceStatusService = deviceStatusService;
this.logger = logger;
this.hiveMQClient = hiveMQClient;
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(User user)
{
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.Where(d => d.User.Id == user.Id || user.Role == Role.Admin).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();
MainDatabaseContext mainDatabaseContext = scope.ServiceProvider.GetRequiredService<MainDatabaseContext>();
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);
mainDatabaseContext.Entry(user).State = EntityState.Unchanged;
mainDatabaseContext.Entry(user).State = EntityState.Unchanged;
_ = mainDatabaseContext.Add(device);
Result saveDatabaseChangesResult = await Result.Try(Task () => mainDatabaseContext.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();
MainDatabaseContext mainDatabaseContext = scope.ServiceProvider.GetRequiredService<MainDatabaseContext>();
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;
}
_ = 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)
{
using IServiceScope scope = serviceScopeFactory.CreateScope();
MainDatabaseContext mainDatabaseContext = scope.ServiceProvider.GetRequiredService<MainDatabaseContext>();
public async Task<Result> UpdateDevice(Device device)
{
using IServiceScope scope = serviceScopeFactory.CreateScope();
MainDatabaseContext mainDatabaseContext = scope.ServiceProvider.GetRequiredService<MainDatabaseContext>();
Result<Device> getDeviceResult = GetDevice(device.MacAddress);
Result<Device> getDeviceResult = GetDevice(device.MacAddress);
if (getDeviceResult.IsFailed)
{
return getDeviceResult.ToResult();
}
if (getDeviceResult.IsFailed)
{
return getDeviceResult.ToResult();
}
Result updateDeviceResult = deviceStatusService.UpdateDeviceStatus(device);
Result updateDeviceResult = deviceStatusService.UpdateDeviceStatus(device);
if (updateDeviceResult.IsFailed)
{
return updateDeviceResult;
}
if (updateDeviceResult.IsFailed)
{
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 FluentResults;
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;
public event EventHandler<EventServiceEventArgs> OnEventCalled;
public List<Event> Events { get; } = new();
List<Device> deviceList = deviceStatusService.GetDevices().ValueOrDefault.Select(x => x.CopyDevice()).ToList();
public EventService(ILogger<EventService> logger, IDeviceStatusService deviceStatusService, IDeviceManagmentService deviceManagmentService)
deviceStatusService.OnDeviceStatusChanged += (_, e) =>
{
this.logger = logger;
List<Device> deviceList = deviceManagmentService.GetDevices().ValueOrDefault.Select(x=>x.CopyDevice()).ToList();
bool newDevice = true;
Device currentDevice = deviceManagmentService.GetDevice(e.MacAddress).ValueOrDefault;
deviceStatusService.OnDeviceStatusChanged += (_, e) =>
for (int i = 0; i < deviceList.Count; i++)
{
bool newDevice = true;
Device currentDevice = deviceManagmentService.GetDevice(e.MacAddress).ValueOrDefault;
for (int i = 0; i < deviceList.Count; i++)
if (deviceList[i].MacAddress == currentDevice.MacAddress)
{
if (deviceList[i].MacAddress == currentDevice.MacAddress)
PropertyInfo[] properties = typeof(Device).GetProperties();
foreach (PropertyInfo property in properties)
{
PropertyInfo[] properties = typeof(Device).GetProperties();
foreach(PropertyInfo property in properties) {
var currentvalue = property.GetValue(deviceList[i], null);
var newvalue = property.GetValue(currentDevice, null);
if(newvalue is not null && !newvalue.ToString().Equals(currentvalue.ToString()))
{
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));
}
object? currentvalue = property.GetValue(deviceList[i], null);
object? newvalue = property.GetValue(currentDevice, null);
if (newvalue is not null && !newvalue?.ToString()?.Equals(currentvalue?.ToString()) == true)
{
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));
}
deviceList[i].OverwiteDevice(currentDevice);
newDevice = false; break;
}
deviceList[i].OverwiteDevice(currentDevice);
newDevice = false; break;
}
if (newDevice)
{
deviceList.Add(deviceManagmentService.GetDevice(e.MacAddress).ValueOrDefault);
}
};
}
}
if (newDevice)
{
deviceList.Add(deviceManagmentService.GetDevice(e.MacAddress).ValueOrDefault);
}
};
}
}
}
@@ -4,20 +4,20 @@ namespace Elektrifikatsiya.Utilities;
public class EmailSettings
{
public string User { get; set; }
public string DefaultEmail { get; set; }
public string Key { get; set; }
public Dictionary<string, string> Templates { get; set; }
public string SmtpServer { get; set; }
public int SmtpPort { get; set; }
public string User { get; set; }
public string DefaultEmail { get; set; }
public string Key { get; set; }
public Dictionary<string, string> Templates { get; set; }
public string SmtpServer { get; set; }
public int SmtpPort { get; set; }
public Dictionary<string, HandlebarsTemplate<object, object>> CompiledTemplates = new();
public void CompileTemplates()
{
foreach ((string templateName, string templatePath) in Templates)
{
CompiledTemplates.Add(templateName, Handlebars.Compile(File.ReadAllText(templatePath)));
}
public Dictionary<string, HandlebarsTemplate<object, object>> CompiledTemplates { get; } = new();
public void CompileTemplates()
{
foreach ((string templateName, string templatePath) in Templates)
{
CompiledTemplates.Add(templateName, Handlebars.Compile(File.ReadAllText(templatePath)));
}
}
}