* Added Login System
* Added Query from Prom
* Changed Dashboard to display data
This commit is contained in:
Stefan
2023-03-22 14:09:30 +01:00
parent 40b9d9aa61
commit 12b8004a93
20 changed files with 554 additions and 109 deletions
@@ -0,0 +1 @@

@@ -0,0 +1,42 @@
@using Elektrifikatsiya.Models
@inject Services.IAuthorizationService AuthorizationService
@if (IsAuthorized)
{
@Authorized
}
else if (!loaded && UseLoadingScreen)
{
@Loading
}
else if (loaded)
{
@NotAuthorized
}
@code {
[Parameter]
public RenderFragment? Authorized { get; set; }
[Parameter]
public RenderFragment? NotAuthorized { get; set; }
[Parameter]
public RenderFragment? Loading { get; set; }
[Parameter]
public Role RequiredRole { get; set; }
[Parameter]
public bool UseLoadingScreen { get; set; }
public bool IsAuthorized { get; set; }
private bool loaded;
protected override async Task OnParametersSetAsync()
{
IsAuthorized = (await AuthorizationService.IsAuthorized(RequiredRole)).ValueOrDefault;
StateHasChanged();
loaded = true;
}
}
@@ -40,10 +40,14 @@
<PackageReference Include="Blazorise.Material" Version="1.2.0" /> <PackageReference Include="Blazorise.Material" Version="1.2.0" />
<PackageReference Include="Blazorise.Icons.Material" Version="1.2.0" /> <PackageReference Include="Blazorise.Icons.Material" Version="1.2.0" />
<PackageReference Include="BCrypt.Net-Next" Version="4.0.3" /> <PackageReference Include="BCrypt.Net-Next" Version="4.0.3" />
<PackageReference Include="FluentResults" Version="3.15.1" /> <PackageReference Include="FluentResults" Version="3.15.2" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.2" /> <PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.4" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="7.0.2" /> <PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="7.0.4" />
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.17.0" /> <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="7.0.4">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.18.1" />
<PackageReference Include="Tmds.MDns" Version="0.7.1" /> <PackageReference Include="Tmds.MDns" Version="0.7.1" />
</ItemGroup> </ItemGroup>
@@ -1,18 +1,40 @@
@using System.Diagnostics; @using System.Diagnostics;
@using FluentResults
@inject Elektrifikatsiya.Services.IAuthenticationService AuthenticationService
@inject NavigationManager NavigationManager
@inherits LayoutComponentBase @inherits LayoutComponentBase
<Image Source="logo.png" Width="Width.Is50" Height="Height.Is50"> </Image> <Image Source="logo.png" Width="Width.Is50" Height="Height.Is50"> </Image>
<Card Width="Width.Is50" Position="Position.Absolute.Top.Is50.Start.Is50.Translate.Middle" Padding="Padding.Is5"> <Card Width="Width.Is50" Position="Position.Absolute.Top.Is50.Start.Is50.Translate.Middle" Padding="Padding.Is5">
<Field Width="Width.Is25" Position="Position.Relative.Top.Is50.Start.Is50.Translate.Middle"> <Field Width="Width.Is25" Position="Position.Relative.Top.Is50.Start.Is50.Translate.Middle">
<TextEdit Placeholder="Username" /> <TextEdit @bind-Text="username" Placeholder="Username" />
</Field> </Field>
<Field Width="Width.Is25" Position="Position.Relative.Top.Is50.Start.Is50.Translate.Middle"> <Field Width="Width.Is25" Position="Position.Relative.Top.Is50.Start.Is50.Translate.Middle">
<TextEdit Role="TextRole.Password" Placeholder="Password" /> <TextEdit @bind-Text="password" Role="TextRole.Password" Placeholder="Password" />
</Field> </Field>
<Button Width="Width.Is25" Color="Color.Primary" Clicked="Clicked" Position="Position.Relative.Bottom.Is50.Start.Is50.Translate.MiddleX" >Login</Button> <Button Width="Width.Is25" Disabled="disabled" Color="color" Clicked="Clicked" Position="Position.Relative.Bottom.Is50.Start.Is50.Translate.MiddleX" >Login</Button>
</Card> </Card>
@code { @code {
private void Clicked() private string username = string.Empty;
private string password = string.Empty;
private Color color = Color.Primary;
private bool disabled;
private async Task Clicked()
{ {
Debug.WriteLine("Button was clicked!"); color = Color.Primary;
disabled = true;
Result loginResult = await AuthenticationService.LoginUserAsync(username, password);
if (loginResult.IsSuccess)
{
NavigationManager.NavigateTo("/", true);
}
else
{
color = Color.Danger;
disabled = false;
}
} }
} }
<!-- TODO: Put this into the Component once we are merging and refactoring -->
@@ -1,7 +1,11 @@
@using Elektrifikatsiya.Components.Layout @using Elektrifikatsiya.Components
@using Elektrifikatsiya.Components.Layout
@using Elektrifikatsiya.Models
@inherits LayoutComponentBase @inherits LayoutComponentBase
@inject NavigationManager NavigationManager
<Layout Sider> <Protected RequiredRole="Role.User">
<Authorized>
<Layout Sider>
<LayoutSider> <LayoutSider>
<LayoutSiderContent> <LayoutSiderContent>
<SideMenu /> <SideMenu />
@@ -12,4 +16,11 @@
@Body @Body
</LayoutContent> </LayoutContent>
</Layout> </Layout>
</Layout> </Layout>
</Authorized>
<NotAuthorized>
@{
NavigationManager.NavigateTo("/login");
}
</NotAuthorized>
</Protected>
@@ -0,0 +1,96 @@
// <auto-generated />
using System;
using Elektrifikatsiya.Database;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
#nullable disable
namespace Elektrifikatsiya.Migrations
{
[DbContext(typeof(MainDatabaseContext))]
[Migration("20230322092207_fix foreign keys")]
partial class fixforeignkeys
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder.HasAnnotation("ProductVersion", "7.0.4");
modelBuilder.Entity("Elektrifikatsiya.Models.Device", b =>
{
b.Property<string>("MacAddress")
.HasColumnType("TEXT");
b.Property<string>("IpAddress")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("Room")
.IsRequired()
.HasColumnType("TEXT");
b.Property<int>("UserId")
.HasColumnType("INTEGER");
b.HasKey("MacAddress");
b.HasIndex("UserId");
b.ToTable("Devices");
});
modelBuilder.Entity("Elektrifikatsiya.Models.User", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<DateTime>("LastLoginDate")
.HasColumnType("TEXT");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("PasswordHash")
.IsRequired()
.HasColumnType("TEXT");
b.Property<int>("Role")
.HasColumnType("INTEGER");
b.Property<string>("SessionToken")
.HasColumnType("TEXT");
b.HasKey("Id");
b.ToTable("Users");
});
modelBuilder.Entity("Elektrifikatsiya.Models.Device", b =>
{
b.HasOne("Elektrifikatsiya.Models.User", "User")
.WithMany("Devices")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("Elektrifikatsiya.Models.User", b =>
{
b.Navigation("Devices");
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,68 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Elektrifikatsiya.Migrations
{
/// <inheritdoc />
public partial class fixforeignkeys : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Users",
columns: table => new
{
Id = table.Column<int>(type: "INTEGER", nullable: false)
.Annotation("Sqlite:Autoincrement", true),
Name = table.Column<string>(type: "TEXT", nullable: false),
PasswordHash = table.Column<string>(type: "TEXT", nullable: false),
Role = table.Column<int>(type: "INTEGER", nullable: false),
SessionToken = table.Column<string>(type: "TEXT", nullable: true),
LastLoginDate = table.Column<DateTime>(type: "TEXT", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Users", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Devices",
columns: table => new
{
MacAddress = table.Column<string>(type: "TEXT", nullable: false),
Name = table.Column<string>(type: "TEXT", nullable: false),
IpAddress = table.Column<string>(type: "TEXT", nullable: false),
UserId = table.Column<int>(type: "INTEGER", nullable: false),
Room = table.Column<string>(type: "TEXT", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Devices", x => x.MacAddress);
table.ForeignKey(
name: "FK_Devices_Users_UserId",
column: x => x.UserId,
principalTable: "Users",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_Devices_UserId",
table: "Devices",
column: "UserId");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Devices");
migrationBuilder.DropTable(
name: "Users");
}
}
}
@@ -0,0 +1,93 @@
// <auto-generated />
using System;
using Elektrifikatsiya.Database;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
#nullable disable
namespace Elektrifikatsiya.Migrations
{
[DbContext(typeof(MainDatabaseContext))]
partial class MainDatabaseContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder.HasAnnotation("ProductVersion", "7.0.4");
modelBuilder.Entity("Elektrifikatsiya.Models.Device", b =>
{
b.Property<string>("MacAddress")
.HasColumnType("TEXT");
b.Property<string>("IpAddress")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("Room")
.IsRequired()
.HasColumnType("TEXT");
b.Property<int>("UserId")
.HasColumnType("INTEGER");
b.HasKey("MacAddress");
b.HasIndex("UserId");
b.ToTable("Devices");
});
modelBuilder.Entity("Elektrifikatsiya.Models.User", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<DateTime>("LastLoginDate")
.HasColumnType("TEXT");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("PasswordHash")
.IsRequired()
.HasColumnType("TEXT");
b.Property<int>("Role")
.HasColumnType("INTEGER");
b.Property<string>("SessionToken")
.HasColumnType("TEXT");
b.HasKey("Id");
b.ToTable("Users");
});
modelBuilder.Entity("Elektrifikatsiya.Models.Device", b =>
{
b.HasOne("Elektrifikatsiya.Models.User", "User")
.WithMany("Devices")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("Elektrifikatsiya.Models.User", b =>
{
b.Navigation("Devices");
});
#pragma warning restore 612, 618
}
}
}
@@ -19,7 +19,7 @@ public class Device
public User User { get; set; } public User User { get; set; }
[NotMapped] [NotMapped]
public int PowerUsage { get; set; } public double PowerUsage { get; set; }
public string Room { get; set; } public string Room { get; set; }
@@ -1,5 +1,4 @@
using System.Text.Json.Serialization; using System.Text.Json.Serialization;
namespace Elektrifikatsiya.Models; namespace Elektrifikatsiya.Models;
public enum Status public enum Status
@@ -24,6 +23,8 @@ public class PrometheusQueryResult
public string? Error { get; set; } public string? Error { get; set; }
public List<string>? Warnings { get; set; } public List<string>? Warnings { get; set; }
public PrometheusDataWrapper? Data { get; set; }
public PrometheusQueryResult(Status status, string? errorType, string? error, List<string>? warnings) public PrometheusQueryResult(Status status, string? errorType, string? error, List<string>? warnings)
{ {
Status = status; Status = status;
@@ -33,7 +34,7 @@ public class PrometheusQueryResult
} }
} }
internal class PrometheusDataWrapper public class PrometheusDataWrapper
{ {
public ResultType ResultType { get; set; } public ResultType ResultType { get; set; }
public List<PrometheusData> Result { get; set; } public List<PrometheusData> Result { get; set; }
@@ -43,9 +44,52 @@ internal class PrometheusDataWrapper
ResultType = resultType; ResultType = resultType;
Result = result; Result = result;
} }
public FluentResults.Result<List<(double, double)>> MatrixTypeToTimestampFloatTuple()
{
if (ResultType != ResultType.Matrix)
{
return FluentResults.Result.Fail("The response did not have the Matrix Type");
}
List<(double, double)> result = new List<(double, double)>();
if (Result[0]?.Value is null)
{
return FluentResults.Result.Fail("There was no result in the Response Body");
}
foreach (PrometheusData prometheusData in Result)
{
string[] segment = prometheusData.Value.ToString()!.Split(",");
result.Add((Convert.ToDouble(segment[0][2..^1]), Convert.ToDouble(segment[1][1..^2])));
}
return result;
}
public FluentResults.Result<(double, double)> VectorTypeToTimestampFloatTuple()
{
if (ResultType != ResultType.Vector)
{
return FluentResults.Result.Fail("The response did not have the Vector Type");
}
string[]? segment = Result.FirstOrDefault()?.Value.ToString()?.Split(",") ?? null;
if (segment is null)
{
return FluentResults.Result.Fail("There was no result in the Response Body");
}
return((Convert.ToDouble(segment[0][2..^1]), Convert.ToDouble(segment[1][1..^2])));
}
} }
internal class PrometheusDataMetric
public class PrometheusDataMetric
{ {
[JsonPropertyName("__name__")] public string Name { get; set; } [JsonPropertyName("__name__")] public string Name { get; set; }
@@ -60,7 +104,7 @@ internal class PrometheusDataMetric
} }
} }
internal class PrometheusData public class PrometheusData
{ {
public PrometheusDataMetric Metric { get; set; } public PrometheusDataMetric Metric { get; set; }
public object Value { get; set; } public object Value { get; set; }
@@ -9,11 +9,20 @@ public class User
[Key] [Key]
public int Id { get; private set; } public int Id { get; private set; }
[Required]
public string Name { get; private set; } public string Name { get; private set; }
[Required]
public string PasswordHash { get; private set; } public string PasswordHash { get; private set; }
[Required]
public Role Role { get; set; }
public string? SessionToken { get; set; } public string? SessionToken { get; set; }
public DateTime LastLoginDate { get; set; } public DateTime LastLoginDate { get; set; }
public Role Role { get; set; }
[Required]
public List<Device> Devices { get; set; } = new();
public User(string name, string passwordHash, Role role) public User(string name, string passwordHash, Role role)
{ {
@@ -2,8 +2,11 @@
@using Blazorise.Components; @using Blazorise.Components;
@using Elektrifikatsiya.Models; @using Elektrifikatsiya.Models;
@using System.Net @using System.Net
@using Elektrifikatsiya.Services
@using Elektrifikatsiya.Utilities
@using System.Diagnostics
@inject IVersionProvider VersionProvider @inject IVersionProvider VersionProvider
@inject IDeviceStatusService DeviceStatusService
<Row Padding="Padding.Is3"> <Row Padding="Padding.Is3">
<Div Display="Display.Flex.Row.OnDesktop" Margin="Margin.Is3.FromBottom" Width="Width.Is100"> <Div Display="Display.Flex.Row.OnDesktop" Margin="Margin.Is3.FromBottom" Width="Width.Is100">
<Column ColumnSize="ColumnSize.Is6.OnDesktop.Is12"> <Column ColumnSize="ColumnSize.Is6.OnDesktop.Is12">
@@ -91,10 +94,20 @@
//TODO: insert new event here if plug produces one //TODO: insert new event here if plug produces one
List<Event> events = new List<Event>() { new Event("Placeholder", "Placeholder", DateTime.Now), new Event("Placeholder", "Placeholder", DateTime.Now), new Event("Placeholder", "Placeholder", DateTime.Now) }; List<Event> events = new List<Event>() { new Event("Placeholder", "Placeholder", DateTime.Now), new Event("Placeholder", "Placeholder", DateTime.Now), new Event("Placeholder", "Placeholder", DateTime.Now) };
//TODO: insert new Device here if user adds one //TODO: insert new Device here if user adds one
List<Device> plugs = new List<Device>() { new Device("ffff:ffff:ffff:ffff", "Josne", IPAddress.Broadcast, new User("Joe", "qiowruioewjfopa", Role.Admin), "Raum"), new Device("ffff:ffff:ffff:ffff", "Josne", IPAddress.Broadcast, new User("Joe", "Josne", Role.Admin), "Raum"), new Device("ffff:ffff:ffff:ffff", "Josne", IPAddress.Broadcast, new User("Joe", "qiowruioewjfopa", Role.Admin), "Raum"), }; List<Device> plugs = new List<Device>();
//code for graph //code for graph
LineChart<double> lineChart; LineChart<double> lineChart;
protected override void OnInitialized()
{
plugs = DeviceStatusService.GetDevices().ValueOrDefault ?? new List<Device>();
DeviceStatusService.OnDeviceStatusChanged += (_, e) =>
{
InvokeAsync(StateHasChanged);
};
}
protected override async Task OnAfterRenderAsync(bool firstRender) protected override async Task OnAfterRenderAsync(bool firstRender)
{ {
if (firstRender) if (firstRender)
@@ -105,18 +118,19 @@
async Task HandleRedraw() async Task HandleRedraw()
{ {
await lineChart.Clear(); await lineChart.Clear();
await lineChart.AddLabelsDatasetsAndUpdate(Labels, GetLineChartDataset()); await lineChart.AddLabelsDatasetsAndUpdate(Labels, await GetLineChartDataset());
} }
//TODO: insert dataset of current and last voltage usages //TODO: insert dataset of current and last voltage usages
LineChartDataset<double> GetLineChartDataset() async Task<LineChartDataset<double>> GetLineChartDataset()
{ {
return new LineChartDataset<double> return new LineChartDataset<double>
{ {
Label = "# of random number in thousands", Label = "# of random number in thousands",
Data = RandomizeData(), Data = await RandomizeData(),
BackgroundColor = backgroundColors, BackgroundColor = backgroundColors,
BorderColor = borderColors, BorderColor = borderColors,
Fill = true, Fill = true,
@@ -129,17 +143,25 @@
List<string> backgroundColors = new List<string> { ChartColor.FromRgba(255, 99, 132, 0.2f), ChartColor.FromRgba(54, 162, 235, 0.2f), ChartColor.FromRgba(255, 206, 86, 0.2f), ChartColor.FromRgba(75, 192, 192, 0.2f), ChartColor.FromRgba(153, 102, 255, 0.2f), ChartColor.FromRgba(255, 159, 64, 0.2f) }; List<string> backgroundColors = new List<string> { ChartColor.FromRgba(255, 99, 132, 0.2f), ChartColor.FromRgba(54, 162, 235, 0.2f), ChartColor.FromRgba(255, 206, 86, 0.2f), ChartColor.FromRgba(75, 192, 192, 0.2f), ChartColor.FromRgba(153, 102, 255, 0.2f), ChartColor.FromRgba(255, 159, 64, 0.2f) };
List<string> borderColors = new List<string> { ChartColor.FromRgba(255, 99, 132, 1f), ChartColor.FromRgba(54, 162, 235, 1f), ChartColor.FromRgba(255, 206, 86, 1f), ChartColor.FromRgba(75, 192, 192, 1f), ChartColor.FromRgba(153, 102, 255, 1f), ChartColor.FromRgba(255, 159, 64, 1f) }; List<string> borderColors = new List<string> { ChartColor.FromRgba(255, 99, 132, 1f), ChartColor.FromRgba(54, 162, 235, 1f), ChartColor.FromRgba(255, 206, 86, 1f), ChartColor.FromRgba(75, 192, 192, 1f), ChartColor.FromRgba(153, 102, 255, 1f), ChartColor.FromRgba(255, 159, 64, 1f) };
List<double> RandomizeData() async Task<List<double>> RandomizeData()
{ {
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];
Debug.WriteLine($$"""sum(power{sensor=~"{{plugnames}}"})[1h:1m]""");
PrometheusDataWrapper? deviceData = (await promQueryer.Query($$"""sum(power{sensor=~"{{plugnames}}"})[1h:1m]"""))?.Data;
var r = new Random(DateTime.Now.Millisecond); var r = new Random(DateTime.Now.Millisecond);
return new List<double> { return deviceData?.MatrixTypeToTimestampFloatTuple().ValueOrDefault?.Select(x => x.Item2).ToList() ?? new List<double>();
r.Next( 3, 50 ) * r.NextDouble(),
r.Next( 3, 50 ) * r.NextDouble(),
r.Next( 3, 50 ) * r.NextDouble(),
r.Next( 3, 50 ) * r.NextDouble(),
r.Next( 3, 50 ) * r.NextDouble(),
r.Next( 3, 50 ) * r.NextDouble() };
} }
}
}
}
@@ -4,6 +4,7 @@ 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;
@@ -51,7 +52,16 @@ app.MapFallbackToPage("/_Host");
app.MapControllers(); app.MapControllers();
IServiceScope serviceScope = app.Services.GetRequiredService<IServiceScopeFactory>().CreateScope(); IServiceScope serviceScope = app.Services.GetRequiredService<IServiceScopeFactory>().CreateScope();
serviceScope.ServiceProvider.GetRequiredService<MainDatabaseContext>().Database.EnsureCreated();
MainDatabaseContext mainDatabase = serviceScope.ServiceProvider.GetRequiredService<MainDatabaseContext>();
mainDatabase.Database.EnsureCreated();
IAuthenticationService authenticationService = serviceScope.ServiceProvider.GetRequiredService<IAuthenticationService>();
if (!mainDatabase.Users.Any())
{
authenticationService.RegisterUserAsync("admin", "admin", Role.Admin);
}
app.Run(); app.Run();
@@ -7,7 +7,7 @@
"ASPNETCORE_ENVIRONMENT": "Development" "ASPNETCORE_ENVIRONMENT": "Development"
}, },
"dotnetRunMessages": true, "dotnetRunMessages": true,
"applicationUrl": "https://localhost:56656;http://localhost:5255" "applicationUrl": "https://localhost:56656;http://localhost:55552"
}, },
"IIS Express": { "IIS Express": {
"commandName": "IISExpress", "commandName": "IISExpress",
@@ -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 mainDatabaseContext.Users.FirstOrDefaultAsync(u => u.Name.Equals(name, StringComparison.InvariantCultureIgnoreCase)); User? user = await mainDatabaseContext.Users.FirstOrDefaultAsync(u => u.Name == name);
if (user is null) if (user is null)
{ {
@@ -129,6 +129,6 @@ public class AuthenticationService : IAuthenticationService
public Task<Result<bool>> UserExistsAsync(string name) public Task<Result<bool>> UserExistsAsync(string name)
{ {
return Result.Try(() => return Result.Try(() =>
mainDatabaseContext.Users.AnyAsync(u => u.Name.Equals(name, StringComparison.InvariantCultureIgnoreCase))); mainDatabaseContext.Users.AnyAsync(u => u.Name == name));
} }
} }
@@ -5,6 +5,7 @@ using FluentResults;
using System.Net; using System.Net;
using System.Net.NetworkInformation; using System.Net.NetworkInformation;
using Microsoft.EntityFrameworkCore;
namespace Elektrifikatsiya.Services.Implementations; namespace Elektrifikatsiya.Services.Implementations;
@@ -108,6 +109,8 @@ public class DeviceManagmentService : IDeviceManagmentService
Device device = new Device(mac, name ?? mac, ip, user, room); Device device = new Device(mac, name ?? mac, ip, user, room);
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());
@@ -1,6 +1,6 @@
using Elektrifikatsiya.Database; using Elektrifikatsiya.Database;
using Elektrifikatsiya.Models; using Elektrifikatsiya.Models;
using Elektrifikatsiya.Utilities;
using FluentResults; using FluentResults;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
@@ -28,7 +28,7 @@ public class UpdateService : IHostedService, IDisposable
logger.LogInformation("Starting update service..."); logger.LogInformation("Starting update service...");
foreach (Device device in await mainDatabaseContext.Devices.AsNoTracking().ToListAsync(cancellationToken)) foreach (Device device in await mainDatabaseContext.Devices.Include(d=>d.User).AsNoTracking().ToListAsync(cancellationToken))
{ {
_ = deviceStatusService.TrackDevice(device); _ = deviceStatusService.TrackDevice(device);
} }
@@ -38,7 +38,7 @@ public class UpdateService : IHostedService, IDisposable
logger.LogInformation("Update service started."); logger.LogInformation("Update service started.");
} }
private void Update() private async void Update()
{ {
Result<List<Device>> getDeviceStatusResult = deviceStatusService.GetDevices(); Result<List<Device>> getDeviceStatusResult = deviceStatusService.GetDevices();
@@ -46,10 +46,16 @@ public class UpdateService : IHostedService, IDisposable
{ {
logger.LogError("Updating devices failed!"); logger.LogError("Updating devices failed!");
} }
PrometheusQuery promQueryer = new PrometheusQuery("http://localhost:9090");
foreach (Device device in getDeviceStatusResult.Value) foreach (Device device in getDeviceStatusResult.Value)
{ {
//TODO: Some update magic PrometheusDataWrapper? deviceData = (await promQueryer.Query($"power{{sensor=\"shellyplug-s-{device.MacAddress}/relay/0\"}}"))?.Data;
if (deviceData is not null)
{
device.PowerUsage = deviceData.VectorTypeToTimestampFloatTuple()?.ValueOrDefault.Item2 ?? 0;
deviceStatusService.UpdateDeviceStatus(device);
}
} }
} }
@@ -2,6 +2,7 @@
using System.Net.Sockets; using System.Net.Sockets;
using System.Text.Encodings.Web; using System.Text.Encodings.Web;
using System.Text.Json; using System.Text.Json;
using System.Text.Json.Serialization;
using Elektrifikatsiya.Models; using Elektrifikatsiya.Models;
using FluentResults; using FluentResults;
@@ -20,6 +21,14 @@ public class PrometheusQuery
public Task<PrometheusQueryResult?> Query(string query) public Task<PrometheusQueryResult?> Query(string query)
{ {
return client.GetFromJsonAsync<PrometheusQueryResult>($"/v1/query?{UrlEncoder.Create().Encode(query)}"); var res = client.GetStringAsync($"/api/v1/query?query={UrlEncoder.Create().Encode(query)}").Result;
return client.GetFromJsonAsync<PrometheusQueryResult>($"/api/v1/query?query={UrlEncoder.Create().Encode(query)}", new JsonSerializerOptions()
{
PropertyNameCaseInsensitive = true,
Converters =
{
new JsonStringEnumConverter()
}
});
} }
} }
+9 -4
View File
@@ -1,10 +1,15 @@
version: '3.4' version: '3.4'
services: services:
elektrifikatsiya: #elektrifikatsiya:
build: # build:
context: . # context: .
dockerfile: Elektrifikatsiya/Dockerfile # dockerfile: Elektrifikatsiya/Dockerfile
# ports:
# - target: 5353
# published: 5353
# protocol: udp
# mode: host
prometheus: prometheus:
image: prom/prometheus:latest image: prom/prometheus:latest
volumes: volumes: