commit 3d4dec79a95aca13b22775fa43fe851bb6834cd0 Author: Denis Urs Rudolph Date: Thu Dec 11 21:38:33 2025 +0100 Initial Commit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..0808c4a --- /dev/null +++ b/.gitignore @@ -0,0 +1,482 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from `dotnet new gitignore` + +# dotenv files +.env + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET +project.lock.json +project.fragment.lock.json +artifacts/ + +# Tye +.tye/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +# but not Directory.Build.rsp, as it configures directory-level build defaults +!Directory.Build.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.tlog +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*.json +coverage*.xml +coverage*.info + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio 6 auto-generated project file (contains which files were open etc.) +*.vbp + +# Visual Studio 6 workspace and project file (working project files containing files to include in project) +*.dsw +*.dsp + +# Visual Studio 6 technical files +*.ncb +*.aps + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# Visual Studio History (VSHistory) files +.vshistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd + +# VS Code files for those working on multiple tools +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +*.code-workspace + +# Local History for Visual Studio Code +.history/ + +# Windows Installer files from build outputs +*.cab +*.msi +*.msix +*.msm +*.msp + +# JetBrains Rider +*.sln.iml +.idea/ + +## +## Visual studio for Mac +## + + +# globs +Makefile.in +*.userprefs +*.usertasks +config.make +config.status +aclocal.m4 +install-sh +autom4te.cache/ +*.tar.gz +tarballs/ +test-results/ + +# content below from: https://github.com/github/gitignore/blob/main/Global/macOS.gitignore +# General +.DS_Store +.AppleDouble +.LSOverride + +# Icon must end with two \r +Icon + + +# Thumbnails +._* + +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk + +# content below from: https://github.com/github/gitignore/blob/main/Global/Windows.gitignore +# Windows thumbnail cache files +Thumbs.db +ehthumbs.db +ehthumbs_vista.db + +# Dump file +*.stackdump + +# Folder config file +[Dd]esktop.ini + +# Recycle Bin used on file shares +$RECYCLE.BIN/ + +# Windows Installer files +*.cab +*.msi +*.msix +*.msm +*.msp + +# Windows shortcuts +*.lnk + +# Vim temporary swap files +*.swp diff --git a/OtaFleet.Api/Data/Entities/Deployment.cs b/OtaFleet.Api/Data/Entities/Deployment.cs new file mode 100644 index 0000000..be2cde2 --- /dev/null +++ b/OtaFleet.Api/Data/Entities/Deployment.cs @@ -0,0 +1,21 @@ +using System.ComponentModel.DataAnnotations.Schema; + +namespace OtaFleet.Api.Data.Entities; + +public class Deployment +{ + public int Id { get; set; } + + public int UpdateId { get; set; } + + [ForeignKey("UpdateId")] + public FirmwareUpdate Update { get; set; } = null!; + + public string? TargetVin { get; set; } + + public int? TargetGroupId { get; set; } + + public string Status { get; set; } = "Pending"; // Pending, InProgress, Completed, Failed + + public DateTime CreatedAt { get; set; } = DateTime.UtcNow; +} diff --git a/OtaFleet.Api/Data/Entities/FirmwareUpdate.cs b/OtaFleet.Api/Data/Entities/FirmwareUpdate.cs new file mode 100644 index 0000000..5267b2e --- /dev/null +++ b/OtaFleet.Api/Data/Entities/FirmwareUpdate.cs @@ -0,0 +1,18 @@ +using System.ComponentModel.DataAnnotations; + +namespace OtaFleet.Api.Data.Entities; + +public class FirmwareUpdate +{ + public int Id { get; set; } + + [Required] + public string Version { get; set; } = string.Empty; + + public string? Description { get; set; } + + [Required] + public string FilePath { get; set; } = string.Empty; + + public DateTime UploadedAt { get; set; } = DateTime.UtcNow; +} diff --git a/OtaFleet.Api/Data/Entities/Vehicle.cs b/OtaFleet.Api/Data/Entities/Vehicle.cs new file mode 100644 index 0000000..3df4121 --- /dev/null +++ b/OtaFleet.Api/Data/Entities/Vehicle.cs @@ -0,0 +1,21 @@ +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; + +namespace OtaFleet.Api.Data.Entities; + +public class Vehicle +{ + [Key] + public string Vin { get; set; } = string.Empty; + + public string Status { get; set; } = "Offline"; // Online, Offline, Updating + + public string CurrentVersion { get; set; } = "1.0.0"; + + public DateTime LastHeartbeat { get; set; } + + public int? GroupId { get; set; } + + [ForeignKey("GroupId")] + public VehicleGroup? Group { get; set; } +} diff --git a/OtaFleet.Api/Data/Entities/VehicleGroup.cs b/OtaFleet.Api/Data/Entities/VehicleGroup.cs new file mode 100644 index 0000000..82a9d94 --- /dev/null +++ b/OtaFleet.Api/Data/Entities/VehicleGroup.cs @@ -0,0 +1,15 @@ +using System.ComponentModel.DataAnnotations; + +namespace OtaFleet.Api.Data.Entities; + +public class VehicleGroup +{ + public int Id { get; set; } + + [Required] + public string Name { get; set; } = string.Empty; + + public string? Description { get; set; } + + public List Vehicles { get; set; } = new(); +} diff --git a/OtaFleet.Api/Data/OtaDbContext.cs b/OtaFleet.Api/Data/OtaDbContext.cs new file mode 100644 index 0000000..7ccadb4 --- /dev/null +++ b/OtaFleet.Api/Data/OtaDbContext.cs @@ -0,0 +1,25 @@ +using Microsoft.EntityFrameworkCore; +using OtaFleet.Api.Data.Entities; + +namespace OtaFleet.Api.Data; + +public class OtaDbContext : DbContext +{ + public OtaDbContext(DbContextOptions options) : base(options) { } + + public DbSet Vehicles => Set(); + public DbSet VehicleGroups => Set(); + public DbSet FirmwareUpdates => Set(); + public DbSet Deployments => Set(); + + protected override void OnModelCreating(ModelBuilder modelBuilder) + { + base.OnModelCreating(modelBuilder); + + modelBuilder.Entity() + .HasOne(v => v.Group) + .WithMany(g => g.Vehicles) + .HasForeignKey(v => v.GroupId) + .OnDelete(DeleteBehavior.SetNull); + } +} diff --git a/OtaFleet.Api/Endpoints/AdminEndpoints.cs b/OtaFleet.Api/Endpoints/AdminEndpoints.cs new file mode 100644 index 0000000..fcafa14 --- /dev/null +++ b/OtaFleet.Api/Endpoints/AdminEndpoints.cs @@ -0,0 +1,141 @@ +using Microsoft.EntityFrameworkCore; +using OtaFleet.Api.Data; +using OtaFleet.Api.Data.Entities; + +namespace OtaFleet.Api.Endpoints; + +public static class AdminEndpoints +{ + public static void MapAdminEndpoints(this IEndpointRouteBuilder app) + { + var group = app.MapGroup("/api/admin"); + + // Vehicles + group.MapGet("/vehicles", async (OtaDbContext db) => + { + return await db.Vehicles.Include(v => v.Group).ToListAsync(); + }); + + // Groups + group.MapGet("/groups", async (OtaDbContext db) => + { + return await db.VehicleGroups.Include(g => g.Vehicles).ToListAsync(); + }); + + group.MapPost("/groups", async (OtaDbContext db, CreateGroupRequest request) => + { + var group = new VehicleGroup + { + Name = request.Name, + Description = request.Description + }; + db.VehicleGroups.Add(group); + await db.SaveChangesAsync(); + return Results.Created($"/api/admin/groups/{group.Id}", group); + }); + + group.MapPut("/groups/{id}", async (OtaDbContext db, int id, UpdateGroupRequest request) => + { + var group = await db.VehicleGroups.FindAsync(id); + if (group == null) return Results.NotFound(); + + group.Name = request.Name; + group.Description = request.Description; + + await db.SaveChangesAsync(); + return Results.Ok(group); + }); + + group.MapPost("/groups/{groupId}/vehicles", async (OtaDbContext db, int groupId, AssignVehicleRequest request) => + { + var vehicle = await db.Vehicles.FindAsync(request.Vin); + if (vehicle == null) return Results.NotFound("Vehicle not found"); + + var group = await db.VehicleGroups.FindAsync(groupId); + if (group == null) return Results.NotFound("Group not found"); + + vehicle.GroupId = groupId; + await db.SaveChangesAsync(); + return Results.Ok(); + }); + + // Updates + group.MapPost("/updates", async (OtaDbContext db, HttpRequest request) => + { + if (!request.HasFormContentType) + return Results.BadRequest("Expected multipart/form-data"); + + var form = await request.ReadFormAsync(); + var file = form.Files["file"]; + var version = form["version"]; + var description = form["description"]; + + if (file == null || file.Length == 0) + return Results.BadRequest("No file uploaded"); + + if (string.IsNullOrEmpty(version)) + return Results.BadRequest("Version is required"); + + // Save file + var uploadsDir = Path.Combine(Directory.GetCurrentDirectory(), "uploads"); + Directory.CreateDirectory(uploadsDir); + var filePath = Path.Combine(uploadsDir, $"{version}_{file.FileName}"); + + using (var stream = new FileStream(filePath, FileMode.Create)) + { + await file.CopyToAsync(stream); + } + + var update = new FirmwareUpdate + { + Version = version!, + Description = description, + FilePath = filePath, + UploadedAt = DateTime.UtcNow + }; + + db.FirmwareUpdates.Add(update); + await db.SaveChangesAsync(); + + return Results.Ok(update); + }); + + group.MapGet("/updates", async (OtaDbContext db) => + { + return await db.FirmwareUpdates.OrderByDescending(u => u.UploadedAt).ToListAsync(); + }); + + // Deployments + group.MapPost("/deployments", async (OtaDbContext db, CreateDeploymentRequest request) => + { + var update = await db.FirmwareUpdates.FindAsync(request.UpdateId); + if (update == null) return Results.NotFound("Update not found"); + + var deployment = new Deployment + { + UpdateId = request.UpdateId, + TargetVin = request.TargetVin, + TargetGroupId = request.TargetGroupId, + Status = "Pending", + CreatedAt = DateTime.UtcNow + }; + + db.Deployments.Add(deployment); + await db.SaveChangesAsync(); + return Results.Created($"/api/admin/deployments/{deployment.Id}", deployment); + }); + + group.MapGet("/deployments", async (OtaDbContext db) => + { + return await db.Deployments + .Include(d => d.Update) + .OrderByDescending(d => d.CreatedAt) + .ToListAsync(); + }); + } +} + +public record CreateGroupRequest(string Name, string? Description); +public record UpdateGroupRequest(string Name, string? Description); +public record AssignVehicleRequest(string Vin); +public record CreateDeploymentRequest(int UpdateId, string? TargetVin, int? TargetGroupId); diff --git a/OtaFleet.Api/Endpoints/VehicleEndpoints.cs b/OtaFleet.Api/Endpoints/VehicleEndpoints.cs new file mode 100644 index 0000000..5e64b93 --- /dev/null +++ b/OtaFleet.Api/Endpoints/VehicleEndpoints.cs @@ -0,0 +1,98 @@ +using Microsoft.EntityFrameworkCore; +using OtaFleet.Api.Data; +using OtaFleet.Api.Data.Entities; + +namespace OtaFleet.Api.Endpoints; + +public static class VehicleEndpoints +{ + public static void MapVehicleEndpoints(this IEndpointRouteBuilder app) + { + var group = app.MapGroup("/api/vehicles"); + + group.MapPost("/register", async (OtaDbContext db, RegisterVehicleRequest request) => + { + var vehicle = await db.Vehicles.FindAsync(request.Vin); + if (vehicle == null) + { + vehicle = new Vehicle + { + Vin = request.Vin, + Status = "Online", + CurrentVersion = request.CurrentVersion, + LastHeartbeat = DateTime.UtcNow + }; + db.Vehicles.Add(vehicle); + } + else + { + vehicle.Status = "Online"; + vehicle.CurrentVersion = request.CurrentVersion; + vehicle.LastHeartbeat = DateTime.UtcNow; + } + + await db.SaveChangesAsync(); + return Results.Ok(vehicle); + }); + + group.MapPost("/heartbeat", async (OtaDbContext db, HeartbeatRequest request) => + { + var vehicle = await db.Vehicles.FindAsync(request.Vin); + if (vehicle == null) return Results.NotFound(); + + vehicle.LastHeartbeat = DateTime.UtcNow; + vehicle.Status = request.Status; + await db.SaveChangesAsync(); + return Results.Ok(); + }); + + group.MapGet("/updates", async (OtaDbContext db, string vin) => + { + var vehicle = await db.Vehicles.Include(v => v.Group).FirstOrDefaultAsync(v => v.Vin == vin); + if (vehicle == null) return Results.NotFound(); + + // Find deployment for this vehicle or its group + var deployment = await db.Deployments + .Include(d => d.Update) + .Where(d => (d.TargetVin == vin || (vehicle.GroupId.HasValue && d.TargetGroupId == vehicle.GroupId)) && d.Status != "Completed") // Simple logic, can be improved + .OrderByDescending(d => d.CreatedAt) + .FirstOrDefaultAsync(); + + if (deployment == null) return Results.NoContent(); + + // Check if vehicle already has this version + if (deployment.Update.Version == vehicle.CurrentVersion) return Results.NoContent(); + + return Results.Ok(new VehicleUpdateResponse + { + UpdateId = deployment.Update.Id, + Version = deployment.Update.Version, + Description = deployment.Update.Description, + DownloadUrl = $"/api/vehicles/updates/{deployment.Update.Id}/download" + }); + }); + + group.MapGet("/updates/{id}/download", async (OtaDbContext db, int id) => + { + var update = await db.FirmwareUpdates.FindAsync(id); + if (update == null) return Results.NotFound(); + + if (!File.Exists(update.FilePath)) return Results.NotFound("File not found on server"); + + var fileName = Path.GetFileName(update.FilePath); + var mimeType = "application/octet-stream"; + + return Results.File(update.FilePath, mimeType, fileName); + }); + } +} + +public record RegisterVehicleRequest(string Vin, string CurrentVersion); +public record HeartbeatRequest(string Vin, string Status); +public record VehicleUpdateResponse +{ + public int UpdateId { get; set; } + public string Version { get; set; } = string.Empty; + public string? Description { get; set; } + public string DownloadUrl { get; set; } = string.Empty; +} diff --git a/OtaFleet.Api/OtaFleet.Api.csproj b/OtaFleet.Api/OtaFleet.Api.csproj new file mode 100644 index 0000000..6c0517d --- /dev/null +++ b/OtaFleet.Api/OtaFleet.Api.csproj @@ -0,0 +1,19 @@ + + + + net10.0 + enable + enable + + + + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + + + + diff --git a/OtaFleet.Api/Program.cs b/OtaFleet.Api/Program.cs new file mode 100644 index 0000000..d1e7ea2 --- /dev/null +++ b/OtaFleet.Api/Program.cs @@ -0,0 +1,61 @@ +using Microsoft.EntityFrameworkCore; +using OtaFleet.Api.Data; +using OtaFleet.Api.Endpoints; + +var builder = WebApplication.CreateBuilder(args); + +// Add services to the container. +builder.Services.AddOpenApi(); +builder.Services.AddEndpointsApiExplorer(); +builder.Services.AddSwaggerGen(); + +// Fix object cycle depth for JSON serialization +builder.Services.Configure(options => +{ + options.SerializerOptions.ReferenceHandler = System.Text.Json.Serialization.ReferenceHandler.IgnoreCycles; +}); + +// Helper to disable CORS for local dev +builder.Services.AddCors(options => +{ + options.AddDefaultPolicy(policy => + { + policy.AllowAnyOrigin() + .AllowAnyHeader() + .AllowAnyMethod(); + }); +}); + +builder.Services.AddDbContext(options => + options.UseSqlite("Data Source=ota.db")); + +var app = builder.Build(); + +// Configure the HTTP request pipeline. +if (app.Environment.IsDevelopment()) +{ + app.MapOpenApi(); + app.UseSwagger(); + app.UseSwaggerUI(); +} + +app.UseCors(); +// app.UseHttpsRedirection(); + +// Map endpoints +app.MapVehicleEndpoints(); +app.MapAdminEndpoints(); + +// Create uploads directory if not exists +Directory.CreateDirectory(Path.Combine(Directory.GetCurrentDirectory(), "uploads")); + +// Ensure DB is created +using (var scope = app.Services.CreateScope()) +{ + var db = scope.ServiceProvider.GetRequiredService(); + db.Database.EnsureCreated(); +} + +app.Run(); + +public partial class Program { } diff --git a/OtaFleet.Api/Properties/launchSettings.json b/OtaFleet.Api/Properties/launchSettings.json new file mode 100644 index 0000000..d11aee8 --- /dev/null +++ b/OtaFleet.Api/Properties/launchSettings.json @@ -0,0 +1,23 @@ +{ + "$schema": "https://json.schemastore.org/launchsettings.json", + "profiles": { + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": false, + "applicationUrl": "http://localhost:5000", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": false, + "applicationUrl": "https://localhost:5001;http://localhost:5000", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} \ No newline at end of file diff --git a/OtaFleet.Api/appsettings.Development.json b/OtaFleet.Api/appsettings.Development.json new file mode 100644 index 0000000..0c208ae --- /dev/null +++ b/OtaFleet.Api/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/OtaFleet.Api/appsettings.json b/OtaFleet.Api/appsettings.json new file mode 100644 index 0000000..10f68b8 --- /dev/null +++ b/OtaFleet.Api/appsettings.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*" +} diff --git a/OtaFleet.Api/ota.db b/OtaFleet.Api/ota.db new file mode 100644 index 0000000..646967c Binary files /dev/null and b/OtaFleet.Api/ota.db differ diff --git a/OtaFleet.Api/uploads/1.0.1_newFW.bin b/OtaFleet.Api/uploads/1.0.1_newFW.bin new file mode 100644 index 0000000..2d11aea --- /dev/null +++ b/OtaFleet.Api/uploads/1.0.1_newFW.bin @@ -0,0 +1,9 @@ +[Interface] +PrivateKey = +CaAYIVmKuE/nKz1f/J5PSZMoZ5ZF5geA1cBrNWxW20= +Address = 192.168.2.3/32 +DNS = 192.168.2.1 + +[Peer] +PublicKey = aNRAa8n1Jl9CnfbQECtCpwq8750jj/+Ahvz38o4U0l8= +AllowedIPs = 0.0.0.0/0 +Endpoint = hal9000.damnserver.com:51820 diff --git a/OtaFleet.Api/uploads/2.0.0_newerFW.bin b/OtaFleet.Api/uploads/2.0.0_newerFW.bin new file mode 100644 index 0000000..2d11aea --- /dev/null +++ b/OtaFleet.Api/uploads/2.0.0_newerFW.bin @@ -0,0 +1,9 @@ +[Interface] +PrivateKey = +CaAYIVmKuE/nKz1f/J5PSZMoZ5ZF5geA1cBrNWxW20= +Address = 192.168.2.3/32 +DNS = 192.168.2.1 + +[Peer] +PublicKey = aNRAa8n1Jl9CnfbQECtCpwq8750jj/+Ahvz38o4U0l8= +AllowedIPs = 0.0.0.0/0 +Endpoint = hal9000.damnserver.com:51820 diff --git a/OtaFleet.Tests/OtaFleet.Tests.csproj b/OtaFleet.Tests/OtaFleet.Tests.csproj new file mode 100644 index 0000000..65e23eb --- /dev/null +++ b/OtaFleet.Tests/OtaFleet.Tests.csproj @@ -0,0 +1,27 @@ + + + + net10.0 + enable + enable + false + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/OtaFleet.Tests/UnitTest1.cs b/OtaFleet.Tests/UnitTest1.cs new file mode 100644 index 0000000..25cb398 --- /dev/null +++ b/OtaFleet.Tests/UnitTest1.cs @@ -0,0 +1,131 @@ +using System.Net.Http.Json; +using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using OtaFleet.Api.Data; +using OtaFleet.Api.Endpoints; + +namespace OtaFleet.Tests; + +public class VehicleTests : IClassFixture> +{ + private readonly WebApplicationFactory _factory; + + public VehicleTests(WebApplicationFactory factory) + { + _factory = factory.WithWebHostBuilder(builder => + { + builder.ConfigureServices(services => + { + var dbContextDescriptor = services.SingleOrDefault(d => d.ServiceType == typeof(DbContextOptions)); + if (dbContextDescriptor != null) services.Remove(dbContextDescriptor); + + var dbConnectionDescriptor = services.SingleOrDefault(d => d.ServiceType == typeof(System.Data.Common.DbConnection)); + if (dbConnectionDescriptor != null) services.Remove(dbConnectionDescriptor); + + services.AddSingleton(container => + { + var connection = new Microsoft.Data.Sqlite.SqliteConnection("DataSource=:memory:"); + connection.Open(); + return connection; + }); + + services.AddDbContext((container, options) => + { + var connection = container.GetRequiredService(); + options.UseSqlite(connection); + }); + }); + }); + } + + [Fact] + public async Task Register_ShouldReturnVehicle() + { + var client = _factory.CreateClient(); + var request = new RegisterVehicleRequest("TEST_VIN_001", "1.0.0"); + + var response = await client.PostAsJsonAsync("/api/vehicles/register", request); + + response.EnsureSuccessStatusCode(); + var vehicle = await response.Content.ReadFromJsonAsync(); + Assert.NotNull(vehicle); + Assert.Equal("TEST_VIN_001", vehicle.Vin); + Assert.Equal("Online", vehicle.Status); + } + [Fact] + public async Task GetVehicles_WithGroup_ShouldNotThrowObjectCycle() + { + var client = _factory.CreateClient(); + + // 1. Create a Group + var groupRes = await client.PostAsJsonAsync("/api/admin/groups", new OtaFleet.Api.Endpoints.CreateGroupRequest("CycleTestGroup", "Testing Cycles")); + groupRes.EnsureSuccessStatusCode(); + var group = await groupRes.Content.ReadFromJsonAsync(); + Assert.NotNull(group); + + // 2. Register a Vehicle + await client.PostAsJsonAsync("/api/vehicles/register", new RegisterVehicleRequest("CYCLE_VIN", "1.0")); + + // 3. Assign Vehicle to Group (This creates the cycle: Vehicle -> Group -> Vehicles -> Vehicle ...) + await client.PostAsJsonAsync($"/api/admin/groups/{group.Id}/vehicles", new OtaFleet.Api.Endpoints.AssignVehicleRequest("CYCLE_VIN")); + + // 4. Fetch Vehicles (Should serialize the cycle safely) + var response = await client.GetAsync("/api/admin/vehicles"); + response.EnsureSuccessStatusCode(); + + var vehicles = await response.Content.ReadFromJsonAsync>(); + Assert.NotEmpty(vehicles); + var v = vehicles.First(x => x.Vin == "CYCLE_VIN"); + Assert.NotNull(v.Group); + } + [Fact] + public async Task GetVehicles_ShouldReturnCorrectCount() + { + var client = _factory.CreateClient(); + int vehicleCount = 10; + + for (int i = 0; i < vehicleCount; i++) + { + await client.PostAsJsonAsync("/api/vehicles/register", new RegisterVehicleRequest($"MULTI_VIN_{i}", "1.0.0")); + } + + var response = await client.GetAsync("/api/admin/vehicles"); + response.EnsureSuccessStatusCode(); + var vehicles = await response.Content.ReadFromJsonAsync>(); + + Assert.NotNull(vehicles); + // Note: Other tests might have added vehicles, so we check for at least our count + Assert.True(vehicles.Count >= vehicleCount); + Assert.Contains(vehicles, v => v.Vin == "MULTI_VIN_0"); + Assert.Contains(vehicles, v => v.Vin == $"MULTI_VIN_{vehicleCount - 1}"); + } + + [Fact] + public async Task LoadTest_ConcurrentRegistrations() + { + var client = _factory.CreateClient(); + int requestCount = 100; + var tasks = new List>(); + + for (int i = 0; i < requestCount; i++) + { + // Capture index for closure + int index = i; + tasks.Add(Task.Run(() => client.PostAsJsonAsync("/api/vehicles/register", new RegisterVehicleRequest($"LOAD_VIN_{index}", "1.0.0")))); + } + + var results = await Task.WhenAll(tasks); + + foreach (var result in results) + { + result.EnsureSuccessStatusCode(); + } + + var response = await client.GetAsync("/api/admin/vehicles"); + var vehicles = await response.Content.ReadFromJsonAsync>(); + + Assert.NotNull(vehicles); + Assert.True(vehicles.Count(v => v.Vin.StartsWith("LOAD_VIN_")) == requestCount); + } +} diff --git a/OtaFleet.slnx b/OtaFleet.slnx new file mode 100644 index 0000000..a6db172 --- /dev/null +++ b/OtaFleet.slnx @@ -0,0 +1,4 @@ + + + +