mirror of
https://github.com/Stefan-5422/-T5-Elektrifikatsiya.git
synced 2026-09-10 15:46:03 +02:00
Merge pull request #38 from Stefan-5422/feature-DeviceRegistration
Feature device registration
This commit is contained in:
@@ -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>
|
|
||||||
@@ -42,6 +42,7 @@
|
|||||||
<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.2" />
|
<PackageReference Include="FluentResults" Version="3.15.2" />
|
||||||
|
<PackageReference Include="HiveMQtt" Version="0.1.10" />
|
||||||
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.4" />
|
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.4" />
|
||||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="7.0.4" />
|
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="7.0.4" />
|
||||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="7.0.4">
|
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="7.0.4">
|
||||||
|
|||||||
@@ -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;
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -24,7 +24,7 @@ public class Device
|
|||||||
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,6 +1,6 @@
|
|||||||
using System.Diagnostics;
|
using System.Diagnostics;
|
||||||
|
using System.Globalization;
|
||||||
using System.Text.Json.Serialization;
|
using System.Text.Json.Serialization;
|
||||||
using Microsoft.AspNetCore.Mvc.Diagnostics;
|
|
||||||
|
|
||||||
namespace Elektrifikatsiya.Models;
|
namespace Elektrifikatsiya.Models;
|
||||||
|
|
||||||
@@ -50,48 +50,47 @@ public class PrometheusDataWrapper
|
|||||||
|
|
||||||
public FluentResults.Result<List<(double, double)>> MatrixTypeToTimestampFloatTuple()
|
public FluentResults.Result<List<(double, double)>> MatrixTypeToTimestampFloatTuple()
|
||||||
{
|
{
|
||||||
if (ResultType != ResultType.Matrix)
|
if (ResultType != ResultType.Matrix)
|
||||||
{
|
{
|
||||||
return FluentResults.Result.Fail("The response did not have the Matrix Type");
|
return FluentResults.Result.Fail("The response did not have the Matrix Type");
|
||||||
}
|
}
|
||||||
|
|
||||||
List<(double, double)> result = new List<(double, double)>();
|
List<(double, double)> result = new List<(double, double)>();
|
||||||
|
|
||||||
if (Result.Count == 0 || Result[0]?.Values is null || Result[0]?.Values?[0] is null)
|
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");
|
return FluentResults.Result.Fail("There was no result in the Response Body");
|
||||||
}
|
}
|
||||||
|
|
||||||
foreach (object value in Result[0]!.Values!)
|
foreach (object value in Result[0]!.Values!)
|
||||||
{
|
{
|
||||||
|
|
||||||
string[] segment = value.ToString()!.Split(",");
|
string[] segment = value.ToString()!.Split(",");
|
||||||
|
|
||||||
result.Add((Convert.ToDouble(segment[0][2..^1]), Convert.ToDouble(segment[1][1..^2])));
|
result.Add((Convert.ToDouble(segment[0][2..^1], CultureInfo.InvariantCulture), Convert.ToDouble(segment[1][1..^2], CultureInfo.InvariantCulture)));
|
||||||
}
|
}
|
||||||
Debug.WriteLine(result);
|
Debug.WriteLine(result);
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
public FluentResults.Result<(double, double)> VectorTypeToTimestampFloatTuple()
|
public FluentResults.Result<(double, double)> VectorTypeToTimestampFloatTuple()
|
||||||
{
|
{
|
||||||
if (ResultType != ResultType.Vector)
|
if (ResultType != ResultType.Vector)
|
||||||
{
|
{
|
||||||
return FluentResults.Result.Fail("The response did not have the Vector Type");
|
return FluentResults.Result.Fail("The response did not have the Vector Type");
|
||||||
}
|
}
|
||||||
|
|
||||||
string[]? segment = Result.FirstOrDefault()?.Value.ToString()?.Split(",") ?? null;
|
string[]? segment = Result.FirstOrDefault()?.Value?.ToString()?.Split(",");
|
||||||
|
|
||||||
if (segment is null)
|
if (segment is null)
|
||||||
{
|
{
|
||||||
return FluentResults.Result.Fail("There was no result in the Response Body");
|
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])));
|
return (Convert.ToDouble(segment[0][2..^1]), Convert.ToDouble(segment[1][1..^2], CultureInfo.InvariantCulture));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
public class PrometheusDataMetric
|
public class PrometheusDataMetric
|
||||||
{
|
{
|
||||||
[JsonPropertyName("__name__")] public string Name { get; set; }
|
[JsonPropertyName("__name__")] public string Name { get; set; }
|
||||||
|
|||||||
@@ -14,144 +14,155 @@
|
|||||||
|
|
||||||
|
|
||||||
<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" />
|
||||||
|
|
||||||
</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>();
|
||||||
|
|
||||||
Validation? ipValidation;
|
Validation? ipValidation;
|
||||||
|
|
||||||
bool visible = true;
|
bool visible = true;
|
||||||
|
bool disabled = false;
|
||||||
|
|
||||||
string ipText = null!;
|
string ipText = null!;
|
||||||
|
|
||||||
protected override void OnInitialized()
|
protected override void OnInitialized()
|
||||||
{
|
{
|
||||||
MdnsDiscovery.OnDeviceFound += async ipAddress =>
|
MdnsDiscovery.OnDeviceFound += async ipAddress =>
|
||||||
{
|
{
|
||||||
visible = false;
|
visible = false;
|
||||||
if (!ipAddresses.Contains(ipAddress))
|
if (!ipAddresses.Contains(ipAddress))
|
||||||
{
|
{
|
||||||
ipAddresses.Add(ipAddress);
|
ipAddresses.Add(ipAddress);
|
||||||
await InvokeAsync(StateHasChanged);
|
await InvokeAsync(StateHasChanged);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
MdnsDiscovery.FetchChachedDevices();
|
MdnsDiscovery.FetchChachedDevices();
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task RegisterDevice(IPAddress ipAddress)
|
private async Task RegisterDevice(IPAddress ipAddress)
|
||||||
{
|
{
|
||||||
Result<Device> result = await DeviceManagmentService.RegisterDevice(ipAddress, (await AuthenticationService.GetUserAsync()).ValueOrDefault);
|
disabled = true;
|
||||||
|
Result<Device> result = await DeviceManagmentService.RegisterDevice(ipAddress, (await AuthenticationService.GetUserAsync()).ValueOrDefault);
|
||||||
|
|
||||||
if (result.IsSuccess)
|
if (result.IsSuccess)
|
||||||
{
|
{
|
||||||
await MessageService.Success("Device added!");
|
await MessageService.Success("Device added!");
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
await MessageService.Error(string.Join(',', result.Errors.Select(e => e.Message)), "Adding device failed!");
|
await MessageService.Error(string.Join(',', result.Errors.Select(e => e.Message)), "Adding device failed!");
|
||||||
}
|
}
|
||||||
}
|
disabled = false;
|
||||||
|
}
|
||||||
|
|
||||||
public void ValidateIPv4(ValidatorEventArgs e)
|
public void ValidateIPv4(ValidatorEventArgs e)
|
||||||
{
|
{
|
||||||
string? input = Convert.ToString(e.Value);
|
string? input = Convert.ToString(e.Value);
|
||||||
|
|
||||||
if (string.IsNullOrWhiteSpace(input))
|
if (string.IsNullOrWhiteSpace(input))
|
||||||
{
|
{
|
||||||
e.Status = ValidationStatus.None;
|
e.Status = ValidationStatus.None;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
string[] splitValues = input.Split('.');
|
string[] splitValues = input.Split('.');
|
||||||
if (splitValues.Length != 4)
|
if (splitValues.Length != 4)
|
||||||
{
|
{
|
||||||
e.Status = ValidationStatus.Error;
|
e.Status = ValidationStatus.Error;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
e.Status = splitValues.All(r => byte.TryParse(r, out _)) ? ValidationStatus.Success : ValidationStatus.Error;
|
e.Status = splitValues.All(r => byte.TryParse(r, out _)) ? ValidationStatus.Success : ValidationStatus.Error;
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -5,165 +5,92 @@
|
|||||||
@using Elektrifikatsiya.Services
|
@using Elektrifikatsiya.Services
|
||||||
@using Elektrifikatsiya.Utilities
|
@using Elektrifikatsiya.Utilities
|
||||||
@using System.Diagnostics
|
@using System.Diagnostics
|
||||||
|
@using Elektrifikatsiya.Services.Implementations
|
||||||
@inject IVersionProvider VersionProvider
|
@inject IVersionProvider VersionProvider
|
||||||
|
|
||||||
@inject IDeviceStatusService DeviceStatusService;
|
@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.Name</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 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", "Placeholder", DateTime.Now), new Event("Placeholder", "Placeholder", DateTime.Now), new Event("Placeholder", "Placeholder", DateTime.Now) };
|
|
||||||
//TODO: insert new Device here if user adds one
|
|
||||||
List<Device> plugs = new List<Device>();
|
|
||||||
//code for graph
|
|
||||||
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();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async Task HandleRedraw()
|
|
||||||
{
|
|
||||||
labels.Clear();
|
|
||||||
await lineChart.Clear();
|
|
||||||
await lineChart.AddLabelsDatasetsAndUpdate(labels, await GetLineChartDataset());
|
|
||||||
}
|
|
||||||
|
|
||||||
//TODO: insert dataset of current and last voltage usages
|
|
||||||
async Task<LineChartDataset<double>> GetLineChartDataset()
|
|
||||||
{
|
|
||||||
return new LineChartDataset<double>
|
|
||||||
{
|
|
||||||
Label = "Wattage",
|
|
||||||
Data = await RandomizeData(),
|
|
||||||
Fill = true,
|
|
||||||
PointRadius = 3,
|
|
||||||
CubicInterpolationMode = "monotone",
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
List<string> labels = new List<string>();
|
|
||||||
|
|
||||||
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);
|
|
||||||
|
|
||||||
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>();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -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,6 +2,14 @@
|
|||||||
@using Blazorise.Components;
|
@using Blazorise.Components;
|
||||||
@using Elektrifikatsiya.Models;
|
@using Elektrifikatsiya.Models;
|
||||||
@using System.Net
|
@using System.Net
|
||||||
|
@using System.Text.Json
|
||||||
|
@using Elektrifikatsiya.Services.Implementations
|
||||||
|
@using Elektrifikatsiya.Services;
|
||||||
|
@using FluentResults
|
||||||
|
|
||||||
|
@inject IDeviceManagmentService DeviceManagmentService
|
||||||
|
@inject IMessageService MessageService
|
||||||
|
|
||||||
<Div>
|
<Div>
|
||||||
<Row Style="width: 100%; height: 100%" Margin="Margin.Is3.FromTop.OnMobile" Padding="Padding.Is4.FromStart.OnMobile">
|
<Row Style="width: 100%; height: 100%" Margin="Margin.Is3.FromTop.OnMobile" Padding="Padding.Is4.FromStart.OnMobile">
|
||||||
<Div Display="Display.Flex.Row.OnDesktop" Margin=" Margin.Is3.FromBottom" Width="Width.Is100">
|
<Div Display="Display.Flex.Row.OnDesktop" Margin=" Margin.Is3.FromBottom" Width="Width.Is100">
|
||||||
@@ -34,7 +42,7 @@
|
|||||||
</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>
|
||||||
@@ -43,14 +51,14 @@
|
|||||||
|
|
||||||
<Column ColumnSize="ColumnSize.Is4.OnDesktop.Is7.OnMobile">
|
<Column ColumnSize="ColumnSize.Is4.OnDesktop.Is7.OnMobile">
|
||||||
<Button Position="Position.Absolute.Top.Is50.Start.Is50.Translate.Middle" Color="Color.Dark" Outline>
|
<Button Position="Position.Absolute.Top.Is50.Start.Is50.Translate.Middle" Color="Color.Dark" Outline>
|
||||||
<BarIcon IconName="IconName.Delete" />
|
<BarIcon @onclick="() => Delete(context.Item)" IconName="IconName.Delete" />
|
||||||
</Button>
|
</Button>
|
||||||
</Column>
|
</Column>
|
||||||
<br />
|
<br />
|
||||||
<br />
|
<br />
|
||||||
<Row>
|
<Row>
|
||||||
<Column ColumnSize="ColumnSize.Is1.OnDesktop">
|
<Column ColumnSize="ColumnSize.Is1.OnDesktop">
|
||||||
<Button @onclick="Toggle" Position="Position.Absolute.Top.Is50.Start.Is100.Translate.Middle" Color="Color.Dark" Outline>
|
<Button @onclick="() => Toggle(context.Item)" Position="Position.Absolute.Top.Is50.Start.Is100.Translate.Middle" Color="Color.Dark" Outline>
|
||||||
<BarIcon IconName="IconName.Pen" />
|
<BarIcon IconName="IconName.Pen" />
|
||||||
</Button>
|
</Button>
|
||||||
</Column>
|
</Column>
|
||||||
@@ -62,6 +70,9 @@
|
|||||||
</ListView>
|
</ListView>
|
||||||
</Column>
|
</Column>
|
||||||
<Column ColumnSize="ColumnSize.Is6.OnDesktop.Is12.OnMobile" Margin="Margin.Is3.FromTop.OnMobile" Padding="Padding.Is4.FromStart.OnMobile">
|
<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">
|
<Div hidden="@hideButtonSettings">
|
||||||
<Field>
|
<Field>
|
||||||
<FieldLabel>
|
<FieldLabel>
|
||||||
@@ -79,7 +90,7 @@
|
|||||||
Here you can change the name of your plug
|
Here you can change the name of your plug
|
||||||
</Paragraph>
|
</Paragraph>
|
||||||
</FieldLabel>
|
</FieldLabel>
|
||||||
<TextEdit Placeholder="Enter Name" />
|
<TextEdit @bind-Text="@DeviceCopy.Name" Placeholder="Enter Name" />
|
||||||
</Field>
|
</Field>
|
||||||
<br />
|
<br />
|
||||||
<br />
|
<br />
|
||||||
@@ -93,6 +104,7 @@
|
|||||||
</Paragraph>
|
</Paragraph>
|
||||||
</FieldLabel>
|
</FieldLabel>
|
||||||
<TextEdit Placeholder="Enter Max Output" />
|
<TextEdit Placeholder="Enter Max Output" />
|
||||||
|
<!--TODO: What is this?-->
|
||||||
</Field>
|
</Field>
|
||||||
<br />
|
<br />
|
||||||
<br />
|
<br />
|
||||||
@@ -105,19 +117,10 @@
|
|||||||
Here you select or change the room the plug belongs to.
|
Here you select or change the room the plug belongs to.
|
||||||
</Paragraph>
|
</Paragraph>
|
||||||
</FieldLabel>
|
</FieldLabel>
|
||||||
<br />
|
<TextEdit @bind-text="@DeviceCopy.Room" Placeholder="Enter the name of the room here"/>
|
||||||
<Dropdown Display="Display.InlineBlock">
|
|
||||||
<DropdownToggle Color="Color.Primary" Width="Width.Is100">Rooms</DropdownToggle>
|
|
||||||
<DropdownMenu>
|
|
||||||
<DropdownItem>Room 1</DropdownItem>
|
|
||||||
<DropdownDivider />
|
|
||||||
<DropdownItem>Room 2</DropdownItem>
|
|
||||||
<DropdownDivider />
|
|
||||||
<DropdownItem>Room 3</DropdownItem>
|
|
||||||
</DropdownMenu>
|
|
||||||
</Dropdown>
|
|
||||||
</Field>
|
</Field>
|
||||||
</Div>
|
</Div>
|
||||||
|
}
|
||||||
<Div hidden="@(!hideButtonSettings)">
|
<Div hidden="@(!hideButtonSettings)">
|
||||||
<Field>
|
<Field>
|
||||||
<FieldLabel>
|
<FieldLabel>
|
||||||
@@ -139,20 +142,68 @@
|
|||||||
</Field>
|
</Field>
|
||||||
</Div>
|
</Div>
|
||||||
<Column ColumnSize="ColumnSize.IsFull" TextAlignment="TextAlignment.End">
|
<Column ColumnSize="ColumnSize.IsFull" TextAlignment="TextAlignment.End">
|
||||||
<Button Color="Color.Primary">Save</Button>
|
<Button @onclick="OnSave" Color="Color.Primary">Save</Button>
|
||||||
</Column>
|
</Column>
|
||||||
</Column>
|
</Column>
|
||||||
</Div>
|
</Div>
|
||||||
</Row>
|
</Row>
|
||||||
</Div>
|
</Div>
|
||||||
|
|
||||||
|
|
||||||
@code {
|
@code {
|
||||||
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>();
|
||||||
|
|
||||||
private bool hideButtonSettings = true;
|
private bool hideButtonSettings = true;
|
||||||
|
|
||||||
private void Toggle()
|
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;
|
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,6 +21,19 @@ 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>();
|
||||||
@@ -27,7 +43,7 @@ builder.Services.AddBootstrapProviders();
|
|||||||
builder.Services.AddHttpClient<IDeviceManagmentService, DeviceManagmentService>();
|
builder.Services.AddHttpClient<IDeviceManagmentService, DeviceManagmentService>();
|
||||||
builder.Services.AddBlazorise(options =>
|
builder.Services.AddBlazorise(options =>
|
||||||
{
|
{
|
||||||
options.Immediate = true;
|
options.Immediate = true;
|
||||||
});
|
});
|
||||||
|
|
||||||
AddBlazorise(builder.Services);
|
AddBlazorise(builder.Services);
|
||||||
@@ -37,9 +53,9 @@ WebApplication app = builder.Build();
|
|||||||
// Configure the HTTP request pipeline.
|
// Configure the HTTP request pipeline.
|
||||||
if (!app.Environment.IsDevelopment())
|
if (!app.Environment.IsDevelopment())
|
||||||
{
|
{
|
||||||
_ = app.UseExceptionHandler("/Error");
|
_ = app.UseExceptionHandler("/Error");
|
||||||
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
|
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
|
||||||
_ = app.UseHsts();
|
_ = app.UseHsts();
|
||||||
}
|
}
|
||||||
|
|
||||||
app.UseHttpsRedirection();
|
app.UseHttpsRedirection();
|
||||||
@@ -60,14 +76,14 @@ IAuthenticationService authenticationService = serviceScope.ServiceProvider.GetR
|
|||||||
|
|
||||||
if (!mainDatabase.Users.Any())
|
if (!mainDatabase.Users.Any())
|
||||||
{
|
{
|
||||||
authenticationService.RegisterUserAsync("admin", "admin", Role.Admin);
|
_ = authenticationService.RegisterUserAsync("admin", "admin", Role.Admin);
|
||||||
}
|
}
|
||||||
|
|
||||||
app.Run();
|
app.Run();
|
||||||
|
|
||||||
void AddBlazorise(IServiceCollection services)
|
void AddBlazorise(IServiceCollection services)
|
||||||
{
|
{
|
||||||
_ = services.AddBlazorise();
|
_ = services.AddBlazorise();
|
||||||
_ = services.AddMaterialProviders();
|
_ = services.AddMaterialProviders();
|
||||||
_ = services.AddMaterialIcons();
|
_ = services.AddMaterialIcons();
|
||||||
}
|
}
|
||||||
+20
-5
@@ -3,9 +3,13 @@ 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;
|
||||||
using Microsoft.EntityFrameworkCore;
|
|
||||||
|
|
||||||
namespace Elektrifikatsiya.Services.Implementations;
|
namespace Elektrifikatsiya.Services.Implementations;
|
||||||
|
|
||||||
@@ -14,13 +18,15 @@ public class DeviceManagmentService : IDeviceManagmentService
|
|||||||
private readonly IServiceScopeFactory serviceScopeFactory;
|
private readonly IServiceScopeFactory serviceScopeFactory;
|
||||||
private readonly IDeviceStatusService deviceStatusService;
|
private readonly IDeviceStatusService deviceStatusService;
|
||||||
private readonly ILogger<DeviceManagmentService> logger;
|
private readonly ILogger<DeviceManagmentService> logger;
|
||||||
|
private readonly IHiveMQClient hiveMQClient;
|
||||||
private readonly HttpClient httpClient;
|
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.hiveMQClient = hiveMQClient;
|
||||||
this.httpClient = httpClient;
|
this.httpClient = httpClient;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -151,13 +157,22 @@ public class DeviceManagmentService : IDeviceManagmentService
|
|||||||
using IServiceScope scope = serviceScopeFactory.CreateScope();
|
using IServiceScope scope = serviceScopeFactory.CreateScope();
|
||||||
MainDatabaseContext mainDatabaseContext = scope.ServiceProvider.GetRequiredService<MainDatabaseContext>();
|
MainDatabaseContext mainDatabaseContext = scope.ServiceProvider.GetRequiredService<MainDatabaseContext>();
|
||||||
|
|
||||||
Result result = deviceStatusService.UpdateDeviceStatus(device);
|
Result<Device> getDeviceResult = GetDevice(device.MacAddress);
|
||||||
|
|
||||||
if (result.IsFailed)
|
if (getDeviceResult.IsFailed)
|
||||||
{
|
{
|
||||||
return result;
|
return getDeviceResult.ToResult();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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);
|
_ = mainDatabaseContext.Update(device);
|
||||||
|
|
||||||
return await Result.Try(Task () => mainDatabaseContext.SaveChangesAsync());
|
return await Result.Try(Task () => mainDatabaseContext.SaveChangesAsync());
|
||||||
|
|||||||
+6
-4
@@ -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,6 +1,7 @@
|
|||||||
using Elektrifikatsiya.Database;
|
using Elektrifikatsiya.Database;
|
||||||
using Elektrifikatsiya.Models;
|
using Elektrifikatsiya.Models;
|
||||||
using Elektrifikatsiya.Utilities;
|
using Elektrifikatsiya.Utilities;
|
||||||
|
|
||||||
using FluentResults;
|
using FluentResults;
|
||||||
|
|
||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
@@ -9,75 +10,77 @@ namespace Elektrifikatsiya.Services.Implementations;
|
|||||||
|
|
||||||
public class UpdateService : IHostedService, IDisposable
|
public class UpdateService : IHostedService, IDisposable
|
||||||
{
|
{
|
||||||
private readonly ILogger<UpdateService> logger;
|
private readonly ILogger<UpdateService> logger;
|
||||||
private readonly IDeviceStatusService deviceStatusService;
|
private readonly IDeviceStatusService deviceStatusService;
|
||||||
private readonly IServiceScopeFactory serviceScopeFactory;
|
private readonly IServiceScopeFactory serviceScopeFactory;
|
||||||
private Timer? timer = null;
|
private Timer? timer = null;
|
||||||
|
|
||||||
public UpdateService(ILogger<UpdateService> logger, IDeviceStatusService deviceStatusService, IServiceScopeFactory serviceScopeFactory)
|
public UpdateService(ILogger<UpdateService> logger, IDeviceStatusService deviceStatusService, IServiceScopeFactory serviceScopeFactory)
|
||||||
{
|
{
|
||||||
this.logger = logger;
|
this.logger = logger;
|
||||||
this.deviceStatusService = deviceStatusService;
|
this.deviceStatusService = deviceStatusService;
|
||||||
this.serviceScopeFactory = serviceScopeFactory;
|
this.serviceScopeFactory = serviceScopeFactory;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task StartAsync(CancellationToken cancellationToken)
|
public async Task StartAsync(CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
IServiceScope serviceScope = serviceScopeFactory.CreateScope();
|
IServiceScope serviceScope = serviceScopeFactory.CreateScope();
|
||||||
MainDatabaseContext mainDatabaseContext = serviceScope.ServiceProvider.GetRequiredService<MainDatabaseContext>();
|
MainDatabaseContext mainDatabaseContext = serviceScope.ServiceProvider.GetRequiredService<MainDatabaseContext>();
|
||||||
|
|
||||||
logger.LogInformation("Starting update service...");
|
logger.LogInformation("Starting update service...");
|
||||||
|
|
||||||
foreach (Device device in await mainDatabaseContext.Devices.Include(d=>d.User).AsNoTracking().ToListAsync(cancellationToken))
|
foreach (Device device in await mainDatabaseContext.Devices.Include(d => d.User).AsNoTracking().ToListAsync(cancellationToken))
|
||||||
{
|
{
|
||||||
_ = deviceStatusService.TrackDevice(device);
|
_ = deviceStatusService.TrackDevice(device);
|
||||||
}
|
}
|
||||||
|
|
||||||
timer = new Timer((_) => Update(), null, TimeSpan.Zero, TimeSpan.FromSeconds(15));
|
timer = new Timer(async (_) => await Update(), null, TimeSpan.Zero, TimeSpan.FromSeconds(15));
|
||||||
|
|
||||||
logger.LogInformation("Update service started.");
|
logger.LogInformation("Update service started.");
|
||||||
}
|
}
|
||||||
|
|
||||||
private async void Update()
|
private async Task Update()
|
||||||
{
|
{
|
||||||
Result<List<Device>> getDeviceStatusResult = deviceStatusService.GetDevices();
|
Result<List<Device>> getDeviceStatusResult = deviceStatusService.GetDevices();
|
||||||
|
|
||||||
if (getDeviceStatusResult.IsFailed)
|
if (getDeviceStatusResult.IsFailed)
|
||||||
{
|
{
|
||||||
logger.LogError("Updating devices failed!");
|
logger.LogError("Updating devices failed!");
|
||||||
}
|
}
|
||||||
PrometheusQuery promQueryer = new PrometheusQuery("http://localhost:9090");
|
PrometheusQuery promQueryer = new PrometheusQuery("http://localhost:9090");
|
||||||
foreach (Device device in getDeviceStatusResult.Value)
|
foreach (Device device in getDeviceStatusResult.Value)
|
||||||
{
|
{
|
||||||
PrometheusDataWrapper? deviceData = (await promQueryer.Query($"power{{sensor=\"shellyplug-s-{device.MacAddress}/relay/0\"}}"))?.Data;
|
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 (deviceData is not null)
|
if (devicePowerData is not null && deviceStatusData is not null)
|
||||||
{
|
{
|
||||||
device.PowerUsage = deviceData.VectorTypeToTimestampFloatTuple()?.ValueOrDefault.Item2 ?? 0;
|
device.PowerUsage = devicePowerData.VectorTypeToTimestampFloatTuple()?.ValueOrDefault.Item2 ?? 0;
|
||||||
deviceStatusService.UpdateDeviceStatus(device);
|
device.Enabled = (deviceStatusData.VectorTypeToTimestampFloatTuple()?.ValueOrDefault.Item2 ?? 0) == 1;
|
||||||
|
_ = deviceStatusService.UpdateDeviceStatus(device);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public Task StopAsync(CancellationToken cancellationToken)
|
public Task StopAsync(CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
logger.LogInformation("Stopping update service.");
|
logger.LogInformation("Stopping update service.");
|
||||||
|
|
||||||
_ = timer?.Change(Timeout.Infinite, 0);
|
_ = timer?.Change(Timeout.Infinite, 0);
|
||||||
|
|
||||||
logger.LogInformation("Stopped update service.");
|
logger.LogInformation("Stopped update service.");
|
||||||
|
|
||||||
return Task.CompletedTask;
|
return Task.CompletedTask;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void Dispose()
|
public void Dispose()
|
||||||
{
|
{
|
||||||
Dispose(true);
|
Dispose(true);
|
||||||
GC.SuppressFinalize(this);
|
GC.SuppressFinalize(this);
|
||||||
}
|
}
|
||||||
|
|
||||||
protected virtual void Dispose(bool disposing)
|
protected virtual void Dispose(bool disposing)
|
||||||
{
|
{
|
||||||
timer?.Dispose();
|
timer?.Dispose();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Binary file not shown.
@@ -10,18 +10,15 @@ 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)
|
||||||
{
|
{
|
||||||
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()
|
return client.GetFromJsonAsync<PrometheusQueryResult>($"/api/v1/query?query={UrlEncoder.Create().Encode(query)}", new JsonSerializerOptions()
|
||||||
{
|
{
|
||||||
PropertyNameCaseInsensitive = true,
|
PropertyNameCaseInsensitive = true,
|
||||||
|
|||||||
Reference in New Issue
Block a user