diff --git a/CartriX.Server/Data/CartriXDbContext.cs b/CartriX.Server/Data/CartriXDbContext.cs new file mode 100644 index 0000000..1334bed --- /dev/null +++ b/CartriX.Server/Data/CartriXDbContext.cs @@ -0,0 +1,12 @@ +using CartriX.Share; +using Microsoft.EntityFrameworkCore; + +namespace CartriX.Server.Data; + +public class CartriXDbContext(DbContextOptions options) : DbContext(options) +{ + public DbSet Printers => Set(); + public DbSet Cartridges => Set(); + public DbSet CartridgeInstallations => Set(); + public DbSet PageCounterLogs => Set(); +} diff --git a/CartriX.Server/Program.cs b/CartriX.Server/Program.cs new file mode 100644 index 0000000..e8f1bdb --- /dev/null +++ b/CartriX.Server/Program.cs @@ -0,0 +1,63 @@ +using CartriX.Server.Data; +using CartriX.Server.Services; +using CartriX.Share; +using Microsoft.EntityFrameworkCore; + +var builder = WebApplication.CreateBuilder(args); + +builder.Services.AddDbContext(options => + options.UseSqlite(builder.Configuration.GetConnectionString("CartriX") ?? "Data Source=cartrix.db")); +builder.Services.AddGrpc(); +builder.Services.AddScoped(); + +var app = builder.Build(); + +using (var scope = app.Services.CreateScope()) +{ + var db = scope.ServiceProvider.GetRequiredService(); + db.Database.EnsureCreated(); +} + +app.MapGrpcService(); +app.MapGet("/", () => "CartriX.Server is running."); + +app.MapGet("/api/printers", async (CartriXDbContext db) => + await db.Printers.OrderBy(p => p.Name).ToListAsync()); + +app.MapPost("/api/printers", async (CreatePrinterRequest request, CartriXDbContext db) => +{ + var printer = new Printer + { + Name = request.Name, + Model = request.Model, + ConnectionType = request.ConnectionType, + Location = request.Location + }; + + db.Printers.Add(printer); + await db.SaveChangesAsync(); + return Results.Created($"/api/printers/{printer.Id}", printer); +}); + +app.MapGet("/api/cartridges", async (CartriXDbContext db) => + await db.Cartridges.OrderBy(c => c.Model).ToListAsync()); + +app.MapPost("/api/installations", async (CreateCartridgeInstallationRequest request, CartridgeLifecycleService lifecycle) => +{ + var installation = await lifecycle.StartInstallationAsync(request); + return Results.Created($"/api/installations/{installation.Id}", installation); +}); + +app.MapPost("/api/installations/{id:int}/remove", async (int id, int pageCounter, CartridgeLifecycleService lifecycle) => +{ + var closed = await lifecycle.CloseInstallationAsync(id, pageCounter); + return closed is null ? Results.NotFound() : Results.Ok(closed); +}); + +app.MapGet("/api/installations/active", async (CartriXDbContext db) => + await db.CartridgeInstallations + .Where(x => x.RemovedAtUtc == null) + .OrderByDescending(x => x.InstalledAtUtc) + .ToListAsync()); + +app.Run(); diff --git a/CartriX.Server/Services/CartridgeLifecycleService.cs b/CartriX.Server/Services/CartridgeLifecycleService.cs new file mode 100644 index 0000000..85c002a --- /dev/null +++ b/CartriX.Server/Services/CartridgeLifecycleService.cs @@ -0,0 +1,46 @@ +using CartriX.Server.Data; +using CartriX.Share; +using Microsoft.EntityFrameworkCore; + +namespace CartriX.Server.Services; + +public class CartridgeLifecycleService(CartriXDbContext db) +{ + public async Task StartInstallationAsync(CreateCartridgeInstallationRequest request) + { + var installation = new CartridgeInstallation + { + PrinterId = request.PrinterId, + CartridgeId = request.CartridgeId, + StartPageCounter = request.StartPageCounter, + InstalledAtUtc = DateTime.UtcNow + }; + + db.CartridgeInstallations.Add(installation); + await db.SaveChangesAsync(); + return installation; + } + + public async Task CloseInstallationAsync(int installationId, int endPageCounter) + { + var installation = await db.CartridgeInstallations.FirstOrDefaultAsync(x => x.Id == installationId); + if (installation is null || installation.RemovedAtUtc is not null) + { + return null; + } + + var cartridge = await db.Cartridges.FirstOrDefaultAsync(x => x.Id == installation.CartridgeId); + + installation.EndPageCounter = endPageCounter; + installation.RemovedAtUtc = DateTime.UtcNow; + installation.PrintedPages = Math.Max(0, endPageCounter - installation.StartPageCounter); + + if (cartridge is not null && installation.PrintedPages > 0) + { + installation.CostPerPage = Math.Round(cartridge.Price / installation.PrintedPages.Value, 4); + } + + await db.SaveChangesAsync(); + return installation; + } +} diff --git a/CartriX.Server/Services/PrinterMonitorGrpcService.cs b/CartriX.Server/Services/PrinterMonitorGrpcService.cs new file mode 100644 index 0000000..4757838 --- /dev/null +++ b/CartriX.Server/Services/PrinterMonitorGrpcService.cs @@ -0,0 +1,32 @@ +using CartriX.Server.Data; +using CartriX.Share; +using CartriX.Share.Grpc; +using Grpc.Core; + +namespace CartriX.Server.Services; + +public class PrinterMonitorGrpcService(CartriXDbContext db, ILogger logger) : PrinterMonitor.PrinterMonitorBase +{ + public override async Task SendStats(PrinterStatsRequest request, ServerCallContext context) + { + var log = new PageCounterLog + { + PrinterId = request.PrinterId, + TotalPages = request.PageCount, + TonerPercent = request.TonerPercent <= 0 ? null : request.TonerPercent, + CapturedAtUtc = DateTime.UtcNow, + Source = string.IsNullOrWhiteSpace(request.Source) ? "agent" : request.Source + }; + + db.PageCounterLogs.Add(log); + await db.SaveChangesAsync(context.CancellationToken); + + logger.LogInformation("Stats received for printer {PrinterId}: pages={PageCount}", request.PrinterId, request.PageCount); + + return new PrinterStatsResponse + { + Success = true, + Message = "ok" + }; + } +} diff --git a/CartriX.Service/CartriX.Service.csproj b/CartriX.Service/CartriX.Service.csproj index 808234a..f00f0c2 100644 --- a/CartriX.Service/CartriX.Service.csproj +++ b/CartriX.Service/CartriX.Service.csproj @@ -8,6 +8,21 @@ + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + diff --git a/CartriX.Service/Worker.cs b/CartriX.Service/Worker.cs index 3fec011..a98e471 100644 --- a/CartriX.Service/Worker.cs +++ b/CartriX.Service/Worker.cs @@ -1,16 +1,39 @@ +using CartriX.Share.Grpc; +using Grpc.Net.Client; + namespace CartriX.Service; public class Worker(ILogger logger) : BackgroundService { protected override async Task ExecuteAsync(CancellationToken stoppingToken) { + var serverAddress = "http://localhost:5054"; + var random = new Random(); + while (!stoppingToken.IsCancellationRequested) { - if (logger.IsEnabled(LogLevel.Information)) + try { - logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now); + using var channel = GrpcChannel.ForAddress(serverAddress); + var client = new PrinterMonitor.PrinterMonitorClient(channel); + + var response = await client.SendStatsAsync(new PrinterStatsRequest + { + PrinterId = 1, + PrinterName = "USB-Lab-01", + PageCount = random.Next(1000, 2000), + TonerPercent = random.Next(10, 100), + Source = "agent-usb" + }, cancellationToken: stoppingToken); + + logger.LogInformation("Agent sent stats: {Message}", response.Message); } - await Task.Delay(1000, stoppingToken); + catch (Exception ex) + { + logger.LogWarning(ex, "Agent cannot send stats to server yet."); + } + + await Task.Delay(TimeSpan.FromMinutes(5), stoppingToken); } } } diff --git a/CartriX.Share/Cartridge.cs b/CartriX.Share/Cartridge.cs new file mode 100644 index 0000000..a2f42a4 --- /dev/null +++ b/CartriX.Share/Cartridge.cs @@ -0,0 +1,9 @@ +namespace CartriX.Share; + +public class Cartridge +{ + public int Id { get; set; } + public string Model { get; set; } = string.Empty; + public decimal Price { get; set; } + public int ManufacturerDeclaredYield { get; set; } +} \ No newline at end of file diff --git a/CartriX.Share/Protos/printer_monitor.proto b/CartriX.Share/Protos/printer_monitor.proto new file mode 100644 index 0000000..b706802 --- /dev/null +++ b/CartriX.Share/Protos/printer_monitor.proto @@ -0,0 +1,20 @@ +syntax = "proto3"; + +option csharp_namespace = "CartriX.Share.Grpc"; + +service PrinterMonitor { + rpc SendStats (PrinterStatsRequest) returns (PrinterStatsResponse); +} + +message PrinterStatsRequest { + int32 printerId = 1; + string printerName = 2; + int32 pageCount = 3; + int32 tonerPercent = 4; + string source = 5; +} + +message PrinterStatsResponse { + bool success = 1; + string message = 2; +} diff --git a/CartriX.sln b/CartriX.sln index 31d1fec..4f766b3 100644 --- a/CartriX.sln +++ b/CartriX.sln @@ -4,9 +4,9 @@ VisualStudioVersion = 17.5.2.0 MinimumVisualStudioVersion = 10.0.40219.1 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CartriX.Server", "CartriX.Server\CartriX.Server.csproj", "{927C5334-796B-3E7D-2A2E-88E22985C85A}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CartriX.Agent", "CartriX.Agent\CartriX.Agent.csproj", "{1287CBBA-C5D5-BAF1-DE9E-B210FF6E8030}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CartriX.Service", "CartriX.Service\CartriX.Service.csproj", "{1287CBBA-C5D5-BAF1-DE9E-B210FF6E8030}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CartriX.Shared", "CartriX.Shared\CartriX.Shared.csproj", "{7A9D6237-FC00-4834-EBA1-6E5943B0DBC7}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CartriX.Share", "CartriX.Share\CartriX.Share.csproj", "{7A9D6237-FC00-4834-EBA1-6E5943B0DBC7}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution