Init commit

This commit is contained in:
Kirill Zotkin
2025-02-13 13:52:02 +02:00
commit 5423cc34a9
72 changed files with 6753 additions and 0 deletions

View File

@@ -0,0 +1,67 @@
using DevOpsProject.CommunicationControl.API.DTO.Client.Request;
using DevOpsProject.CommunicationControl.Logic.Services.Interfaces;
using DevOpsProject.Shared.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
namespace DevOpsProject.CommunicationControl.API.Controllers
{
[ApiController]
[Route("api/client")]
public class ClientController : Controller
{
private readonly ICommunicationControlService _communicationControlService;
private readonly IOptionsMonitor<OperationalAreaConfig> _operationalAreaConfig;
public ClientController(ICommunicationControlService communicationControlService, IOptionsMonitor<OperationalAreaConfig> operationalAreaConfig)
{
_communicationControlService = communicationControlService;
_operationalAreaConfig = operationalAreaConfig;
}
[HttpGet("area")]
public async Task<IActionResult> GetOperationalArea()
{
return Ok(_operationalAreaConfig.CurrentValue);
}
[HttpGet("hive/{hiveId}")]
public async Task<IActionResult> GetHive(string hiveId)
{
var hiveModel = await _communicationControlService.GetHiveModel(hiveId);
return Ok(hiveModel);
}
[HttpGet("hive")]
public async Task<IActionResult> GetHives()
{
var hives = await _communicationControlService.GetAllHives();
return Ok(hives);
}
[HttpDelete("hive/{hiveId}")]
public async Task<IActionResult> DisconnectHive(string hiveId)
{
var disconnetResult = await _communicationControlService.DisconnectHive(hiveId);
return Ok(disconnetResult);
}
[HttpPatch("hive")]
public async Task<IActionResult> SendBulkHiveMovingSignal(MoveHivesRequest request)
{
if (request?.Hives == null || !request.Hives.Any())
return BadRequest("No hive IDs provided.");
foreach (var id in request.Hives)
{
Task.Run(async () => await _communicationControlService.SendHiveControlSignal(id, request.Destination));
}
return Accepted("Hives are being moved asynchronously.");
}
}
}

View File

@@ -0,0 +1,63 @@
using DevOpsProject.CommunicationControl.API.DTO.Hive.Request;
using DevOpsProject.CommunicationControl.API.DTO.Hive.Response;
using DevOpsProject.CommunicationControl.Logic.Services.Interfaces;
using DevOpsProject.Shared.Models;
using Microsoft.AspNetCore.Mvc;
namespace DevOpsProject.CommunicationControl.API.Controllers
{
[ApiController]
[Route("api/hive")]
public class HiveController : Controller
{
private readonly ICommunicationControlService _communicationControlService;
public HiveController(ICommunicationControlService communicationControlService)
{
_communicationControlService = communicationControlService;
}
[HttpPost("connect")]
public async Task<IActionResult> Connect(HiveConnectRequest request)
{
var hiveModel = new HiveModel
{
HiveID = request.HiveID,
HiveIP = request.HiveIP,
HivePort = request.HivePort,
};
var hiveOperationalArea = await _communicationControlService.ConnectHive(hiveModel);
var connectResponse = new HiveConnectResponse
{
ConnectResult = true,
OperationalArea = hiveOperationalArea,
};
return Ok(connectResponse);
}
[HttpPost("telemetry")]
public async Task<IActionResult> Telemetry(HiveTelemetryRequest request)
{
var hiveTelemetryModel = new HiveTelemetryModel
{
HiveID = request.HiveID,
Location = request.Location,
Speed = request.Speed,
Height = request.Height,
State = request.State,
Timestamp = DateTime.Now
};
var telemetryUpdateTimestamp = await _communicationControlService.AddTelemetry(hiveTelemetryModel);
var telemetryResponse = new HiveTelemetryResponse
{
Timestamp = telemetryUpdateTimestamp
};
return Ok(telemetryResponse);
}
}
}

View File

@@ -0,0 +1,18 @@
using DevOpsProject.CommunicationControl.Logic.Services;
using DevOpsProject.CommunicationControl.Logic.Services.Interfaces;
namespace DevOpsProject.CommunicationControl.API.DI
{
public static class LogicConfiguration
{
public static IServiceCollection AddCommunicationControlLogic(this IServiceCollection serviceCollection)
{
serviceCollection.AddTransient<ICommunicationControlService, CommunicationControlService>();
serviceCollection.AddTransient<ISpatialService, SpatialService>();
return serviceCollection;
}
}
}

View File

@@ -0,0 +1,31 @@
using DevOpsProject.CommunicationControl.Logic.Services.Interfaces;
using DevOpsProject.CommunicationControl.Logic.Services;
using DevOpsProject.Shared.Configuration;
using StackExchange.Redis;
namespace DevOpsProject.CommunicationControl.API.DI
{
public static class RedisConfiguration
{
public static IServiceCollection AddRedis(this IServiceCollection serviceCollection, IConfiguration configuration)
{
var redisConfiguration = configuration.GetSection("Redis").Get<RedisOptions>();
var redis = ConnectionMultiplexer.Connect(redisConfiguration.ConnectionString);
serviceCollection.AddSingleton<IConnectionMultiplexer>(redis);
serviceCollection.Configure<RedisOptions>(
configuration.GetSection("Redis"));
serviceCollection.Configure<RedisKeys>(
configuration.GetSection("RedisKeys"));
serviceCollection.AddTransient<IRedisKeyValueService, RedisKeyValueService>();
// add message bus here - currently using Redis implementation
serviceCollection.AddTransient<IPublishService, RedisPublishService>();
return serviceCollection;
}
}
}

View File

@@ -0,0 +1,10 @@
using DevOpsProject.Shared.Models;
namespace DevOpsProject.CommunicationControl.API.DTO.Client.Request
{
public class MoveHivesRequest
{
public List<string> Hives { get;set;}
public Location Destination { get; set; }
}
}

View File

@@ -0,0 +1,9 @@
namespace DevOpsProject.CommunicationControl.API.DTO.Hive.Request
{
public class HiveConnectRequest
{
public string HiveIP { get; set; }
public int HivePort { get; set; }
public string HiveID { get; set; }
}
}

View File

@@ -0,0 +1,14 @@
using DevOpsProject.Shared.Enums;
using DevOpsProject.Shared.Models;
namespace DevOpsProject.CommunicationControl.API.DTO.Hive.Request
{
public class HiveTelemetryRequest
{
public string HiveID { get; set; }
public Location Location { get; set; }
public float Speed { get; set; }
public float Height { get; set; }
public State State { get; set; }
}
}

View File

@@ -0,0 +1,10 @@
using DevOpsProject.Shared.Models;
namespace DevOpsProject.CommunicationControl.API.DTO.Hive.Response
{
public class HiveConnectResponse
{
public bool ConnectResult { get; set; }
public HiveOperationalArea OperationalArea { get;set; }
}
}

View File

@@ -0,0 +1,7 @@
namespace DevOpsProject.CommunicationControl.API.DTO.Hive.Response
{
public class HiveTelemetryResponse
{
public DateTime Timestamp { get; set; }
}
}

View File

@@ -0,0 +1,29 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Http.Polly" Version="9.0.1" />
<PackageReference Include="Serilog" Version="4.2.0" />
<PackageReference Include="Serilog.AspNetCore" Version="9.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="9.0.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="6.0.0" />
<PackageReference Include="Serilog.Sinks.File" Version="6.0.0" />
<PackageReference Include="StackExchange.Redis" Version="2.8.24" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.6.2" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\DevOpsProject.CommunicationControl.Logic\DevOpsProject.CommunicationControl.Logic.csproj" />
<ProjectReference Include="..\DevOpsProject.Shared\DevOpsProject.Shared.csproj" />
</ItemGroup>
<ItemGroup>
<Folder Include="DTO\Client\Response\" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<ActiveDebugProfile>https</ActiveDebugProfile>
<Controller_SelectedScaffolderID>MvcControllerEmptyScaffolder</Controller_SelectedScaffolderID>
<Controller_SelectedScaffolderCategoryPath>root/Common/MVC/Controller</Controller_SelectedScaffolderCategoryPath>
</PropertyGroup>
</Project>

View File

@@ -0,0 +1,6 @@
@DevOpsProject_HostAddress = http://localhost:5134
GET {{DevOpsProject_HostAddress}}/weatherforecast/
Accept: application/json
###

View File

@@ -0,0 +1,35 @@
using Microsoft.AspNetCore.Diagnostics;
using System.Text.Json;
namespace DevOpsProject.CommunicationControl.API.Middleware
{
public class ExceptionHandlingMiddleware : IExceptionHandler
{
private readonly ILogger<ExceptionHandlingMiddleware> _logger;
private readonly IHostEnvironment _hostEnvironment;
public ExceptionHandlingMiddleware(ILogger<ExceptionHandlingMiddleware> logger, IHostEnvironment hostEnvironment)
{
_hostEnvironment = hostEnvironment;
_logger = logger;
}
public async ValueTask<bool> TryHandleAsync(HttpContext httpContext, Exception exception, CancellationToken cancellationToken)
{
_logger.LogError(exception, "Unhandled exception occured: {Message}", exception.Message);
httpContext.Response.StatusCode = StatusCodes.Status500InternalServerError;
httpContext.Response.ContentType = "application/json";
var errorResponse = new
{
Message = "Unexpected error occured",
Detail = _hostEnvironment.IsDevelopment() ? exception.ToString() : null
};
var jsonResponse = JsonSerializer.Serialize(errorResponse, new JsonSerializerOptions { WriteIndented = true });
await httpContext.Response.WriteAsync(jsonResponse, cancellationToken);
return true;
}
}
}

View File

@@ -0,0 +1,85 @@
using DevOpsProject.CommunicationControl.API.DI;
using DevOpsProject.CommunicationControl.API.Middleware;
using DevOpsProject.Shared.Clients;
using DevOpsProject.Shared.Models;
using Microsoft.Extensions.Options;
using Polly;
using Polly.Extensions.Http;
using Serilog;
internal class Program
{
private static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
builder.Host.UseSerilog((context, services, loggerConfig) =>
loggerConfig.ReadFrom.Configuration(context.Configuration)
.ReadFrom.Services(services)
.Enrich.FromLogContext());
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
// TODO: LATER - ADD OpenTelemtry
builder.Services.AddRedis(builder.Configuration);
builder.Services.AddCommunicationControlLogic();
builder.Services.Configure<OperationalAreaConfig>(builder.Configuration.GetSection("OperationalArea"));
builder.Services.AddSingleton<IOptionsMonitor<OperationalAreaConfig>, OptionsMonitor<OperationalAreaConfig>>();
var hiveRetryPolicy = HttpPolicyExtensions
.HandleTransientHttpError()
.WaitAndRetryAsync(3, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)));
builder.Services.AddHttpClient<HiveHttpClient>()
.AddPolicyHandler(hiveRetryPolicy);
var corsPolicyName = "AllowReactApp";
var localCorsPolicyName = "AllowLocalHtml";
builder.Services.AddCors(options =>
{
options.AddPolicy(name: corsPolicyName,
policy =>
{
policy.AllowAnyOrigin() //SECURITY WARNING ! Never allow all origins
.AllowAnyMethod()
.AllowAnyHeader();
});
options.AddPolicy(name: localCorsPolicyName,
policy =>
{
policy.AllowAnyOrigin() //SECURITY WARNING ! Never allow all origins
.AllowAnyMethod()
.AllowAnyHeader();
});
});
builder.Services.AddExceptionHandler<ExceptionHandlingMiddleware>();
builder.Services.AddProblemDetails();
var app = builder.Build();
app.UseExceptionHandler();
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseCors(corsPolicyName);
//app.UseCors(localCorsPolicyName);
app.UseAuthorization();
app.MapControllers();
app.Run();
}
}

View File

@@ -0,0 +1,41 @@
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:3542",
"sslPort": 44340
}
},
"profiles": {
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "http://0.0.0.0:8080",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "https://0.0.0.0:7097;http://0.0.0.0:8080",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}

View File

@@ -0,0 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}

View File

@@ -0,0 +1,50 @@
{
"Serilog": {
"Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.File" ],
"MinimumLevel": {
"Default": "Information",
"Override": {
"Microsoft": "Information",
"System": "Information"
}
},
"WriteTo": [
{
"Name": "Console"
},
{
"Name": "File",
"Args": {
"path": "Logs/log-.txt",
"rollingInterval": "Day",
"rollOnFileSizeLimit": true,
"formatter": "Serilog.Formatting.Compact.CompactJsonFormatter, Serilog.Formatting.Compact"
}
}
],
"Enrich": [ "FromLogContext", "WithMachineName", "WithProcessId", "WithThreadId" ],
"Properties": {
"Application": "DevOpsProject.CommunicationControl",
"Environment": "Development"
}
},
"Redis": {
"ConnectionString": "localhost:6379",
"PublishChannel": "HiveChannel"
},
"RedisKeys": {
"HiveKey": "Hive"
},
"OperationalArea": {
"Latitude": 48.697189,
"Longitude": 38.066246,
"Radius_KM": 5,
"InitialHeight_KM": 1,
"InitialSpeed_KM": 5,
"TelemetryInterval_MS": 30000,
"PingInterval_MS": 15000
},
"AllowedHosts": "*",
"Urls": "http://0.0.0.0:8080"
}