diff --git a/src/Elektrifikatsiya/Elektrifikatsiya/Elektrifikatsiya.csproj b/src/Elektrifikatsiya/Elektrifikatsiya/Elektrifikatsiya.csproj index 72696db..89ebdd6 100644 --- a/src/Elektrifikatsiya/Elektrifikatsiya/Elektrifikatsiya.csproj +++ b/src/Elektrifikatsiya/Elektrifikatsiya/Elektrifikatsiya.csproj @@ -42,6 +42,7 @@ + diff --git a/src/Elektrifikatsiya/Elektrifikatsiya/Models/Device.cs b/src/Elektrifikatsiya/Elektrifikatsiya/Models/Device.cs index 86c3d8c..000e5ef 100644 --- a/src/Elektrifikatsiya/Elektrifikatsiya/Models/Device.cs +++ b/src/Elektrifikatsiya/Elektrifikatsiya/Models/Device.cs @@ -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() + { } } \ No newline at end of file diff --git a/src/Elektrifikatsiya/Elektrifikatsiya/Pages/Dashboard.razor b/src/Elektrifikatsiya/Elektrifikatsiya/Pages/Dashboard.razor index 70a9522..66a3051 100644 --- a/src/Elektrifikatsiya/Elektrifikatsiya/Pages/Dashboard.razor +++ b/src/Elektrifikatsiya/Elektrifikatsiya/Pages/Dashboard.razor @@ -9,168 +9,88 @@ @inject IVersionProvider VersionProvider @inject IDeviceStatusService DeviceStatusService; +@inject IDeviceManagmentService DeviceManagmentService; - - - - - - Plugs - - - - - - - - - - @context.Item.Name - - - - - User: @context.Item.User.Name - - Room: @context.Item.Room - - - @context.Item.PowerUsage W - - - - - - - - - - - - - - - - - - Logs - - - - - - @context.Item.EventName - @context.Item.Date - - @context.Item.Description - - - - - - - - Aktualisieren - - - + + + + + + Plugs + + + + + + + + + + @context.Item.Name + + + + + User: @context.Item.User.Name + + Room: @context.Item.Room + + + @context.Item.PowerUsage W + + + + + + + + + + + + + + + + + Logs + + + + + + @context.Item.EventName + @context.Item.Date + + @context.Item.Description + + + + + + + + Aktualisieren + + + - - -@code { - //TODO: insert new event here if plug produces one - List events = new List() { 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 plugs = new List(); - //code for graph - LineChart lineChart; - - protected override void OnInitialized() - { - plugs = DeviceStatusService.GetDevices().ValueOrDefault ?? new List(); - - 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> GetLineChartDataset() - { - return new LineChartDataset - { - Label = "Wattage", - Data = await RandomizeData(), - Fill = true, - PointRadius = 3, - CubicInterpolationMode = "monotone", - }; - } - - List labels = new List(); - - async Task> 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(); - } -} \ No newline at end of file diff --git a/src/Elektrifikatsiya/Elektrifikatsiya/Pages/Dashboard.razor.cs b/src/Elektrifikatsiya/Elektrifikatsiya/Pages/Dashboard.razor.cs index fa4bbf2..3d70f26 100644 --- a/src/Elektrifikatsiya/Elektrifikatsiya/Pages/Dashboard.razor.cs +++ b/src/Elektrifikatsiya/Elektrifikatsiya/Pages/Dashboard.razor.cs @@ -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 events = new List() { 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 plugs = new List(); + + //code for graph + private LineChart lineChart; + + protected override void OnInitialized() + { + plugs = DeviceStatusService.GetDevices().ValueOrDefault ?? new List(); + + 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> GetLineChartDataset() + { + return new LineChartDataset + { + Label = "Wattage", + Data = await DeviceData(), + Fill = true, + PointRadius = 3, + CubicInterpolationMode = "monotone", + }; + } + + private readonly List labels = new List(); + + private async Task> 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(); } } \ No newline at end of file diff --git a/src/Elektrifikatsiya/Elektrifikatsiya/Pages/Settings.razor b/src/Elektrifikatsiya/Elektrifikatsiya/Pages/Settings.razor index b4afa9f..263b2af 100644 --- a/src/Elektrifikatsiya/Elektrifikatsiya/Pages/Settings.razor +++ b/src/Elektrifikatsiya/Elektrifikatsiya/Pages/Settings.razor @@ -172,7 +172,7 @@ { hideButtonSettings = !hideButtonSettings; SelectedDevice = device; - DeviceCopy = Device.CopyDevice(device); + DeviceCopy = device.CopyDevice(); } private void OnSave() diff --git a/src/Elektrifikatsiya/Elektrifikatsiya/Program.cs b/src/Elektrifikatsiya/Elektrifikatsiya/Program.cs index 02d9c9d..6615bf5 100644 --- a/src/Elektrifikatsiya/Elektrifikatsiya/Program.cs +++ b/src/Elektrifikatsiya/Elektrifikatsiya/Program.cs @@ -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(); builder.Services.AddSingleton(); +builder.Services.AddSingleton((provider)=> +{ + HiveMQClientOptions options = new() + { + Host = "localhost", + Port = 1883, + UseTLS = false, + }; + + HiveMQClient client = new(options); + client.ConnectAsync().ConfigureAwait(false); + return client; +}); builder.Services.AddTransient(); builder.Services.AddScoped(); builder.Services.AddScoped(); @@ -27,7 +43,7 @@ builder.Services.AddBootstrapProviders(); builder.Services.AddHttpClient(); 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(); } \ No newline at end of file diff --git a/src/Elektrifikatsiya/Elektrifikatsiya/Services/Implementations/DeviceManagmentService.cs b/src/Elektrifikatsiya/Elektrifikatsiya/Services/Implementations/DeviceManagmentService.cs index 3343c76..12e4bb1 100644 --- a/src/Elektrifikatsiya/Elektrifikatsiya/Services/Implementations/DeviceManagmentService.cs +++ b/src/Elektrifikatsiya/Elektrifikatsiya/Services/Implementations/DeviceManagmentService.cs @@ -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 logger; + private readonly IHiveMQClient hiveMQClient; private readonly HttpClient httpClient; - public DeviceManagmentService(IServiceScopeFactory serviceScopeFactory, IDeviceStatusService deviceStatusService, ILogger logger, HttpClient httpClient) + public DeviceManagmentService(IServiceScopeFactory serviceScopeFactory, IDeviceStatusService deviceStatusService, ILogger 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(); - Result result = deviceStatusService.UpdateDeviceStatus(device); + Result 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()); diff --git a/src/Elektrifikatsiya/Elektrifikatsiya/Services/Implementations/DeviceStatusService.cs b/src/Elektrifikatsiya/Elektrifikatsiya/Services/Implementations/DeviceStatusService.cs index 2e6e904..becc6f4 100644 --- a/src/Elektrifikatsiya/Elektrifikatsiya/Services/Implementations/DeviceStatusService.cs +++ b/src/Elektrifikatsiya/Elektrifikatsiya/Services/Implementations/DeviceStatusService.cs @@ -6,15 +6,17 @@ namespace Elektrifikatsiya.Services.Implementations; public class DeviceStatusService : IDeviceStatusService { - private readonly ILogger logger; - public event EventHandler? OnDeviceStatusChanged; + private readonly ILogger logger; + + public event EventHandler? OnDeviceStatusChanged; private readonly Dictionary devices = new(); - + public DeviceStatusService(ILogger logger) { - this.logger = logger; + this.logger = logger; } + public Result> 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; diff --git a/src/Elektrifikatsiya/Elektrifikatsiya/Services/Implementations/UpdateService.cs b/src/Elektrifikatsiya/Elektrifikatsiya/Services/Implementations/UpdateService.cs index f31d184..0a3ef4a 100644 --- a/src/Elektrifikatsiya/Elektrifikatsiya/Services/Implementations/UpdateService.cs +++ b/src/Elektrifikatsiya/Elektrifikatsiya/Services/Implementations/UpdateService.cs @@ -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 logger; - private readonly IDeviceStatusService deviceStatusService; - private readonly IServiceScopeFactory serviceScopeFactory; - private Timer? timer = null; + private readonly ILogger logger; + private readonly IDeviceStatusService deviceStatusService; + private readonly IServiceScopeFactory serviceScopeFactory; + private Timer? timer = null; - public UpdateService(ILogger logger, IDeviceStatusService deviceStatusService, IServiceScopeFactory serviceScopeFactory) - { - this.logger = logger; - this.deviceStatusService = deviceStatusService; - this.serviceScopeFactory = serviceScopeFactory; - } + public UpdateService(ILogger 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(); + public async Task StartAsync(CancellationToken cancellationToken) + { + IServiceScope serviceScope = serviceScopeFactory.CreateScope(); + MainDatabaseContext mainDatabaseContext = serviceScope.ServiceProvider.GetRequiredService(); - 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> getDeviceStatusResult = deviceStatusService.GetDevices(); + private async Task Update() + { + Result> 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(); + } } \ No newline at end of file