mirror of
https://github.com/Stefan-5422/-T5-Elektrifikatsiya.git
synced 2026-09-04 00:45:58 +02:00
Add Authentication stuff
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">
|
||||
<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 System.Net
|
||||
@using Elektrifikatsiya.Services;
|
||||
@@ -10,190 +11,193 @@
|
||||
@inject IMessageService MessageService
|
||||
@inject IAuthenticationService AuthenthicationService;
|
||||
@inject NavigationManager NavigationManager;
|
||||
<Div>
|
||||
<Row Style="width: 100%; height: 100%" Margin="Margin.Is3.FromTop.OnMobile" Padding="Padding.Is4.FromStart.OnMobile">
|
||||
|
||||
<Div Display="Display.Flex.Row.OnDesktop" Margin=" Margin.Is3.FromBottom" Width="Width.Is100">
|
||||
<Column ColumnSize="ColumnSize.Is5.OnDesktop.Is12.OnMobile">
|
||||
<Bar Breakpoint="Breakpoint.Desktop"
|
||||
Background="Background.White"
|
||||
ThemeContrast="ThemeContrast.None"
|
||||
Shadow="Shadow.Remove"
|
||||
Border="Border.Is1.RoundedTop">
|
||||
<BarBrand>
|
||||
<Column ColumnSize="ColumnSize.Is12">
|
||||
Users
|
||||
</Column>
|
||||
<Column ColumnSize="ColumnSize.Is12.Is11.WithOffset.OnDesktop.IsAuto.OnMobile">
|
||||
<Button Clicked="@ShowModalAddUser" TextAlignment="TextAlignment.End" Shadow="Shadow.Remove">
|
||||
<BarIcon IconName="IconName.Add"></BarIcon>
|
||||
</Button>
|
||||
</Column>
|
||||
</BarBrand>
|
||||
|
||||
|
||||
|
||||
|
||||
</Bar>
|
||||
<ListView TItem="User"
|
||||
Data="@users"
|
||||
TextField="@((_)=>(""))"
|
||||
ValueField="@((_)=>(""))"
|
||||
Style="border-radius: 0px 0px"
|
||||
Height="100%"
|
||||
MaxHeight="90%">
|
||||
<ItemTemplate>
|
||||
<ListGroupItem Border="Border.OnBottom">
|
||||
<Row>
|
||||
|
||||
<Column ColumnSize="ColumnSize.Is6">
|
||||
<Row>
|
||||
<Column ColumnSize="ColumnSize.Is7">
|
||||
<Heading Size="HeadingSize.Is6" Margin="Margin.Is1.FromBottom">@context.Item.Name</Heading>
|
||||
</Column>
|
||||
</Row>
|
||||
<Row>
|
||||
<Column>
|
||||
<Small>Name: @context.Item.Name</Small>
|
||||
<br />
|
||||
<Small>Rolle: @context.Item.Role</Small>
|
||||
<br />
|
||||
<Small>E-Mail: @context.Item.Email</Small>
|
||||
</Column>
|
||||
</Row>
|
||||
<Protected RequiredRole="Role.Admin">
|
||||
<Authorized>
|
||||
<Div>
|
||||
<Row Style="width: 100%; height: 100%" Margin="Margin.Is3.FromTop.OnMobile" Padding="Padding.Is4.FromStart.OnMobile">
|
||||
<Div Display="Display.Flex.Row.OnDesktop" Margin=" Margin.Is3.FromBottom" Width="Width.Is100">
|
||||
<Column ColumnSize="ColumnSize.Is5.OnDesktop.Is12.OnMobile">
|
||||
<Bar Breakpoint="Breakpoint.Desktop"
|
||||
Background="Background.White"
|
||||
ThemeContrast="ThemeContrast.None"
|
||||
Shadow="Shadow.Remove"
|
||||
Border="Border.Is1.RoundedTop">
|
||||
<BarBrand>
|
||||
<Column ColumnSize="ColumnSize.Is12">
|
||||
Users
|
||||
</Column>
|
||||
|
||||
<Column ColumnSize="ColumnSize.Is4.OnDesktop.Is7.OnMobile">
|
||||
<Button @onclick="() => Delete(context.Item)" class="btn1" Position="Position.Absolute.Top.Is50.Start.Is50.Translate.Middle" Color="Color.Dark" Outline>
|
||||
<BarIcon IconName="IconName.Delete" />
|
||||
<Column ColumnSize="ColumnSize.Is12.Is11.WithOffset.OnDesktop.IsAuto.OnMobile">
|
||||
<Button Clicked="@ShowModalAddUser" TextAlignment="TextAlignment.End" Shadow="Shadow.Remove">
|
||||
<BarIcon IconName="IconName.Add"></BarIcon>
|
||||
</Button>
|
||||
<style>
|
||||
.btn1:hover {
|
||||
background: #E50000;
|
||||
}
|
||||
</style>
|
||||
|
||||
<Modal @ref="modalRefAddUser">
|
||||
<ModalContent Centered>
|
||||
<ModalHeader>
|
||||
<ModalTitle>Add User</ModalTitle>
|
||||
<CloseButton />
|
||||
</ModalHeader>
|
||||
<ModalBody>
|
||||
<Field>
|
||||
<FieldLabel>User Name</FieldLabel>
|
||||
<TextEdit @ref="modalAddUserName" Placeholder="Enter new name..." />
|
||||
</Field>
|
||||
<Field>
|
||||
<FieldLabel>User E-Mail</FieldLabel>
|
||||
<TextEdit @ref="modalAddUserEmail" Placeholder="Enter new E-mail..." />
|
||||
</Field>
|
||||
<Field>
|
||||
<FieldLabel>User Password</FieldLabel>
|
||||
<TextEdit @ref="modalAddUserPW" Placeholder="Enter new password..." />
|
||||
</Field>
|
||||
</ModalBody>
|
||||
<ModalFooter>
|
||||
<Button Color="Color.Secondary" style="border-bottom-left-radius: 3px; border-bottom-right-radius: 3px" Clicked="@HideModalAddUser">Close</Button>
|
||||
<Button Color="Color.Primary" style="border-bottom-left-radius: 0px; border-bottom-right-radius: 0" Clicked="@AddButtonPressed">Add</Button>
|
||||
</ModalFooter>
|
||||
</ModalContent>
|
||||
</Modal>
|
||||
</Column>
|
||||
</BarBrand>
|
||||
</Bar>
|
||||
<ListView TItem="User"
|
||||
Data="@users"
|
||||
TextField="@((_)=>(""))"
|
||||
ValueField="@((_)=>(""))"
|
||||
Style="border-radius: 0px 0px"
|
||||
Height="100%"
|
||||
MaxHeight="90%">
|
||||
<ItemTemplate>
|
||||
<ListGroupItem Border="Border.OnBottom">
|
||||
<Row>
|
||||
|
||||
<Column ColumnSize="ColumnSize.Is6">
|
||||
<Row>
|
||||
<Column ColumnSize="ColumnSize.Is7">
|
||||
<Heading Size="HeadingSize.Is6" Margin="Margin.Is1.FromBottom">@context.Item.Name</Heading>
|
||||
</Column>
|
||||
</Row>
|
||||
<Row>
|
||||
<Column>
|
||||
<Small>Name: @context.Item.Name</Small>
|
||||
<br />
|
||||
<Small>Rolle: @context.Item.Role</Small>
|
||||
<br />
|
||||
<Small>E-Mail: @context.Item.Email</Small>
|
||||
</Column>
|
||||
</Row>
|
||||
</Column>
|
||||
|
||||
<Column ColumnSize="ColumnSize.Is4.OnDesktop.Is7.OnMobile">
|
||||
<Button @onclick="() => Delete(context.Item)" class="btn1" Position="Position.Absolute.Top.Is50.Start.Is50.Translate.Middle" Color="Color.Dark" Outline>
|
||||
<BarIcon IconName="IconName.Delete" />
|
||||
</Button>
|
||||
<style>
|
||||
.btn1:hover {
|
||||
background: #E50000;
|
||||
}
|
||||
</style>
|
||||
|
||||
<Modal @ref="modalRefAddUser">
|
||||
<ModalContent Centered>
|
||||
<ModalHeader>
|
||||
<ModalTitle>Add User</ModalTitle>
|
||||
<CloseButton />
|
||||
</ModalHeader>
|
||||
<ModalBody>
|
||||
<Field>
|
||||
<FieldLabel>User Name</FieldLabel>
|
||||
<TextEdit @ref="modalAddUserName" Placeholder="Enter new name..." />
|
||||
</Field>
|
||||
<Field>
|
||||
<FieldLabel>User E-Mail</FieldLabel>
|
||||
<TextEdit @ref="modalAddUserEmail" Placeholder="Enter new E-mail..." />
|
||||
</Field>
|
||||
<Field>
|
||||
<FieldLabel>User Password</FieldLabel>
|
||||
<TextEdit @ref="modalAddUserPW" Placeholder="Enter new password..." />
|
||||
</Field>
|
||||
</ModalBody>
|
||||
<ModalFooter>
|
||||
<Button Color="Color.Secondary" style="border-bottom-left-radius: 3px; border-bottom-right-radius: 3px" Clicked="@HideModalAddUser">Close</Button>
|
||||
<Button Color="Color.Primary" style="border-bottom-left-radius: 0px; border-bottom-right-radius: 0" Clicked="@AddButtonPressed">Add</Button>
|
||||
</ModalFooter>
|
||||
</ModalContent>
|
||||
</Modal>
|
||||
</Column>
|
||||
<br />
|
||||
<br />
|
||||
<Row>
|
||||
<Column ColumnSize="ColumnSize.Is1.OnDesktop">
|
||||
<Button @onclick="() => Toggle(context.Item)" Position="Position.Absolute.Top.Is50.Start.Is100.Translate.Middle" Color="Color.Dark" Outline>
|
||||
<BarIcon IconName="IconName.Pen" />
|
||||
</Button>
|
||||
</Column>
|
||||
</Row>
|
||||
|
||||
</Row>
|
||||
</ListGroupItem>
|
||||
</ItemTemplate>
|
||||
</ListView>
|
||||
</Column>
|
||||
<Column ColumnSize="ColumnSize.Is6.OnDesktop.Is12.OnMobile" Margin="Margin.Is3.FromTop.OnMobile" Padding="Padding.Is4.FromStart.OnMobile">
|
||||
@if (SelectedUser is not null)
|
||||
{
|
||||
<Div hidden="@hideButtonSettings">
|
||||
<Field>
|
||||
<FieldLabel>
|
||||
<h2>
|
||||
User Settings
|
||||
</h2>
|
||||
</FieldLabel>
|
||||
</Field>
|
||||
<Field>
|
||||
<FieldLabel>
|
||||
<h5>
|
||||
User Name
|
||||
</h5>
|
||||
<Paragraph>
|
||||
Here you can change the name of the User
|
||||
</Paragraph>
|
||||
</FieldLabel>
|
||||
<TextEdit @bind-Text="@SelectedUser.Name" Placeholder="Enter User Name" />
|
||||
</Field>
|
||||
<br />
|
||||
<br />
|
||||
<Row>
|
||||
<Column ColumnSize="ColumnSize.Is1.OnDesktop">
|
||||
<Button @onclick="() => Toggle(context.Item)" Position="Position.Absolute.Top.Is50.Start.Is100.Translate.Middle" Color="Color.Dark" Outline>
|
||||
<BarIcon IconName="IconName.Pen" />
|
||||
</Button>
|
||||
</Column>
|
||||
</Row>
|
||||
|
||||
</Row>
|
||||
</ListGroupItem>
|
||||
</ItemTemplate>
|
||||
</ListView>
|
||||
</Column>
|
||||
<Column ColumnSize="ColumnSize.Is6.OnDesktop.Is12.OnMobile" Margin="Margin.Is3.FromTop.OnMobile" Padding="Padding.Is4.FromStart.OnMobile">
|
||||
@if (SelectedUser is not null)
|
||||
{
|
||||
<Div hidden="@hideButtonSettings">
|
||||
<Field>
|
||||
<FieldLabel>
|
||||
<h2>
|
||||
User Settings
|
||||
</h2>
|
||||
</FieldLabel>
|
||||
</Field>
|
||||
<Field>
|
||||
<FieldLabel>
|
||||
<h5>
|
||||
User Name
|
||||
</h5>
|
||||
<Paragraph>
|
||||
Here you can change the name of the User
|
||||
</Paragraph>
|
||||
</FieldLabel>
|
||||
<TextEdit @bind-Text="@SelectedUser.Name" Placeholder="Enter User Name" />
|
||||
</Field>
|
||||
<br />
|
||||
<br />
|
||||
<Field>
|
||||
<FieldLabel>
|
||||
<h5>
|
||||
E-Mail
|
||||
</h5>
|
||||
<Paragraph>
|
||||
Here you can change the E-Mail of a User
|
||||
</Paragraph>
|
||||
</FieldLabel>
|
||||
<TextEdit @bind-Text="@SelectedUser.Email" Placeholder="Enter new email" />
|
||||
</Field>
|
||||
<br />
|
||||
<Field>
|
||||
<FieldLabel>
|
||||
<h5>
|
||||
Password
|
||||
</h5>
|
||||
<Paragraph>
|
||||
Here you can change the password of a User
|
||||
</Paragraph>
|
||||
</FieldLabel>
|
||||
<TextEdit Placeholder="Enter old password" />
|
||||
<br />
|
||||
<TextEdit Placeholder="Enter new password" />
|
||||
</Field>
|
||||
<br />
|
||||
<br />
|
||||
<Field>
|
||||
<FieldLabel>
|
||||
<h5>
|
||||
Select Role
|
||||
</h5>
|
||||
<Paragraph>
|
||||
Here you select or change the role of to User or Admin
|
||||
</Paragraph>
|
||||
</FieldLabel>
|
||||
<br />
|
||||
<Dropdown Display="Display.InlineBlock">
|
||||
<DropdownToggle Color="Color.Primary" Width="Width.Is100">Roles</DropdownToggle>
|
||||
<DropdownMenu>
|
||||
<DropdownItem>Admin</DropdownItem>
|
||||
<DropdownDivider />
|
||||
<DropdownItem>User</DropdownItem>
|
||||
</DropdownMenu>
|
||||
</Dropdown>
|
||||
</Field>
|
||||
<Column ColumnSize="ColumnSize.IsFull" TextAlignment="TextAlignment.End">
|
||||
<Button Color="Color.Primary">Save</Button>
|
||||
</Column>
|
||||
</Div>
|
||||
}
|
||||
</Column>
|
||||
<Field>
|
||||
<FieldLabel>
|
||||
<h5>
|
||||
E-Mail
|
||||
</h5>
|
||||
<Paragraph>
|
||||
Here you can change the E-Mail of a User
|
||||
</Paragraph>
|
||||
</FieldLabel>
|
||||
<TextEdit @bind-Text="@SelectedUser.Email" Placeholder="Enter new email" />
|
||||
</Field>
|
||||
<br />
|
||||
<Field>
|
||||
<FieldLabel>
|
||||
<h5>
|
||||
Password
|
||||
</h5>
|
||||
<Paragraph>
|
||||
Here you can change the password of a User
|
||||
</Paragraph>
|
||||
</FieldLabel>
|
||||
<TextEdit Placeholder="Enter old password" />
|
||||
<br />
|
||||
<TextEdit Placeholder="Enter new password" />
|
||||
</Field>
|
||||
<br />
|
||||
<br />
|
||||
<Field>
|
||||
<FieldLabel>
|
||||
<h5>
|
||||
Select Role
|
||||
</h5>
|
||||
<Paragraph>
|
||||
Here you select or change the role of to User or Admin
|
||||
</Paragraph>
|
||||
</FieldLabel>
|
||||
<br />
|
||||
<Dropdown Display="Display.InlineBlock">
|
||||
<DropdownToggle Color="Color.Primary" Width="Width.Is100">Roles</DropdownToggle>
|
||||
<DropdownMenu>
|
||||
<DropdownItem>Admin</DropdownItem>
|
||||
<DropdownDivider />
|
||||
<DropdownItem>User</DropdownItem>
|
||||
</DropdownMenu>
|
||||
</Dropdown>
|
||||
</Field>
|
||||
<Column ColumnSize="ColumnSize.IsFull" TextAlignment="TextAlignment.End">
|
||||
<Button Color="Color.Primary">Save</Button>
|
||||
</Column>
|
||||
</Div>
|
||||
}
|
||||
</Column>
|
||||
</Div>
|
||||
</Row>
|
||||
</Div>
|
||||
</Row>
|
||||
</Div>
|
||||
</Authorized>
|
||||
<NotAuthorized>
|
||||
Bro no! this page is only for admins! 😠
|
||||
</NotAuthorized>
|
||||
</Protected>
|
||||
|
||||
@code {
|
||||
List<User> users = new List<User>();
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
+122
-122
@@ -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);
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user