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

This commit is contained in:
Aldin296
2023-05-10 08:49:36 +02:00
38 changed files with 1246 additions and 722 deletions
+3
View File
@@ -348,3 +348,6 @@ MigrationBackup/
# Ionide (cross platform F# VS Code tools) working folder # Ionide (cross platform F# VS Code tools) working folder
.ionide/ .ionide/
# Project specific
*.sqlite*
@@ -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;
}
}
@@ -1,74 +0,0 @@
using Blazorise;
using Elektrifikatsiya.Components.TodoApp;
using Microsoft.AspNetCore.Components;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Elektrifikatsiya.Components.TodoApp;
public abstract class BaseTodoItems : ComponentBase
{
protected Validations validations;
protected string description;
protected Filter filter = Filter.All;
protected List<Todo> todos = new()
{
new() { Description = "Buy milk" },
new() { Description = "Call John regarding the meeting" },
new() { Description = "Walk a dog" },
};
protected IEnumerable<Todo> Todos
{
get
{
var query = from t in todos select t;
if (filter == Filter.Active)
query = from q in query where !q.Completed select q;
if (filter == Filter.Completed)
query = from q in query where q.Completed select q;
return query;
}
}
protected void SetFilter(Filter filter)
{
this.filter = filter;
}
protected void OnCheckAll(bool isChecked)
{
todos.ForEach(x => x.Completed = isChecked);
}
protected async Task OnAddTodo()
{
if (await validations.ValidateAll())
{
todos.Add(new() { Description = description });
description = null;
await validations.ClearAll();
}
}
protected void OnClearCompleted()
{
todos.RemoveAll(x => x.Completed);
filter = Filter.All;
}
protected Task OnTodoStatusChanged(bool isChecked)
{
return InvokeAsync(StateHasChanged);
}
}
@@ -1,8 +0,0 @@
namespace Elektrifikatsiya.Components.TodoApp;
public enum Filter
{
All,
Active,
Completed,
}
@@ -1,8 +0,0 @@
namespace Elektrifikatsiya.Components.TodoApp;
public class Todo
{
public bool Completed { get; set; }
public string Description { get; set; }
}
@@ -1,22 +0,0 @@
<ListGroupItem>
<Field Horizontal Padding="Padding.IsAuto.OnAll">
<FieldBody ColumnSize="ColumnSize.Is1">
<Check TValue="bool" Checked="@Todo.Completed" CheckedChanged="@OnCheckedChanged"></Check>
</FieldBody>
<FieldBody ColumnSize="ColumnSize.Is11">
@Todo.Description
</FieldBody>
</Field>
</ListGroupItem>
@code{
Task OnCheckedChanged( bool isChecked )
{
Todo.Completed = isChecked;
return StatusChanged?.Invoke( isChecked );
}
[Parameter] public Todo Todo { get; set; }
[Parameter] public Func<bool, Task> StatusChanged { get; set; }
}
@@ -1,57 +0,0 @@
@inherits BaseTodoItems
<Container Fluid>
<Row>
<Column>
<Card>
<CardHeader Padding="Padding.Is1.FromBottom">
<CardTitle Size="4">Todo List</CardTitle>
</CardHeader>
<CardBody Padding="Padding.Is0.FromBottom">
<Fields>
<Column ColumnSize="ColumnSize.Is1">
<Check TValue="bool" Checked="@Todos.All(x=>x.Completed)" CheckedChanged="@OnCheckAll">All</Check>
</Column>
<Column ColumnSize="ColumnSize.Is11">
<Addons>
<Addon AddonType="AddonType.Body">
<Validations @ref="validations" Mode="ValidationMode.Manual">
<Validation Validator="@ValidationRule.IsNotEmpty">
<TextEdit @bind-Text="@description" Placeholder="What needs to be done?"></TextEdit>
</Validation>
</Validations>
</Addon>
<Addon AddonType="AddonType.End">
<Button Color="Color.Primary" Clicked="@OnAddTodo">
<Icon Name="IconName.Add" />Add
</Button>
</Addon>
</Addons>
</Column>
</Fields>
</CardBody>
<CardBody Padding="Padding.Is0.OnY">
<ListGroup Flush>
@foreach ( var todo in Todos )
{
<TodoItem Todo="@todo" StatusChanged="@OnTodoStatusChanged" />
}
</ListGroup>
</CardBody>
<CardFooter Padding="Padding.Is3.FromBottom">
<Field Horizontal>
<FieldBody ColumnSize="ColumnSize.Is10">
<Buttons Role="ButtonsRole.Addons">
<Button Color="Color.Info" Clicked="@(() => SetFilter( Filter.All ))" Active="@(filter == Filter.All)">All</Button>
<Button Color="Color.Info" Clicked="@(() => SetFilter( Filter.Active ))" Active="@(filter == Filter.Active)">Active</Button>
<Button Color="Color.Info" Clicked="@(() => SetFilter( Filter.Completed ))" Active="@(filter == Filter.Completed)">Completed</Button>
</Buttons>
</FieldBody>
<FieldBody ColumnSize="ColumnSize.Is2">
<Button Color="Color.Warning" Float="Float.End" Clicked="@OnClearCompleted" Display="@(todos.Any(x=>x.Completed) ? Display.Always : Display.None)">Clear Completed</Button>
</FieldBody>
</Field>
</CardFooter>
</Card>
</Column>
</Row>
</Container>
@@ -1,14 +0,0 @@
using Elektrifikatsiya.Models;
using Microsoft.EntityFrameworkCore;
namespace Elektrifikatsiya.Database
{
public class DeviceManagmentDatabaseContext : DbContext
{
public DbSet<Device> Devices { get; set; }
public DeviceManagmentDatabaseContext(DbContextOptions<DeviceManagmentDatabaseContext> options) : base(options)
{
}
}
}
@@ -4,11 +4,13 @@ using Microsoft.EntityFrameworkCore;
namespace Elektrifikatsiya.Database; namespace Elektrifikatsiya.Database;
public class UserDatabaseContext : DbContext public class MainDatabaseContext : DbContext
{ {
public UserDatabaseContext(DbContextOptions<UserDatabaseContext> dbContextOptions) : base(dbContextOptions) public MainDatabaseContext(DbContextOptions<MainDatabaseContext> dbContextOptions) : base(dbContextOptions)
{ {
} }
public DbSet<User> Users { get; set; } public DbSet<User> Users { get; set; }
public DbSet<Device> Devices { get; set; }
public DbSet<Event> Events { get; set; }
} }
@@ -41,10 +41,15 @@
<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="HiveMQtt" Version="0.1.10" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="7.0.2" /> <PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.4" />
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.17.0" /> <PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="7.0.4" />
<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,17 +1,42 @@
@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">
<Column ColumnSize="ColumnSize.Is6.OnDesktop.Is12.Is3.WithOffset"> <Column ColumnSize="ColumnSize.Is6.OnDesktop.Is12.Is3.WithOffset">
<Field Position="Position.Relative.Top.Is50.Start.Is50.Translate.Middle"> <Field Position="Position.Relative.Top.Is50.Start.Is50.Translate.Middle">
<TextEdit Placeholder="Username" /> <TextEdit @bind-Text="username" Placeholder="Username" />
</Field> </Field>
<Field Position="Position.Relative.Top.Is50.Start.Is50.Translate.Middle"> <Field 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 Color="Color.Primary" 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>
</Column> </Column>
</Card> </Card>
@code { @code {
private string username = string.Empty;
private string password = string.Empty;
private Color color = Color.Primary;
private bool disabled;
private async Task 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;
}
}
} }
@@ -1,15 +1,26 @@
@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">
<LayoutSider> <Authorized>
<LayoutSiderContent> <Layout Sider>
<SideMenu /> <LayoutSider>
</LayoutSiderContent> <LayoutSiderContent>
</LayoutSider> <SideMenu />
<Layout> </LayoutSiderContent>
<LayoutContent Padding="Padding.Is4.OnDesktop.Is0"> </LayoutSider>
@Body <Layout>
</LayoutContent> <LayoutContent Padding="Padding.Is4.OnDesktop.Is0">
</Layout> @Body
</Layout> </LayoutContent>
</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,12 +19,12 @@ 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; }
[NotMapped] [NotMapped]
public bool Available { get; set; } public bool Enabled { get; set; }
public Device(string macAddress, string name, IPAddress address, User user, string room) public Device(string macAddress, string name, IPAddress address, User user, string room)
{ {
@@ -35,5 +35,22 @@ public class Device
Room = room; Room = room;
} }
private Device(){} public Device CopyDevice()
{
return new Device(MacAddress, Name, IpAddress, User, Room);
}
public void OverwiteDevice(Device overwriter)
{
Room = overwriter.Room;
Enabled = overwriter.Enabled;
PowerUsage = overwriter.PowerUsage;
Name = overwriter.Name;
User = overwriter.User;
MacAddress = overwriter.MacAddress;
IpAddress = overwriter.IpAddress;
}
private Device()
{ }
} }
@@ -1,7 +1,13 @@
namespace Elektrifikatsiya.Models using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
namespace Elektrifikatsiya.Models
{ {
public class Event public class Event
{ {
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
public int Id { get; private set; }
public string EventName { get; set; } public string EventName { get; set; }
public string Description { get; set; } public string Description { get; set; }
public DateTime Date { get; set; } public DateTime Date { get; set; }
@@ -1,4 +1,6 @@
using System.Text.Json.Serialization; using System.Diagnostics;
using System.Globalization;
using System.Text.Json.Serialization;
namespace Elektrifikatsiya.Models; namespace Elektrifikatsiya.Models;
@@ -24,6 +26,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 +37,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 +47,51 @@ 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.Count == 0 || Result[0]?.Values is null || Result[0]?.Values?[0] is null)
{
return FluentResults.Result.Fail("There was no result in the Response Body");
}
foreach (object value in Result[0]!.Values!)
{
string[] segment = value.ToString()!.Split(",");
result.Add((Convert.ToDouble(segment[0][2..^1], CultureInfo.InvariantCulture), Convert.ToDouble(segment[1][1..^2], CultureInfo.InvariantCulture)));
}
Debug.WriteLine(result);
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(",");
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], CultureInfo.InvariantCulture));
}
} }
internal class PrometheusDataMetric public class PrometheusDataMetric
{ {
[JsonPropertyName("__name__")] public string Name { get; set; } [JsonPropertyName("__name__")] public string Name { get; set; }
@@ -60,14 +106,9 @@ internal class PrometheusDataMetric
} }
} }
internal class PrometheusData public class PrometheusData
{ {
public PrometheusDataMetric Metric { get; set; } public PrometheusDataMetric? Metric { get; set; } = null;
public object Value { get; set; } public object? Value { get; set; } = null;
public List<object>? Values { get; set; } = null;
public PrometheusData(PrometheusDataMetric metric, object value)
{
Metric = metric;
Value = value;
}
} }
@@ -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)
{ {
@@ -5,123 +5,164 @@
@using Elektrifikatsiya.Services @using Elektrifikatsiya.Services
@using Elektrifikatsiya.Services.Implementations @using Elektrifikatsiya.Services.Implementations
@using Elektrifikatsiya.Utilities @using Elektrifikatsiya.Utilities
@using FluentResults;
@using Blazorise.LoadingIndicator;
@inject IVersionProvider VersionProvider @inject IVersionProvider VersionProvider
@inject IDeviceManagmentService DeviceManagmentService @inject IDeviceManagmentService DeviceManagmentService
@inject IAuthenticationService AuthenticationService @inject IAuthenticationService AuthenticationService
@inject IMessageService MessageService
<Row Style="height:50%; width:100%" Padding="Padding.Is3.OnDesktop.Is5.FromStart.OnMobile"> <Row Style="height:50%; width:100%" Padding="Padding.Is3.OnDesktop.Is5.FromStart.OnMobile">
<Row Style="height:90%; width:100%"> <Row Style="height:90%; width:100%">
<Column ColumnSize="ColumnSize.Is4.OnDesktop.Is1"></Column> <Column ColumnSize="ColumnSize.Is4.OnDesktop.Is1"></Column>
<Column ColumnSize="ColumnSize.Is4.OnDesktop.Is12"> <Column ColumnSize="ColumnSize.Is4.OnDesktop.Is12">
<Bar Breakpoint="Breakpoint.Desktop" <Bar Breakpoint="Breakpoint.Desktop"
Background="Background.White" Background="Background.White"
ThemeContrast="ThemeContrast.None" ThemeContrast="ThemeContrast.None"
Shadow="Shadow.Remove" Shadow="Shadow.Remove"
Border="Border.Is1.RoundedTop"> Border="Border.Is1.RoundedTop">
<BarBrand> <BarBrand>
<Column ColumnSize="ColumnSize.Is9"> <Column ColumnSize="ColumnSize.Is9">
Add a plug via wifi Add a plug via wifi
</Column> </Column>
<Column ColumnSize="ColumnSize.Is3.Is6.WithOffset"> <Column ColumnSize="ColumnSize.Is3.Is6.WithOffset">
<LoadingIndicator @bind-Visible="@visible"> <LoadingIndicator @bind-Visible="@visible" />
</LoadingIndicator>
</Column> </Column>
</BarBrand> </BarBrand>
</Bar> </Bar>
<ListView Class="w-100" <ListView Class="w-100"
TItem="IPAddress" TItem="IPAddress"
Data="@ipAddresses" Data="@ipAddresses"
TextField="@((_)=>(""))" TextField="@((_)=>(""))"
ValueField="@((_)=>(""))" ValueField="@((_)=>(""))"
Mode="ListGroupMode.Static" Mode="ListGroupMode.Static"
Style="border-radius: 0px 0px"> Style="border-radius: 0px 0px">
<ItemTemplate> <ItemTemplate>
<ListGroupItem> <ListGroupItem>
<Row> <Row>
<Column ColumnSize="ColumnSize.Is8"> <Column ColumnSize="ColumnSize.Is8">
<Row> <Row>
</Row> </Row>
<Row Width="Width.Is100"> <Row Width="Width.Is100">
<Column> <Column>
<Small>IP: @context.Item</Small> <Small>IP: @context.Item</Small>
</Column> </Column>
</Row> </Row>
</Column> </Column>
<Column ColumnSize="ColumnSize.Is4"> <Column ColumnSize="ColumnSize.Is4">
<Button Position="Position.Absolute.Top.Is50.Start.Is50.Translate.Middle" Color="Color.Dark" Clicked="@(async () => await DeviceManagmentService.RegisterDevice(context.Item,(await AuthenticationService.GetUserAsync()).ValueOrDefault))" Outline> <Button Disabled="disabled" Position="Position.Absolute.Top.Is50.Start.Is50.Translate.Middle" Color="Color.Dark" Clicked="@(async () => await RegisterDevice(context.Item))" Outline>
<BarIcon IconName="IconName.Add" /> <BarIcon IconName="IconName.Add" />
</Button> </Button>
</Column> </Column>
</Row> </Row>
</ListGroupItem> </ListGroupItem>
</ItemTemplate> </ItemTemplate>
</ListView> </ListView>
</Column> </Column>
</Row> </Row>
</Row> </Row>
<Row Style="height:50%; width:100%; border-top-style:solid; border-top-color:#1a237e" Padding="Padding.Is3.OnDesktop.Is5.FromStart.OnMobile"> <Row Style="height:50%; width:100%; border-top-style:solid; border-top-color:#1a237e" Padding="Padding.Is3.OnDesktop.Is5.FromStart.OnMobile">
<Column ColumnSize="ColumnSize.Is4.OnDesktop.Is1"></Column> <Column ColumnSize="ColumnSize.Is4.OnDesktop.Is1"></Column>
<Column ColumnSize="ColumnSize.Is4.OnDesktop.Is12"> <Column ColumnSize="ColumnSize.Is4.OnDesktop.Is12">
<Row Style="height:15%; width:100%"></Row> <Row Style="height:15%; width:100%"></Row>
<Row Style="height:10%; width:100%"> <Row Style="height:10%; width:100%">
<Bar Breakpoint="Breakpoint.Desktop" <Bar Breakpoint="Breakpoint.Desktop"
Background="Background.White" Background="Background.White"
ThemeContrast="ThemeContrast.None" ThemeContrast="ThemeContrast.None"
Shadow="Shadow.Remove" Shadow="Shadow.Remove"
Border="Border.Is1.RoundedTop" Border="Border.Is1.RoundedTop"
Style="width:100%"> Style="width:100%">
<BarBrand> <BarBrand>
Add a plug via IP Add a plug via IP
</BarBrand> </BarBrand>
</Bar> </Bar>
<ListGroup Style="width:100%; border-radius: 0px 0px"> <ListGroup Style="width:100%; border-radius: 0px 0px">
<ListGroupItem Color="Color.Default"> <ListGroupItem Color="Color.Default">
<Form> <Form>
<Field Horizontal> <Validation @ref="ipValidation" Validator="ValidateIPv4">
<FieldBody ColumnSize="ColumnSize.Is12"> <Field Horizontal>
<TextEdit Placeholder="Enter the Device IP here" /> <FieldBody ColumnSize="ColumnSize.Is12">
<br> <TextEdit @bind-Text="ipText" Placeholder="Enter the Device IP here">
<Button style="background-color:#1a237e; color:white" Type="ButtonType.Submit" PreventDefaultOnSubmit>CONNECT</Button> <Feedback>
</FieldBody> <ValidationNone>Please enter a ip address.</ValidationNone>
</Field> <ValidationSuccess>Ip address is valid.</ValidationSuccess>
</Form> <ValidationError>Ip address is not valid!</ValidationError>
</ListGroupItem> </Feedback>
</ListGroup> </TextEdit>
</Row> <br>
<Row Style="height:75%; width:100%"></Row> <Button style="background-color:#1a237e; color:white" Type="ButtonType.Submit" Disabled="ipValidation?.Status != ValidationStatus.Success || disabled" Clicked="@(async (_)=> await RegisterDevice(IPAddress.Parse(ipText!)))" PreventDefaultOnSubmit>CONNECT</Button>
</Column> </FieldBody>
</Field>
</Validation>
</Form>
</ListGroupItem>
</ListGroup>
</Row>
<Row Style="height:75%; width:100%"></Row>
</Column>
</Row> </Row>
@code { @code {
List<IPAddress> ipAddresses = new List<IPAddress>(); List<IPAddress> ipAddresses = new List<IPAddress>();
bool visible = false; Validation? ipValidation;
DateTime time = DateTime.UtcNow; bool visible = true;
bool disabled = false;
protected override void OnInitialized() string ipText = null!;
{
ipAddresses.AddRange(MdnsDiscovery.GetChachedDevices());
System.Timers.Timer aTimer = new System.Timers.Timer(1000); protected override void OnInitialized()
aTimer.Elapsed += (_, _) => { {
DateTime dateTime = DateTime.UtcNow; MdnsDiscovery.OnDeviceFound += async ipAddress =>
if(dateTime >= time.AddSeconds(3)) {
{ visible = false;
visible = false; if (!ipAddresses.Contains(ipAddress))
InvokeAsync(StateHasChanged); {
} ipAddresses.Add(ipAddress);
}; await InvokeAsync(StateHasChanged);
aTimer.Start(); }
};
MdnsDiscovery.OnDeviceFound += address => MdnsDiscovery.FetchChachedDevices();
{ }
visible = true;
ipAddresses.Add(address); private async Task RegisterDevice(IPAddress ipAddress)
InvokeAsync(StateHasChanged); {
disabled = true;
Result<Device> result = await DeviceManagmentService.RegisterDevice(ipAddress, (await AuthenticationService.GetUserAsync()).ValueOrDefault);
if (result.IsSuccess)
{
await MessageService.Success("Device added!");
}
else
{
await MessageService.Error(string.Join(',', result.Errors.Select(e => e.Message)), "Adding device failed!");
}
disabled = false;
}
public void ValidateIPv4(ValidatorEventArgs e)
{
string? input = Convert.ToString(e.Value);
if (string.IsNullOrWhiteSpace(input))
{
e.Status = ValidationStatus.None;
return;
}
string[] splitValues = input.Split('.');
if (splitValues.Length != 4)
{
e.Status = ValidationStatus.Error;
return;
}
e.Status = splitValues.All(r => byte.TryParse(r, out _)) ? ValidationStatus.Success : ValidationStatus.Error;
}
time = DateTime.UtcNow;
};
}
} }
@@ -2,156 +2,95 @@
@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
@using Elektrifikatsiya.Services.Implementations
@inject IVersionProvider VersionProvider @inject IVersionProvider VersionProvider
@inject IDeviceStatusService DeviceStatusService;
@inject IDeviceManagmentService DeviceManagmentService;
<Div> <Div>
<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">
<Bar Breakpoint="Breakpoint.Desktop" <Bar Breakpoint="Breakpoint.Desktop"
Background="Background.White" Background="Background.White"
ThemeContrast="ThemeContrast.None" ThemeContrast="ThemeContrast.None"
Shadow="Shadow.Remove" Shadow="Shadow.Remove"
Border="Border.Is1.RoundedTop"> Border="Border.Is1.RoundedTop">
<BarBrand> <BarBrand>
Plugs Plugs
</BarBrand> </BarBrand>
</Bar> </Bar>
<ListView TItem="Device" <ListView TItem="Device"
Data="@plugs" Data="@plugs"
TextField="@((_)=>(""))" TextField="@((_)=>(""))"
ValueField="@((_)=>(""))" ValueField="@((_)=>(""))"
Mode="ListGroupMode.Static" Mode="ListGroupMode.Static"
Style="border-radius: 0px 0px"> Style="border-radius: 0px 0px">
<ItemTemplate > <ItemTemplate>
<ListGroupItem> <ListGroupItem>
<Row> <Row>
<Column ColumnSize="ColumnSize.Is8"> <Column ColumnSize="ColumnSize.Is8">
<Row> <Row>
<Column ColumnSize="ColumnSize.Is7"> <Column ColumnSize="ColumnSize.Is7">
<Heading Size="HeadingSize.Is6" Margin="Margin.Is1.FromBottom">@context.Item.Name</Heading> <Heading Size="HeadingSize.Is6" Margin="Margin.Is1.FromBottom">@context.Item.Name</Heading>
</Column> </Column>
</Row> </Row>
<Row> <Row>
<Column> <Column>
<Small>User: @context.Item.User</Small> <Small>User: @context.Item.User.Name</Small>
<br /> <br />
<Small>Room: @context.Item.Room</Small> <Small>Room: @context.Item.Room</Small>
</Column> </Column>
<Column ColumnSize="ColumnSize.Is5"> <Column ColumnSize="ColumnSize.Is5">
<Paragraph Margin="Margin.Is1.OnY">@context.Item.PowerUsage W</Paragraph> <Paragraph Margin="Margin.Is1.OnY">@context.Item.PowerUsage W</Paragraph>
</Column> </Column>
</Row> </Row>
</Column> </Column>
<Column ColumnSize="ColumnSize.Is4"> <Column ColumnSize="ColumnSize.Is4">
<Button Clicked="@ChangeButtonColor" Position="Position.Absolute.Top.Is50.Start.Is50.Translate.Middle" Color="Color.Primary"Primary Outline> <Button Clicked="() => Switch(context.Item)" Position="Position.Absolute.Top.Is50.Start.Is50.Translate.Middle" Color="Color.Primary" Primary Outline>
<!--TODO: This button should change color--> <BarIcon TextColor="(context.Item.Enabled?TextColor.Success:TextColor.Danger)" IconName="IconName.Bolt" />
<BarIcon IconName="IconName.Bolt" /> </Button>
</Button> </Column>
</Column> </Row>
</Row> </ListGroupItem>
</ListGroupItem> </ItemTemplate>
</ItemTemplate> </ListView>
</ListView> </Column>
</Column> <Column ColumnSize="ColumnSize.Is6.OnDesktop.Is12">
<Column ColumnSize="ColumnSize.Is6.OnDesktop.Is12"> <Bar Breakpoint="Breakpoint.Desktop"
<Bar Breakpoint="Breakpoint.Desktop" Background="Background.White"
Background="Background.White" ThemeContrast="ThemeContrast.None"
ThemeContrast="ThemeContrast.None" Shadow="Shadow.Remove"
Shadow="Shadow.Remove" Border="Border.Is1.Rounded.RoundedTop">
Border="Border.Is1.Rounded.RoundedTop"> <BarBrand>
<BarBrand> Logs
Logs </BarBrand>
</BarBrand> </Bar>
</Bar> <ListView TItem="Event"
<ListView TItem="Event" Data="@events"
Data="@events" TextField="@((_)=>(""))"
TextField="@((_)=>(""))" ValueField="@((_)=>(""))"
ValueField="@((_)=>(""))" Mode="ListGroupMode.Static"
Mode="ListGroupMode.Static" Style="border-radius: 0px 0px">
Style="border-radius: 0px 0px"> <ItemTemplate>
<ItemTemplate> <Div Flex="Flex.InlineFlex.JustifyContent.Between" Width="Width.Is100">
<Div Flex="Flex.InlineFlex.JustifyContent.Between" Width="Width.Is100"> <Heading Size="HeadingSize.Is6" Margin="Margin.Is2.FromBottom">@context.Item.EventName</Heading>
<Heading Size="HeadingSize.Is6" Margin="Margin.Is2.FromBottom">@context.Item.EventName</Heading> <Small>@context.Item.Date</Small>
<Small>@context.Item.Date</Small> </Div>
</Div> <Paragraph Margin="Margin.Is2.FromBottom">@context.Item.Description</Paragraph>
<Paragraph Margin="Margin.Is2.FromBottom">@context.Item.Description</Paragraph> </ItemTemplate>
</ItemTemplate> </ListView>
</ListView> </Column>
</Column> </Div>
</Div> </Row>
</Row> <Row Padding="Padding.Is3">
<Row Padding="Padding.Is3"> <Column>
<Column> <Button Color="Color.Primary" Style="border-radius: 0px" Clicked="@(async () => await HandleRedraw())">Aktualisieren</Button>
<Button Color="Color.Primary" Style="border-radius: 0px" Clicked="@(async () => await HandleRedraw())">Aktualisieren</Button> <LineChart Height="Height.Is100" Width="Width.Is100" @ref="lineChart" TItem="double" />
<LineChart Height="Height.Is100" Width="Width.Is100" @ref="lineChart" TItem="double" /> </Column>
</Column> </Row>
</Row>
</Div> </Div>
@code {
//TODO: insert new event here if plug produces one
List<Event> events = new List<Event>() { new Event("Placeholder", "Event", DateTime.Now), new Event("Placeholder", "Event", DateTime.Now), new Event("Placeholder", "Event", DateTime.Now) };
//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"), };
//code for graph
LineChart<double> lineChart;
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
await HandleRedraw();
}
}
async Task HandleRedraw()
{
await lineChart.Clear();
await lineChart.AddLabelsDatasetsAndUpdate(Labels, GetLineChartDataset());
}
//TODO: insert dataset of current and last voltage usages
LineChartDataset<double> GetLineChartDataset()
{
return new LineChartDataset<double>
{
Label = "# of random number in thousands",
Data = RandomizeData(),
BackgroundColor = backgroundColors,
BorderColor = borderColors,
Fill = true,
PointRadius = 3,
CubicInterpolationMode = "monotone",
};
}
string[] Labels = { "Red", "Blue", "Yellow", "Green", "Purple", "Orange" };
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<double> RandomizeData()
{
var r = new Random(DateTime.Now.Millisecond);
return 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() };
}
//private Background buttonColor = Background.Primary;
private void ChangeButtonColor()
{
//device.on = !device.on;
}
}
@@ -1,23 +1,97 @@
using System; using Blazorise.Charts;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Components;
using System.Net.Http;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.Components.Forms;
using Microsoft.AspNetCore.Components.Routing;
using Microsoft.AspNetCore.Components.Web;
using Microsoft.AspNetCore.Components.Web.Virtualization;
using Microsoft.JSInterop;
using Elektrifikatsiya;
using Blazorise;
namespace Elektrifikatsiya.Pages using Elektrifikatsiya.Models;
using Elektrifikatsiya.Utilities;
using System.Diagnostics;
using System.Text;
namespace Elektrifikatsiya.Pages;
public partial class Dashboard
{ {
public partial class Dashboard //TODO: insert new event here if plug produces one
{ private readonly 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
private List<Device> plugs = new List<Device>();
//code for graph
private 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)
{
if (firstRender)
{
await HandleRedraw();
}
}
private async Task Switch(Device device)
{
device.Enabled = !device.Enabled;
_ = await DeviceManagmentService.UpdateDevice(device);
}
private async Task HandleRedraw()
{
labels.Clear();
await lineChart.Clear();
await lineChart.AddLabelsDatasetsAndUpdate(labels, await GetLineChartDataset());
}
//TODO: insert dataset of current and last voltage usages
private async Task<LineChartDataset<double>> GetLineChartDataset()
{
return new LineChartDataset<double>
{
Label = "Wattage",
Data = await DeviceData(),
Fill = true,
PointRadius = 3,
CubicInterpolationMode = "monotone",
};
}
private readonly List<string> labels = new List<string>();
private async Task<List<double>> DeviceData()
{
PrometheusQuery promQueryer = new PrometheusQuery("http://localhost:9090");
StringBuilder builder = new();
foreach (Device device in plugs)
{
_ = builder.Append($"shellyplug-s-{device.MacAddress}/relay/0|");
}
if (builder.Length <= 1)
{
return new();
}
string plugnames = builder.ToString()[..^1];
Debug.WriteLine($$"""sum(power{sensor=~"{{plugnames}}"})[1h:1m]""");
PrometheusDataWrapper? deviceData = (await promQueryer.Query($$"""sum(power{sensor=~"{{plugnames}}"})[1h:1m]"""))?.Data;
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>();
} }
} }
@@ -2,60 +2,208 @@
@using Blazorise.Components; @using Blazorise.Components;
@using Elektrifikatsiya.Models; @using Elektrifikatsiya.Models;
@using System.Net @using System.Net
<Row Style="width: 100%; height: 100%"> @using System.Text.Json
<Column ColumnSize="ColumnSize.Is4"> @using Elektrifikatsiya.Services.Implementations
<Bar Breakpoint="Breakpoint.Desktop" @using Elektrifikatsiya.Services;
Background="Background.White" @using FluentResults
ThemeContrast="ThemeContrast.None"
Shadow="Shadow.Remove" @inject IDeviceManagmentService DeviceManagmentService
Border="Border.Is1.RoundedTop"> @inject IMessageService MessageService
<BarBrand>
Plugs <Div>
</BarBrand> <Row Style="width: 100%; height: 100%" Margin="Margin.Is3.FromTop.OnMobile" Padding="Padding.Is4.FromStart.OnMobile">
</Bar> <Div Display="Display.Flex.Row.OnDesktop" Margin=" Margin.Is3.FromBottom" Width="Width.Is100">
<ListView TItem="Device" <Column ColumnSize="ColumnSize.Is5.OnDesktop.Is12.OnMobile">
Data="@plugs" <Bar Breakpoint="Breakpoint.Desktop"
TextField="@(()=>(""))" Background="Background.White"
ValueField="@(()=>(""))" ThemeContrast="ThemeContrast.None"
Style="border-radius: 0px 0px" Shadow="Shadow.Remove"
Height="100%" Border="Border.Is1.RoundedTop">
MaxHeight="90%"> <BarBrand>
<ItemTemplate> Plugs
<ListGroupItem Border="Border.OnBottom"> </BarBrand>
<Row> </Bar>
<Column ColumnSize="ColumnSize.Is8"> <ListView TItem="Device"
<Row> Data="@plugs"
<Column ColumnSize="ColumnSize.Is7"> TextField="@((_)=>(""))"
<Heading Size="HeadingSize.Is6" Margin="Margin.Is1.FromBottom">@context.Item.Name</Heading> ValueField="@((_)=>(""))"
</Column> Style="border-radius: 0px 0px"
</Row> Height="100%"
<Row> MaxHeight="90%">
<Column> <ItemTemplate>
<Small>User: @context.Item.User</Small> <ListGroupItem Border="Border.OnBottom">
<br /> <Row>
<Small>Room: @context.Item.Room</Small>
</Column> <Column ColumnSize="ColumnSize.Is6">
<Column ColumnSize="ColumnSize.Is5"> <Row>
<Paragraph Margin="Margin.Is1.OnY">@context.Item.PowerUsage W</Paragraph> <Column ColumnSize="ColumnSize.Is7">
</Column> <Heading Size="HeadingSize.Is6" Margin="Margin.Is1.FromBottom">@context.Item.Name</Heading>
</Row> </Column>
</Column> </Row>
<Column ColumnSize="ColumnSize.Is4"> <Row>
<Button Position="Position.Absolute.Top.Is50.Start.Is50.Translate.Middle" Color="Color.Dark" Outline> <Column>
<BarIcon IconName="IconName.Bolt" /> <Small>User: @context.Item.User.Name</Small>
</Button> <br />
</Column> <Small>Room: @context.Item.Room</Small>
</Row> </Column>
</ListGroupItem> </Row>
</ItemTemplate> </Column>
</ListView>
</Column> <Column ColumnSize="ColumnSize.Is4.OnDesktop.Is7.OnMobile">
</Row> <Button Position="Position.Absolute.Top.Is50.Start.Is50.Translate.Middle" Color="Color.Dark" Outline>
<BarIcon @onclick="() => Delete(context.Item)" IconName="IconName.Delete" />
</Button>
</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 (DeviceCopy is not null)
{
<Div hidden="@hideButtonSettings">
<Field>
<FieldLabel>
<h2>
Plug Settings
</h2>
</FieldLabel>
</Field>
<Field>
<FieldLabel>
<h5>
Plug Name
</h5>
<Paragraph>
Here you can change the name of your plug
</Paragraph>
</FieldLabel>
<TextEdit @bind-Text="@DeviceCopy.Name" Placeholder="Enter Name" />
</Field>
<br />
<br />
<Field>
<FieldLabel>
<h5>
Change Max Output
</h5>
<Paragraph>
Here you can limit how much power your plug uses
</Paragraph>
</FieldLabel>
<TextEdit Placeholder="Enter Max Output" />
<!--TODO: What is this?-->
</Field>
<br />
<br />
<Field>
<FieldLabel>
<h5>
Select Room
</h5>
<Paragraph>
Here you select or change the room the plug belongs to.
</Paragraph>
</FieldLabel>
<TextEdit @bind-text="@DeviceCopy.Room" Placeholder="Enter the name of the room here"/>
</Field>
</Div>
}
<Div hidden="@(!hideButtonSettings)">
<Field>
<FieldLabel>
<h2>
General Settings
</h2>
</FieldLabel>
</Field>
<Field>
<FieldLabel>
<h5>
Electricity Price
</h5>
<Paragraph>
Here you enter your electricity price. This is gonna calculate the overall Price of your System
</Paragraph>
</FieldLabel>
<TextEdit Placeholder="Enter Electricity Price" />
</Field>
</Div>
<Column ColumnSize="ColumnSize.IsFull" TextAlignment="TextAlignment.End">
<Button @onclick="OnSave" Color="Color.Primary">Save</Button>
</Column>
</Column>
</Div>
</Row>
</Div>
@code { @code {
List<Device> plugs = new List<Device>();
private bool hideButtonSettings = true;
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"), }; Device? SelectedDevice = null;
Device? DeviceCopy = null;
protected override void OnInitialized()
{
Result<List<Device>> getDevicesResult = DeviceManagmentService.GetDevices();
if (getDevicesResult.IsSuccess)
{
plugs = getDevicesResult.Value;
}
}
private void Toggle(Device device)
{
hideButtonSettings = !hideButtonSettings;
SelectedDevice = device;
DeviceCopy = device.CopyDevice();
}
private void OnSave()
{
if (hideButtonSettings || DeviceCopy is null || SelectedDevice is null)
{
}
else
{
SelectedDevice.OverwiteDevice(DeviceCopy);
DeviceManagmentService.UpdateDevice(SelectedDevice);
}
}
private async Task Delete(Device contextItem)
{
bool succ = await MessageService.Confirm($"Do you really want to delete the device \"{contextItem.Name}\"?");
if(!succ)
{
return;
}
await DeviceManagmentService.UnregisterDevice(contextItem.MacAddress);
int index = plugs.FindIndex(x => x.MacAddress == contextItem.MacAddress);
if(index != -1)
{
plugs.RemoveAt(index);
}
}
} }
@@ -1,3 +0,0 @@
@using Elektrifikatsiya.Components.TodoApp
@page "/apps/todo"
<TodoItems />
@@ -8,6 +8,9 @@ using Elektrifikatsiya.Models;
using Elektrifikatsiya.Services; using Elektrifikatsiya.Services;
using Elektrifikatsiya.Services.Implementations; using Elektrifikatsiya.Services.Implementations;
using HiveMQtt.Client;
using HiveMQtt.Client.Options;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
WebApplicationBuilder builder = WebApplication.CreateBuilder(args); WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
@@ -18,12 +21,24 @@ builder.Services.AddServerSideBlazor();
builder.Services.AddHttpContextAccessor(); builder.Services.AddHttpContextAccessor();
builder.Services.AddHostedService<UpdateService>(); builder.Services.AddHostedService<UpdateService>();
builder.Services.AddSingleton<IDeviceStatusService, DeviceStatusService>(); builder.Services.AddSingleton<IDeviceStatusService, DeviceStatusService>();
builder.Services.AddSingleton<IHiveMQClient, HiveMQClient>((provider)=>
{
HiveMQClientOptions options = new()
{
Host = "localhost",
Port = 1883,
UseTLS = false,
};
HiveMQClient client = new(options);
client.ConnectAsync().ConfigureAwait(false);
return client;
});
builder.Services.AddTransient<IDeviceManagmentService, DeviceManagmentService>(); builder.Services.AddTransient<IDeviceManagmentService, DeviceManagmentService>();
builder.Services.AddScoped<IAuthenticationService, AuthenticationService>(); builder.Services.AddScoped<IAuthenticationService, AuthenticationService>();
builder.Services.AddScoped<IAuthorizationService, AuthorizationService>(); builder.Services.AddScoped<IAuthorizationService, AuthorizationService>();
builder.Services.AddScoped<ICookieService, CookieService>(); builder.Services.AddScoped<ICookieService, CookieService>();
builder.Services.AddDbContext<UserDatabaseContext>(options => options.UseSqlite("Data Source=./UserDatabase.sqlite")); builder.Services.AddDbContext<MainDatabaseContext>(options => options.UseSqlite("Data Source=./MainDatabase.sqlite"));
builder.Services.AddDbContext<DeviceManagmentDatabaseContext>((options) => options.UseSqlite("Data Source=./DeviceManagement.sqlite"));
builder.Services.AddBootstrapProviders(); builder.Services.AddBootstrapProviders();
builder.Services.AddHttpClient<IDeviceManagmentService, DeviceManagmentService>(); builder.Services.AddHttpClient<IDeviceManagmentService, DeviceManagmentService>();
builder.Services.AddBlazorise(options => builder.Services.AddBlazorise(options =>
@@ -53,10 +68,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<UserDatabaseContext>().Database.EnsureCreated();
AsyncServiceScope scope = app.Services.CreateAsyncScope(); MainDatabaseContext mainDatabase = serviceScope.ServiceProvider.GetRequiredService<MainDatabaseContext>();
scope.ServiceProvider.GetRequiredService<DeviceManagmentDatabaseContext>().Database.EnsureCreated(); 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:5656;http://localhost:5255" "applicationUrl": "https://localhost:56656;http://localhost:55552"
}, },
"IIS Express": { "IIS Express": {
"commandName": "IISExpress", "commandName": "IISExpress",
@@ -12,13 +12,13 @@ namespace Elektrifikatsiya.Services.Implementations;
public class AuthenticationService : IAuthenticationService public class AuthenticationService : IAuthenticationService
{ {
private readonly UserDatabaseContext userDatabaseContext; private readonly MainDatabaseContext mainDatabaseContext;
private readonly IHttpContextAccessor httpContextAccessor; private readonly IHttpContextAccessor httpContextAccessor;
private readonly ICookieService cookieService; private readonly ICookieService cookieService;
public AuthenticationService(UserDatabaseContext userDatabaseContext, IHttpContextAccessor httpContextAccessor, ICookieService cookieService) public AuthenticationService(MainDatabaseContext mainDatabaseContext, IHttpContextAccessor httpContextAccessor, ICookieService cookieService)
{ {
this.userDatabaseContext = userDatabaseContext; this.mainDatabaseContext = mainDatabaseContext;
this.httpContextAccessor = httpContextAccessor; this.httpContextAccessor = httpContextAccessor;
this.cookieService = cookieService; this.cookieService = cookieService;
} }
@@ -32,8 +32,8 @@ public class AuthenticationService : IAuthenticationService
return getUserResult.ToResult(); return getUserResult.ToResult();
} }
_ = userDatabaseContext.Users.Remove(getUserResult.Value); _ = mainDatabaseContext.Users.Remove(getUserResult.Value);
return (await Result.Try(() => userDatabaseContext.SaveChangesAsync())).ToResult(); return (await Result.Try(() => mainDatabaseContext.SaveChangesAsync())).ToResult();
} }
public async Task<Result<User>> GetUserAsync() public async Task<Result<User>> GetUserAsync()
@@ -45,7 +45,7 @@ public class AuthenticationService : IAuthenticationService
return Result.Fail("Token is not valid!"); return Result.Fail("Token is not valid!");
} }
User? user = await userDatabaseContext.Users.FirstOrDefaultAsync(u => u.SessionToken == token); User? user = await mainDatabaseContext.Users.FirstOrDefaultAsync(u => u.SessionToken == token);
if (user is null || DateTime.UtcNow - user.LastLoginDate > TimeSpan.FromDays(7)) if (user is null || DateTime.UtcNow - user.LastLoginDate > TimeSpan.FromDays(7))
{ {
@@ -62,7 +62,7 @@ public class AuthenticationService : IAuthenticationService
public async Task<Result> LoginUserAsync(string name, string password) public async Task<Result> LoginUserAsync(string name, string password)
{ {
User? user = await userDatabaseContext.Users.FirstOrDefaultAsync(u => u.Name.Equals(name, StringComparison.InvariantCultureIgnoreCase)); User? user = await mainDatabaseContext.Users.FirstOrDefaultAsync(u => u.Name == name);
if (user is null) if (user is null)
{ {
@@ -79,7 +79,7 @@ public class AuthenticationService : IAuthenticationService
user.LastLoginDate = DateTime.UtcNow; user.LastLoginDate = DateTime.UtcNow;
user.SessionToken = newToken; user.SessionToken = newToken;
_ = await userDatabaseContext.SaveChangesAsync(); _ = await mainDatabaseContext.SaveChangesAsync();
await cookieService.WriteCookieAsync("token", newToken, 7); await cookieService.WriteCookieAsync("token", newToken, 7);
@@ -97,7 +97,7 @@ public class AuthenticationService : IAuthenticationService
return Result.Ok(); return Result.Ok();
} }
User? user = await userDatabaseContext.Users.FirstOrDefaultAsync(u => u.SessionToken == token); User? user = await mainDatabaseContext.Users.FirstOrDefaultAsync(u => u.SessionToken == token);
if (user is null) if (user is null)
{ {
@@ -106,7 +106,7 @@ public class AuthenticationService : IAuthenticationService
user.SessionToken = null; user.SessionToken = null;
_ = await userDatabaseContext.SaveChangesAsync(); _ = await mainDatabaseContext.SaveChangesAsync();
return Result.Ok(); return Result.Ok();
} }
@@ -121,14 +121,14 @@ public class AuthenticationService : IAuthenticationService
} }
User user = new User(name, BC.HashPassword(password), role); User user = new User(name, BC.HashPassword(password), role);
_ = userDatabaseContext.Users.Add(user); _ = mainDatabaseContext.Users.Add(user);
return (await Result.Try(() => userDatabaseContext.SaveChangesAsync())).ToResult(); return (await Result.Try(() => mainDatabaseContext.SaveChangesAsync())).ToResult();
} }
public Task<Result<bool>> UserExistsAsync(string name) public Task<Result<bool>> UserExistsAsync(string name)
{ {
return Result.Try(() => return Result.Try(() =>
userDatabaseContext.Users.AnyAsync(u => u.Name.Equals(name, StringComparison.InvariantCultureIgnoreCase))); mainDatabaseContext.Users.AnyAsync(u => u.Name == name));
} }
} }
@@ -3,6 +3,11 @@ using Elektrifikatsiya.Models;
using FluentResults; using FluentResults;
using HiveMQtt.Client;
using HiveMQtt.Client.Results;
using Microsoft.EntityFrameworkCore;
using System.Net; using System.Net;
using System.Net.NetworkInformation; using System.Net.NetworkInformation;
@@ -10,153 +15,166 @@ namespace Elektrifikatsiya.Services.Implementations;
public class DeviceManagmentService : IDeviceManagmentService public class DeviceManagmentService : IDeviceManagmentService
{ {
private readonly IServiceScopeFactory serviceScopeFactory; private readonly IServiceScopeFactory serviceScopeFactory;
private readonly IDeviceStatusService deviceStatusService; private readonly IDeviceStatusService deviceStatusService;
private readonly ILogger<DeviceManagmentService> logger; private readonly ILogger<DeviceManagmentService> logger;
private readonly HttpClient httpClient; private readonly IHiveMQClient hiveMQClient;
private readonly HttpClient httpClient;
public DeviceManagmentService(IServiceScopeFactory serviceScopeFactory, IDeviceStatusService deviceStatusService, ILogger<DeviceManagmentService> logger, 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.httpClient = httpClient; this.hiveMQClient = hiveMQClient;
} this.httpClient = httpClient;
}
public Result<Device> GetDevice(string macAdress) public Result<Device> GetDevice(string macAdress)
{ {
Result<List<Device>> getDevicesResult = deviceStatusService.GetDevices(); Result<List<Device>> getDevicesResult = deviceStatusService.GetDevices();
if (getDevicesResult.IsFailed) if (getDevicesResult.IsFailed)
{ {
return getDevicesResult.ToResult(); return getDevicesResult.ToResult();
} }
Device? device = getDevicesResult.Value.FirstOrDefault(d => d.MacAddress == macAdress); Device? device = getDevicesResult.Value.FirstOrDefault(d => d.MacAddress == macAdress);
if (device is null) if (device is null)
{ {
return Result.Fail("Device does not exist!"); return Result.Fail("Device does not exist!");
} }
return device; return device;
} }
public Result<List<Device>> GetDevices() public Result<List<Device>> GetDevices()
{ {
Result<List<Device>> getDevicesResult = deviceStatusService.GetDevices(); Result<List<Device>> getDevicesResult = deviceStatusService.GetDevices();
if (getDevicesResult.IsFailed) if (getDevicesResult.IsFailed)
{ {
return getDevicesResult.ToResult(); return getDevicesResult.ToResult();
} }
return getDevicesResult.Value.ToList(); return getDevicesResult.Value.ToList();
} }
public Result<List<Device>> GetDevicesInRoom(string room) public Result<List<Device>> GetDevicesInRoom(string room)
{ {
Result<List<Device>> getDevicesResult = deviceStatusService.GetDevices(); Result<List<Device>> getDevicesResult = deviceStatusService.GetDevices();
if (getDevicesResult.IsFailed) if (getDevicesResult.IsFailed)
{ {
return getDevicesResult.ToResult(); return getDevicesResult.ToResult();
} }
return getDevicesResult.Value.Where(d => d.Room == room).ToList(); return getDevicesResult.Value.Where(d => d.Room == room).ToList();
} }
public Result<List<Device>> GetDevicesOfUser(int userId) public Result<List<Device>> GetDevicesOfUser(int userId)
{ {
Result<List<Device>> getDevicesResult = deviceStatusService.GetDevices(); Result<List<Device>> getDevicesResult = deviceStatusService.GetDevices();
if (getDevicesResult.IsFailed) if (getDevicesResult.IsFailed)
{ {
return getDevicesResult.ToResult(); return getDevicesResult.ToResult();
} }
return getDevicesResult.Value.Where(d => d.User.Id == userId).ToList(); return getDevicesResult.Value.Where(d => d.User.Id == userId).ToList();
} }
public async Task<Result<Device>> RegisterDevice(IPAddress ip, User user, string? name = null, string room = "default") public async Task<Result<Device>> RegisterDevice(IPAddress ip, User user, string? name = null, string room = "default")
{ {
using IServiceScope scope = serviceScopeFactory.CreateScope(); using IServiceScope scope = serviceScopeFactory.CreateScope();
DeviceManagmentDatabaseContext deviceManagmentDatabaseContext = scope.ServiceProvider.GetRequiredService<DeviceManagmentDatabaseContext>(); MainDatabaseContext mainDatabaseContext = scope.ServiceProvider.GetRequiredService<MainDatabaseContext>();
ShellyResponse? shellyResponse = null; ShellyResponse? shellyResponse = null;
try try
{ {
shellyResponse = await httpClient.GetFromJsonAsync<ShellyResponse>($"http://{ip}/shelly"); shellyResponse = await httpClient.GetFromJsonAsync<ShellyResponse>($"http://{ip}/shelly");
} }
catch (Exception ex) catch (Exception ex)
{ {
logger.LogError("HTTP request failed! {message}", ex.Message); logger.LogError("HTTP request failed! {message}", ex.Message);
} }
if (shellyResponse is null || shellyResponse.Type != "SHPLG-S") if (shellyResponse is null || shellyResponse.Type != "SHPLG-S")
{ {
return Result.Fail("Device is not reachable or not a \"SHPLG-S\"!"); return Result.Fail("Device is not reachable or not a \"SHPLG-S\"!");
} }
string mac = shellyResponse.Mac; string mac = shellyResponse.Mac;
if (!PhysicalAddress.TryParse(mac, out _)) if (!PhysicalAddress.TryParse(mac, out _))
{ {
return Result.Fail("Invalid mac address!"); return Result.Fail("Invalid mac address!");
} }
Device device = new Device(mac, name ?? mac, ip, user, room); Device device = new Device(mac, name ?? mac, ip, user, room);
_ = deviceManagmentDatabaseContext.Add(device); mainDatabaseContext.Entry(user).State = EntityState.Unchanged;
Result saveDatabaseChangesResult = await Result.Try(Task () => deviceManagmentDatabaseContext.SaveChangesAsync());
if (saveDatabaseChangesResult.IsFailed) _ = mainDatabaseContext.Add(device);
{ Result saveDatabaseChangesResult = await Result.Try(Task () => mainDatabaseContext.SaveChangesAsync());
return saveDatabaseChangesResult;
}
return deviceStatusService.TrackDevice(device); if (saveDatabaseChangesResult.IsFailed)
} {
return saveDatabaseChangesResult;
}
public async Task<Result> UnregisterDevice(string macAdress) return deviceStatusService.TrackDevice(device);
{ }
using IServiceScope scope = serviceScopeFactory.CreateScope();
DeviceManagmentDatabaseContext deviceManagmentDatabaseContext = scope.ServiceProvider.GetRequiredService<DeviceManagmentDatabaseContext>();
Result<Device> getDeviceResult = GetDevice(macAdress); public async Task<Result> UnregisterDevice(string macAdress)
{
using IServiceScope scope = serviceScopeFactory.CreateScope();
MainDatabaseContext mainDatabaseContext = scope.ServiceProvider.GetRequiredService<MainDatabaseContext>();
if (getDeviceResult.IsFailed) Result<Device> getDeviceResult = GetDevice(macAdress);
{
return getDeviceResult.ToResult();
}
Result untrackDeviceResult = deviceStatusService.UntrackDevice(macAdress); if (getDeviceResult.IsFailed)
{
return getDeviceResult.ToResult();
}
if (untrackDeviceResult.IsFailed) Result untrackDeviceResult = deviceStatusService.UntrackDevice(macAdress);
{
return untrackDeviceResult;
}
_ = deviceManagmentDatabaseContext.Remove(getDeviceResult.Value); if (untrackDeviceResult.IsFailed)
{
return untrackDeviceResult;
}
return await Result.Try(Task () => deviceManagmentDatabaseContext.SaveChangesAsync()); _ = mainDatabaseContext.Remove(getDeviceResult.Value);
}
public async Task<Result> UpdateDevice(Device device) return await Result.Try(Task () => mainDatabaseContext.SaveChangesAsync());
{ }
using IServiceScope scope = serviceScopeFactory.CreateScope();
DeviceManagmentDatabaseContext deviceManagmentDatabaseContext = scope.ServiceProvider.GetRequiredService<DeviceManagmentDatabaseContext>();
Result result = deviceStatusService.UpdateDeviceStatus(device); public async Task<Result> UpdateDevice(Device device)
{
using IServiceScope scope = serviceScopeFactory.CreateScope();
MainDatabaseContext mainDatabaseContext = scope.ServiceProvider.GetRequiredService<MainDatabaseContext>();
if (result.IsFailed) Result<Device> getDeviceResult = GetDevice(device.MacAddress);
{
return result;
}
_ = deviceManagmentDatabaseContext.Update(device); if (getDeviceResult.IsFailed)
{
return getDeviceResult.ToResult();
}
return await Result.Try(Task () => deviceManagmentDatabaseContext.SaveChangesAsync()); Result updateDeviceResult = deviceStatusService.UpdateDeviceStatus(device);
}
if (updateDeviceResult.IsFailed)
{
return updateDeviceResult;
}
PublishResult res = await hiveMQClient.PublishAsync($"shellies/shellyplug-s-{device.MacAddress}/relay/0/command", device.Enabled ? "on" : "off");
_ = mainDatabaseContext.Update(device);
return await Result.Try(Task () => mainDatabaseContext.SaveChangesAsync());
}
} }
@@ -6,15 +6,17 @@ namespace Elektrifikatsiya.Services.Implementations;
public class DeviceStatusService : IDeviceStatusService public class DeviceStatusService : IDeviceStatusService
{ {
private readonly ILogger<DeviceStatusService> logger; private readonly ILogger<DeviceStatusService> logger;
public event EventHandler<DeviceStatusChagedEventArgs>? OnDeviceStatusChanged;
public event EventHandler<DeviceStatusChagedEventArgs>? OnDeviceStatusChanged;
private readonly Dictionary<string, Device> devices = new(); private readonly Dictionary<string, Device> devices = new();
public DeviceStatusService(ILogger<DeviceStatusService> logger) public DeviceStatusService(ILogger<DeviceStatusService> logger)
{ {
this.logger = logger; this.logger = logger;
} }
public Result<List<Device>> GetDevices() public Result<List<Device>> GetDevices()
{ {
return devices.Values.ToList(); return devices.Values.ToList();
@@ -30,7 +32,7 @@ public class DeviceStatusService : IDeviceStatusService
} }
modDevice.PowerUsage = device.PowerUsage; modDevice.PowerUsage = device.PowerUsage;
modDevice.Available = device.Available; modDevice.Enabled = device.Enabled;
modDevice.IpAddress = device.IpAddress; modDevice.IpAddress = device.IpAddress;
modDevice.Name = device.Name; modDevice.Name = device.Name;
@@ -1,8 +1,10 @@
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;
using System.Threading.Tasks;
namespace Elektrifikatsiya.Services.Implementations; namespace Elektrifikatsiya.Services.Implementations;
@@ -22,12 +24,12 @@ public class UpdateService : IHostedService, IDisposable
public async Task StartAsync(CancellationToken cancellationToken) public async Task StartAsync(CancellationToken cancellationToken)
{ {
IServiceScope serviceScope = serviceScopeFactory.CreateScope(); IServiceScope serviceScope = serviceScopeFactory.CreateScope();
DeviceManagmentDatabaseContext deviceManagmentDatabaseContext = serviceScope.ServiceProvider.GetRequiredService<DeviceManagmentDatabaseContext>(); MainDatabaseContext mainDatabaseContext = serviceScope.ServiceProvider.GetRequiredService<MainDatabaseContext>();
logger.LogInformation("Starting update service..."); logger.LogInformation("Starting update service...");
foreach (Device device in await deviceManagmentDatabaseContext.Devices.AsNoTracking().ToListAsync(cancellationToken)) foreach (Device device in await mainDatabaseContext.Devices.Include(d => d.User).AsNoTracking().ToListAsync(cancellationToken))
{ {
_ = deviceStatusService.TrackDevice(device); _ = deviceStatusService.TrackDevice(device);
} }
@@ -45,10 +47,18 @@ 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? devicePowerData = (await promQueryer.Query($"power{{sensor=\"shellyplug-s-{device.MacAddress}/relay/0\"}}"))?.Data;
PrometheusDataWrapper? deviceStatusData = (await promQueryer.Query($"state{{sensor=\"shellyplug-s-{device.MacAddress}/relay\"}}"))?.Data;
if (devicePowerData is not null && deviceStatusData is not null)
{
device.PowerUsage = devicePowerData.VectorTypeToTimestampFloatTuple()?.ValueOrDefault.Item2 ?? 0;
device.Enabled = (deviceStatusData.VectorTypeToTimestampFloatTuple()?.ValueOrDefault.Item2 ?? 0) == 1;
_ = deviceStatusService.UpdateDeviceStatus(device);
}
} }
} }
@@ -1,4 +1,8 @@
using System.Net; using Elektrifikatsiya.Models;
using Microsoft.Extensions.Caching.Memory;
using System.Net;
using Tmds.MDns; using Tmds.MDns;
@@ -9,17 +13,56 @@ public static class MdnsDiscovery
public static event Action<IPAddress> OnDeviceFound = null!; public static event Action<IPAddress> OnDeviceFound = null!;
private static readonly ServiceBrowser serviceBrowser = new ServiceBrowser(); private static readonly ServiceBrowser serviceBrowser = new ServiceBrowser();
private static readonly HttpClient client = new();
private static readonly MemoryCache memoryCache = new MemoryCache(new MemoryCacheOptions());
static MdnsDiscovery() static MdnsDiscovery()
{ {
serviceBrowser.StartBrowse("_http._tcp"); serviceBrowser.StartBrowse("_http._tcp");
serviceBrowser.ServiceAdded += (_, eventArgs) => OnDeviceFound?.Invoke(eventArgs.Announcement.Addresses.First()); serviceBrowser.ServiceAdded += async (_, eventArgs) => await AddDevice(eventArgs.Announcement);
serviceBrowser.ServiceChanged += (_, eventArgs) => OnDeviceFound?.Invoke(eventArgs.Announcement.Addresses.First()); serviceBrowser.ServiceChanged += async (_, eventArgs) => await AddDevice(eventArgs.Announcement);
serviceBrowser.ServiceRemoved += (_, eventArgs) => OnDeviceFound?.Invoke(eventArgs.Announcement.Addresses.First()); serviceBrowser.ServiceRemoved += async (_, eventArgs) => await AddDevice(eventArgs.Announcement);
} }
public static IEnumerable<IPAddress> GetChachedDevices() public static void FetchChachedDevices()
{ {
return serviceBrowser.Services.Select(s => s.Addresses.First()); serviceBrowser.Services.ToList().ForEach(async d => await AddDevice(d));
}
private static async Task AddDevice(ServiceAnnouncement announcement)
{
IPAddress ipAddress = announcement.Addresses.First();
if (!memoryCache.TryGetValue(ipAddress.ToString(), out bool isShellyDevice))
{
isShellyDevice = await IsShellyDevice(ipAddress);
_ = memoryCache.Set(ipAddress.ToString(), isShellyDevice, TimeSpan.FromHours(1));
}
if (isShellyDevice)
{
OnDeviceFound?.Invoke(ipAddress);
}
}
private static async Task<bool> IsShellyDevice(IPAddress ipAddress)
{
ShellyResponse? shellyResponse;
try
{
shellyResponse = await client.GetFromJsonAsync<ShellyResponse>($"http://{ipAddress}/shelly");
}
catch (HttpRequestException)
{
return false;
}
if (shellyResponse is null || shellyResponse.Type != "SHPLG-S")
{
return false;
}
return true;
} }
} }
@@ -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;
@@ -9,17 +10,22 @@ namespace Elektrifikatsiya.Utilities;
public class PrometheusQuery public class PrometheusQuery
{ {
private string connectionString;
private readonly HttpClient client = new(); private readonly HttpClient client = new();
public PrometheusQuery(string connectionString) public PrometheusQuery(string connectionString)
{ {
this.connectionString = connectionString;
client.BaseAddress = new Uri(connectionString); client.BaseAddress = new Uri(connectionString);
} }
public Task<PrometheusQueryResult?> Query(string query) public Task<PrometheusQueryResult?> Query(string query)
{ {
return client.GetFromJsonAsync<PrometheusQueryResult>($"/v1/query?{UrlEncoder.Create().Encode(query)}"); return client.GetFromJsonAsync<PrometheusQueryResult>($"/api/v1/query?query={UrlEncoder.Create().Encode(query)}", new JsonSerializerOptions()
{
PropertyNameCaseInsensitive = true,
Converters =
{
new JsonStringEnumConverter()
}
});
} }
} }
@@ -9,9 +9,6 @@
<DockerServiceName>elektrifikatsiya</DockerServiceName> <DockerServiceName>elektrifikatsiya</DockerServiceName>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<None Include="docker-compose.override.yml">
<DependentUpon>docker-compose.yml</DependentUpon>
</None>
<None Include="docker-compose.yml" /> <None Include="docker-compose.yml" />
<None Include=".dockerignore" /> <None Include=".dockerignore" />
</ItemGroup> </ItemGroup>
@@ -1,13 +0,0 @@
version: '3.4'
services:
elektrifikatsiya:
environment:
- ASPNETCORE_ENVIRONMENT=Development
- ASPNETCORE_URLS=https://+:443;http://+:80
ports:
- "80"
- "443"
volumes:
- ${APPDATA}/Microsoft/UserSecrets:/root/.microsoft/usersecrets:ro
- ${APPDATA}/ASP.NET/Https:/root/.aspnet/https:ro
+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: