mirror of
https://github.com/Stefan-5422/-T5-Elektrifikatsiya.git
synced 2026-09-04 00:45:58 +02:00
Turn on and off button thingy
This commit is contained in:
@@ -42,6 +42,7 @@
|
||||
<PackageReference Include="Blazorise.Icons.Material" Version="1.2.0" />
|
||||
<PackageReference Include="BCrypt.Net-Next" Version="4.0.3" />
|
||||
<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.Sqlite" Version="7.0.4" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="7.0.4">
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
using System.Net;
|
||||
using Microsoft.AspNetCore.Razor.TagHelpers;
|
||||
using Microsoft.AspNetCore.Server.IIS.Core;
|
||||
|
||||
namespace Elektrifikatsiya.Models;
|
||||
|
||||
@@ -26,7 +24,7 @@ public class Device
|
||||
public string Room { get; set; }
|
||||
|
||||
[NotMapped]
|
||||
public bool Available { get; set; }
|
||||
public bool Enabled { get; set; }
|
||||
|
||||
public Device(string macAddress, string name, IPAddress address, User user, string room)
|
||||
{
|
||||
@@ -37,17 +35,22 @@ public class Device
|
||||
Room = room;
|
||||
}
|
||||
|
||||
public static Device CopyDevice(Device device) => new Device(device.MacAddress, device.Name, device.IpAddress, device.User, device.Room);
|
||||
public Device CopyDevice()
|
||||
{
|
||||
return new Device(MacAddress, Name, IpAddress, User, Room);
|
||||
}
|
||||
|
||||
public void OverwiteDevice(Device overwriter)
|
||||
{
|
||||
this.Room = overwriter.Room;
|
||||
this.Available = overwriter.Available;
|
||||
this.PowerUsage = overwriter.PowerUsage;
|
||||
this.Name = overwriter.Name;
|
||||
this.User = overwriter.User;
|
||||
this.MacAddress = overwriter.MacAddress;
|
||||
this.IpAddress = overwriter.IpAddress;
|
||||
Room = overwriter.Room;
|
||||
Enabled = overwriter.Enabled;
|
||||
PowerUsage = overwriter.PowerUsage;
|
||||
Name = overwriter.Name;
|
||||
User = overwriter.User;
|
||||
MacAddress = overwriter.MacAddress;
|
||||
IpAddress = overwriter.IpAddress;
|
||||
}
|
||||
private Device(){}
|
||||
|
||||
private Device()
|
||||
{ }
|
||||
}
|
||||
@@ -9,168 +9,88 @@
|
||||
@inject IVersionProvider VersionProvider
|
||||
|
||||
@inject IDeviceStatusService DeviceStatusService;
|
||||
@inject IDeviceManagmentService DeviceManagmentService;
|
||||
|
||||
<Div>
|
||||
<Row Padding="Padding.Is3">
|
||||
<Div Display="Display.Flex.Row.OnDesktop" Margin=" Margin.Is3.FromBottom" Width="Width.Is100">
|
||||
<Column ColumnSize="ColumnSize.Is6.OnDesktop.Is12">
|
||||
<Bar Breakpoint="Breakpoint.Desktop"
|
||||
Background="Background.White"
|
||||
ThemeContrast="ThemeContrast.None"
|
||||
Shadow="Shadow.Remove"
|
||||
Border="Border.Is1.RoundedTop">
|
||||
<BarBrand>
|
||||
Plugs
|
||||
</BarBrand>
|
||||
</Bar>
|
||||
<ListView TItem="Device"
|
||||
Data="@plugs"
|
||||
TextField="@((_)=>(""))"
|
||||
ValueField="@((_)=>(""))"
|
||||
Mode="ListGroupMode.Static"
|
||||
Style="border-radius: 0px 0px">
|
||||
<ItemTemplate >
|
||||
<ListGroupItem>
|
||||
<Row>
|
||||
<Column ColumnSize="ColumnSize.Is8">
|
||||
<Row>
|
||||
<Column ColumnSize="ColumnSize.Is7">
|
||||
<Heading Size="HeadingSize.Is6" Margin="Margin.Is1.FromBottom">@context.Item.Name</Heading>
|
||||
</Column>
|
||||
</Row>
|
||||
<Row>
|
||||
<Column>
|
||||
<Small>User: @context.Item.User.Name</Small>
|
||||
<br />
|
||||
<Small>Room: @context.Item.Room</Small>
|
||||
</Column>
|
||||
<Column ColumnSize="ColumnSize.Is5">
|
||||
<Paragraph Margin="Margin.Is1.OnY">@context.Item.PowerUsage W</Paragraph>
|
||||
</Column>
|
||||
</Row>
|
||||
</Column>
|
||||
<Column ColumnSize="ColumnSize.Is4">
|
||||
<Button Position="Position.Absolute.Top.Is50.Start.Is50.Translate.Middle" Color="Color.Primary"Primary Outline>
|
||||
<!--TODO: This button should change color-->
|
||||
<BarIcon IconName="IconName.Bolt" />
|
||||
</Button>
|
||||
</Column>
|
||||
</Row>
|
||||
</ListGroupItem>
|
||||
</ItemTemplate>
|
||||
</ListView>
|
||||
</Column>
|
||||
<Column ColumnSize="ColumnSize.Is6.OnDesktop.Is12">
|
||||
<Bar Breakpoint="Breakpoint.Desktop"
|
||||
Background="Background.White"
|
||||
ThemeContrast="ThemeContrast.None"
|
||||
Shadow="Shadow.Remove"
|
||||
Border="Border.Is1.Rounded.RoundedTop">
|
||||
<BarBrand>
|
||||
Logs
|
||||
</BarBrand>
|
||||
</Bar>
|
||||
<ListView TItem="Event"
|
||||
Data="@events"
|
||||
TextField="@((_)=>(""))"
|
||||
ValueField="@((_)=>(""))"
|
||||
Mode="ListGroupMode.Static"
|
||||
Style="border-radius: 0px 0px">
|
||||
<ItemTemplate>
|
||||
<Div Flex="Flex.InlineFlex.JustifyContent.Between" Width="Width.Is100">
|
||||
<Heading Size="HeadingSize.Is6" Margin="Margin.Is2.FromBottom">@context.Item.EventName</Heading>
|
||||
<Small>@context.Item.Date</Small>
|
||||
</Div>
|
||||
<Paragraph Margin="Margin.Is2.FromBottom">@context.Item.Description</Paragraph>
|
||||
</ItemTemplate>
|
||||
</ListView>
|
||||
</Column>
|
||||
</Div>
|
||||
</Row>
|
||||
<Row Padding="Padding.Is3">
|
||||
<Column>
|
||||
<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" />
|
||||
</Column>
|
||||
</Row>
|
||||
<Row Padding="Padding.Is3">
|
||||
<Div Display="Display.Flex.Row.OnDesktop" Margin=" Margin.Is3.FromBottom" Width="Width.Is100">
|
||||
<Column ColumnSize="ColumnSize.Is6.OnDesktop.Is12">
|
||||
<Bar Breakpoint="Breakpoint.Desktop"
|
||||
Background="Background.White"
|
||||
ThemeContrast="ThemeContrast.None"
|
||||
Shadow="Shadow.Remove"
|
||||
Border="Border.Is1.RoundedTop">
|
||||
<BarBrand>
|
||||
Plugs
|
||||
</BarBrand>
|
||||
</Bar>
|
||||
<ListView TItem="Device"
|
||||
Data="@plugs"
|
||||
TextField="@((_)=>(""))"
|
||||
ValueField="@((_)=>(""))"
|
||||
Mode="ListGroupMode.Static"
|
||||
Style="border-radius: 0px 0px">
|
||||
<ItemTemplate>
|
||||
<ListGroupItem>
|
||||
<Row>
|
||||
<Column ColumnSize="ColumnSize.Is8">
|
||||
<Row>
|
||||
<Column ColumnSize="ColumnSize.Is7">
|
||||
<Heading Size="HeadingSize.Is6" Margin="Margin.Is1.FromBottom">@context.Item.Name</Heading>
|
||||
</Column>
|
||||
</Row>
|
||||
<Row>
|
||||
<Column>
|
||||
<Small>User: @context.Item.User.Name</Small>
|
||||
<br />
|
||||
<Small>Room: @context.Item.Room</Small>
|
||||
</Column>
|
||||
<Column ColumnSize="ColumnSize.Is5">
|
||||
<Paragraph Margin="Margin.Is1.OnY">@context.Item.PowerUsage W</Paragraph>
|
||||
</Column>
|
||||
</Row>
|
||||
</Column>
|
||||
<Column ColumnSize="ColumnSize.Is4">
|
||||
<Button Clicked="() => Switch(context.Item)" Position="Position.Absolute.Top.Is50.Start.Is50.Translate.Middle" Color="Color.Primary" Primary Outline>
|
||||
<BarIcon TextColor="(context.Item.Enabled?TextColor.Success:TextColor.Danger)" IconName="IconName.Bolt" />
|
||||
</Button>
|
||||
</Column>
|
||||
</Row>
|
||||
</ListGroupItem>
|
||||
</ItemTemplate>
|
||||
</ListView>
|
||||
</Column>
|
||||
<Column ColumnSize="ColumnSize.Is6.OnDesktop.Is12">
|
||||
<Bar Breakpoint="Breakpoint.Desktop"
|
||||
Background="Background.White"
|
||||
ThemeContrast="ThemeContrast.None"
|
||||
Shadow="Shadow.Remove"
|
||||
Border="Border.Is1.Rounded.RoundedTop">
|
||||
<BarBrand>
|
||||
Logs
|
||||
</BarBrand>
|
||||
</Bar>
|
||||
<ListView TItem="Event"
|
||||
Data="@events"
|
||||
TextField="@((_)=>(""))"
|
||||
ValueField="@((_)=>(""))"
|
||||
Mode="ListGroupMode.Static"
|
||||
Style="border-radius: 0px 0px">
|
||||
<ItemTemplate>
|
||||
<Div Flex="Flex.InlineFlex.JustifyContent.Between" Width="Width.Is100">
|
||||
<Heading Size="HeadingSize.Is6" Margin="Margin.Is2.FromBottom">@context.Item.EventName</Heading>
|
||||
<Small>@context.Item.Date</Small>
|
||||
</Div>
|
||||
<Paragraph Margin="Margin.Is2.FromBottom">@context.Item.Description</Paragraph>
|
||||
</ItemTemplate>
|
||||
</ListView>
|
||||
</Column>
|
||||
</Div>
|
||||
</Row>
|
||||
<Row Padding="Padding.Is3">
|
||||
<Column>
|
||||
<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" />
|
||||
</Column>
|
||||
</Row>
|
||||
</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|";
|
||||
}
|
||||
|
||||
if(string.IsNullOrEmpty(plugnames))
|
||||
{
|
||||
return new();
|
||||
}
|
||||
|
||||
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 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;
|
||||
using Blazorise.Charts;
|
||||
|
||||
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>();
|
||||
}
|
||||
}
|
||||
@@ -172,7 +172,7 @@
|
||||
{
|
||||
hideButtonSettings = !hideButtonSettings;
|
||||
SelectedDevice = device;
|
||||
DeviceCopy = Device.CopyDevice(device);
|
||||
DeviceCopy = device.CopyDevice();
|
||||
}
|
||||
|
||||
private void OnSave()
|
||||
|
||||
@@ -8,6 +8,9 @@ using Elektrifikatsiya.Models;
|
||||
using Elektrifikatsiya.Services;
|
||||
using Elektrifikatsiya.Services.Implementations;
|
||||
|
||||
using HiveMQtt.Client;
|
||||
using HiveMQtt.Client.Options;
|
||||
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
|
||||
@@ -18,6 +21,19 @@ builder.Services.AddServerSideBlazor();
|
||||
builder.Services.AddHttpContextAccessor();
|
||||
builder.Services.AddHostedService<UpdateService>();
|
||||
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.AddScoped<IAuthenticationService, AuthenticationService>();
|
||||
builder.Services.AddScoped<IAuthorizationService, AuthorizationService>();
|
||||
@@ -27,7 +43,7 @@ builder.Services.AddBootstrapProviders();
|
||||
builder.Services.AddHttpClient<IDeviceManagmentService, DeviceManagmentService>();
|
||||
builder.Services.AddBlazorise(options =>
|
||||
{
|
||||
options.Immediate = true;
|
||||
options.Immediate = true;
|
||||
});
|
||||
|
||||
AddBlazorise(builder.Services);
|
||||
@@ -37,9 +53,9 @@ WebApplication app = builder.Build();
|
||||
// Configure the HTTP request pipeline.
|
||||
if (!app.Environment.IsDevelopment())
|
||||
{
|
||||
_ = 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.
|
||||
_ = app.UseHsts();
|
||||
_ = 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.
|
||||
_ = app.UseHsts();
|
||||
}
|
||||
|
||||
app.UseHttpsRedirection();
|
||||
@@ -60,14 +76,14 @@ IAuthenticationService authenticationService = serviceScope.ServiceProvider.GetR
|
||||
|
||||
if (!mainDatabase.Users.Any())
|
||||
{
|
||||
_ = authenticationService.RegisterUserAsync("admin", "admin", Role.Admin);
|
||||
_ = authenticationService.RegisterUserAsync("admin", "admin", Role.Admin);
|
||||
}
|
||||
|
||||
app.Run();
|
||||
|
||||
void AddBlazorise(IServiceCollection services)
|
||||
{
|
||||
_ = services.AddBlazorise();
|
||||
_ = services.AddMaterialProviders();
|
||||
_ = services.AddMaterialIcons();
|
||||
_ = services.AddBlazorise();
|
||||
_ = services.AddMaterialProviders();
|
||||
_ = services.AddMaterialIcons();
|
||||
}
|
||||
+20
-5
@@ -3,9 +3,13 @@ using Elektrifikatsiya.Models;
|
||||
|
||||
using FluentResults;
|
||||
|
||||
using HiveMQtt.Client;
|
||||
using HiveMQtt.Client.Results;
|
||||
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
using System.Net;
|
||||
using System.Net.NetworkInformation;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Elektrifikatsiya.Services.Implementations;
|
||||
|
||||
@@ -14,13 +18,15 @@ public class DeviceManagmentService : IDeviceManagmentService
|
||||
private readonly IServiceScopeFactory serviceScopeFactory;
|
||||
private readonly IDeviceStatusService deviceStatusService;
|
||||
private readonly ILogger<DeviceManagmentService> logger;
|
||||
private readonly IHiveMQClient hiveMQClient;
|
||||
private readonly HttpClient httpClient;
|
||||
|
||||
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.deviceStatusService = deviceStatusService;
|
||||
this.logger = logger;
|
||||
this.hiveMQClient = hiveMQClient;
|
||||
this.httpClient = httpClient;
|
||||
}
|
||||
|
||||
@@ -151,13 +157,22 @@ public class DeviceManagmentService : IDeviceManagmentService
|
||||
using IServiceScope scope = serviceScopeFactory.CreateScope();
|
||||
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);
|
||||
|
||||
return await Result.Try(Task () => mainDatabaseContext.SaveChangesAsync());
|
||||
|
||||
+7
-5
@@ -6,15 +6,17 @@ namespace Elektrifikatsiya.Services.Implementations;
|
||||
|
||||
public class DeviceStatusService : IDeviceStatusService
|
||||
{
|
||||
private readonly ILogger<DeviceStatusService> logger;
|
||||
public event EventHandler<DeviceStatusChagedEventArgs>? OnDeviceStatusChanged;
|
||||
private readonly ILogger<DeviceStatusService> logger;
|
||||
|
||||
public event EventHandler<DeviceStatusChagedEventArgs>? OnDeviceStatusChanged;
|
||||
|
||||
private readonly Dictionary<string, Device> devices = new();
|
||||
|
||||
|
||||
public DeviceStatusService(ILogger<DeviceStatusService> logger)
|
||||
{
|
||||
this.logger = logger;
|
||||
this.logger = logger;
|
||||
}
|
||||
|
||||
public Result<List<Device>> GetDevices()
|
||||
{
|
||||
return devices.Values.ToList();
|
||||
@@ -30,7 +32,7 @@ public class DeviceStatusService : IDeviceStatusService
|
||||
}
|
||||
|
||||
modDevice.PowerUsage = device.PowerUsage;
|
||||
modDevice.Available = device.Available;
|
||||
modDevice.Enabled = device.Enabled;
|
||||
modDevice.IpAddress = device.IpAddress;
|
||||
modDevice.Name = device.Name;
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
using Elektrifikatsiya.Database;
|
||||
using Elektrifikatsiya.Models;
|
||||
using Elektrifikatsiya.Utilities;
|
||||
|
||||
using FluentResults;
|
||||
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
@@ -9,75 +10,77 @@ namespace Elektrifikatsiya.Services.Implementations;
|
||||
|
||||
public class UpdateService : IHostedService, IDisposable
|
||||
{
|
||||
private readonly ILogger<UpdateService> logger;
|
||||
private readonly IDeviceStatusService deviceStatusService;
|
||||
private readonly IServiceScopeFactory serviceScopeFactory;
|
||||
private Timer? timer = null;
|
||||
private readonly ILogger<UpdateService> logger;
|
||||
private readonly IDeviceStatusService deviceStatusService;
|
||||
private readonly IServiceScopeFactory serviceScopeFactory;
|
||||
private Timer? timer = null;
|
||||
|
||||
public UpdateService(ILogger<UpdateService> logger, IDeviceStatusService deviceStatusService, IServiceScopeFactory serviceScopeFactory)
|
||||
{
|
||||
this.logger = logger;
|
||||
this.deviceStatusService = deviceStatusService;
|
||||
this.serviceScopeFactory = serviceScopeFactory;
|
||||
}
|
||||
public UpdateService(ILogger<UpdateService> logger, IDeviceStatusService deviceStatusService, IServiceScopeFactory serviceScopeFactory)
|
||||
{
|
||||
this.logger = logger;
|
||||
this.deviceStatusService = deviceStatusService;
|
||||
this.serviceScopeFactory = serviceScopeFactory;
|
||||
}
|
||||
|
||||
public async Task StartAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
IServiceScope serviceScope = serviceScopeFactory.CreateScope();
|
||||
MainDatabaseContext mainDatabaseContext = serviceScope.ServiceProvider.GetRequiredService<MainDatabaseContext>();
|
||||
public async Task StartAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
IServiceScope serviceScope = serviceScopeFactory.CreateScope();
|
||||
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))
|
||||
{
|
||||
_ = deviceStatusService.TrackDevice(device);
|
||||
}
|
||||
foreach (Device device in await mainDatabaseContext.Devices.Include(d => d.User).AsNoTracking().ToListAsync(cancellationToken))
|
||||
{
|
||||
_ = deviceStatusService.TrackDevice(device);
|
||||
}
|
||||
|
||||
timer = new Timer(async (_) => await 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 Task Update()
|
||||
{
|
||||
Result<List<Device>> getDeviceStatusResult = deviceStatusService.GetDevices();
|
||||
private async Task Update()
|
||||
{
|
||||
Result<List<Device>> getDeviceStatusResult = deviceStatusService.GetDevices();
|
||||
|
||||
if (getDeviceStatusResult.IsFailed)
|
||||
{
|
||||
logger.LogError("Updating devices failed!");
|
||||
}
|
||||
PrometheusQuery promQueryer = new PrometheusQuery("http://localhost:9090");
|
||||
foreach (Device device in getDeviceStatusResult.Value)
|
||||
{
|
||||
PrometheusDataWrapper? deviceData = (await promQueryer.Query($"power{{sensor=\"shellyplug-s-{device.MacAddress}/relay/0\"}}"))?.Data;
|
||||
if (getDeviceStatusResult.IsFailed)
|
||||
{
|
||||
logger.LogError("Updating devices failed!");
|
||||
}
|
||||
PrometheusQuery promQueryer = new PrometheusQuery("http://localhost:9090");
|
||||
foreach (Device device in getDeviceStatusResult.Value)
|
||||
{
|
||||
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)
|
||||
{
|
||||
device.PowerUsage = deviceData.VectorTypeToTimestampFloatTuple()?.ValueOrDefault.Item2 ?? 0;
|
||||
deviceStatusService.UpdateDeviceStatus(device);
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public Task StopAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
logger.LogInformation("Stopping update service.");
|
||||
public Task StopAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
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()
|
||||
{
|
||||
Dispose(true);
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
public void Dispose()
|
||||
{
|
||||
Dispose(true);
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
|
||||
protected virtual void Dispose(bool disposing)
|
||||
{
|
||||
timer?.Dispose();
|
||||
}
|
||||
protected virtual void Dispose(bool disposing)
|
||||
{
|
||||
timer?.Dispose();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user