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,18 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Options" Version="9.0.1" />
<PackageReference Include="StackExchange.Redis" Version="2.8.24" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\DevOpsProject.Shared\DevOpsProject.Shared.csproj" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,155 @@
using DevOpsProject.CommunicationControl.Logic.Services.Interfaces;
using DevOpsProject.Shared.Clients;
using DevOpsProject.Shared.Configuration;
using DevOpsProject.Shared.Exceptions;
using DevOpsProject.Shared.Messages;
using DevOpsProject.Shared.Models;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace DevOpsProject.CommunicationControl.Logic.Services
{
public class CommunicationControlService : ICommunicationControlService
{
private readonly ISpatialService _spatialService;
private readonly IRedisKeyValueService _redisService;
private readonly RedisKeys _redisKeys;
private readonly IPublishService _messageBus;
private readonly HiveHttpClient _hiveHttpClient;
private readonly ILogger<CommunicationControlService> _logger;
public CommunicationControlService(ISpatialService spatialService, IRedisKeyValueService redisService, IOptionsSnapshot<RedisKeys> redisKeysSnapshot,
IPublishService messageBus, HiveHttpClient hiveHttpClient, ILogger<CommunicationControlService> logger)
{
_spatialService = spatialService;
_redisService = redisService;
_redisKeys = redisKeysSnapshot.Value;
_messageBus = messageBus;
_hiveHttpClient = hiveHttpClient;
_logger = logger;
}
public async Task<bool> DisconnectHive(string hiveId)
{
bool isSuccessfullyDisconnected = false;
try
{
var result = await _redisService.DeleteAsync(hiveId);
isSuccessfullyDisconnected = result;
return result;
}
finally
{
await _messageBus.Publish(new HiveDisconnectedMessage
{
HiveID = hiveId,
IsSuccessfullyDisconnected = isSuccessfullyDisconnected
});
}
}
public async Task<HiveModel> GetHiveModel(string hiveId)
{
var result = await _redisService.GetAsync<HiveModel>(GetHiveKey(hiveId));
return result;
}
public async Task<List<HiveModel>> GetAllHives()
{
var result = await _redisService.GetAllAsync<HiveModel>($"{_redisKeys.HiveKey}:");
return result;
}
public async Task<HiveOperationalArea> ConnectHive(HiveModel model)
{
bool result = await _redisService.SetAsync(GetHiveKey(model.HiveID), model);
if (result)
{
var operationalArea = await _spatialService.GetHiveOperationalArea(model);
await _messageBus.Publish(new HiveConnectedMessage
{
HiveID = model.HiveID,
Hive = model,
InitialOperationalArea = operationalArea,
IsSuccessfullyConnected = result
});
return operationalArea;
}
else
{
await _messageBus.Publish(new HiveConnectedMessage
{
HiveID = model.HiveID,
Hive = model,
IsSuccessfullyConnected = result
});
throw new HiveConnectionException($"Failed to connect hive for HiveId: {model.HiveID}");
}
}
public async Task<DateTime> AddTelemetry(HiveTelemetryModel model)
{
string hiveKey = GetHiveKey(model.HiveID);
bool hiveExists = await _redisService.CheckIfKeyExists(hiveKey);
if (hiveExists)
{
bool result = await _redisService.UpdateAsync(hiveKey, (HiveModel hive) =>
{
hive.Telemetry = model;
});
await _messageBus.Publish(new TelemetrySentMessage
{
HiveID = model.HiveID,
Telemetry = model,
IsSuccessfullySent = result
});
return model.Timestamp;
}
else
{
await _messageBus.Publish(new TelemetrySentMessage
{
HiveID = model.HiveID,
Telemetry = model,
IsSuccessfullySent = false
});
throw new HiveNotFoundException($"Hive not found for id: {model.HiveID}");
}
}
public async Task<string?> SendHiveControlSignal(string hiveId, Location destination)
{
var hive = await GetHiveModel(hiveId);
if (hive == null)
{
throw new Exception($"Hive control signal error: cannot find hive with id: {hiveId}");
}
bool isSuccessfullySent = false;
try
{
// TODO: Schema can be moved to appsettings
var result = await _hiveHttpClient.SendHiveControlCommandAsync("http", hive.HiveIP, hive.HivePort, destination);
isSuccessfullySent = true;
return result;
}
finally
{
await _messageBus.Publish(new MoveHiveMessage
{
IsSuccessfullySent = isSuccessfullySent,
Destination = destination,
HiveID = hiveId
});
}
}
private string GetHiveKey(string hiveId)
{
return $"{_redisKeys.HiveKey}:{hiveId}";
}
}
}

View File

@@ -0,0 +1,14 @@
using DevOpsProject.Shared.Models;
namespace DevOpsProject.CommunicationControl.Logic.Services.Interfaces
{
public interface ICommunicationControlService
{
Task<bool> DisconnectHive(string hiveId);
Task<HiveModel> GetHiveModel(string hiveId);
Task<List<HiveModel>> GetAllHives();
Task<HiveOperationalArea> ConnectHive(HiveModel model);
Task<DateTime> AddTelemetry(HiveTelemetryModel model);
Task<string?> SendHiveControlSignal(string hiveId, Location destination);
}
}

View File

@@ -0,0 +1,7 @@
namespace DevOpsProject.CommunicationControl.Logic.Services.Interfaces
{
public interface IPublishService
{
Task Publish<T>(T message);
}
}

View File

@@ -0,0 +1,12 @@
namespace DevOpsProject.CommunicationControl.Logic.Services.Interfaces
{
public interface IRedisKeyValueService
{
Task<T> GetAsync<T>(string key);
Task<List<T>> GetAllAsync<T>(string keyPattern);
Task<bool> SetAsync<T>(string key, T value);
Task<bool> UpdateAsync<T>(string key, Action<T> updateAction);
Task<bool> CheckIfKeyExists(string key);
Task<bool> DeleteAsync(string key);
}
}

View File

@@ -0,0 +1,9 @@
using DevOpsProject.Shared.Models;
namespace DevOpsProject.CommunicationControl.Logic.Services.Interfaces
{
public interface ISpatialService
{
Task<HiveOperationalArea> GetHiveOperationalArea(HiveModel hiveModel);
}
}

View File

@@ -0,0 +1,75 @@
using DevOpsProject.CommunicationControl.Logic.Services.Interfaces;
using StackExchange.Redis;
using System.Text.Json;
namespace DevOpsProject.CommunicationControl.Logic.Services
{
public class RedisKeyValueService : IRedisKeyValueService
{
private readonly IConnectionMultiplexer _connectionMultiplexer;
public RedisKeyValueService(IConnectionMultiplexer connectionMultiplexer)
{
_connectionMultiplexer = connectionMultiplexer;
}
public async Task<T> GetAsync<T>(string key)
{
var db = _connectionMultiplexer.GetDatabase();
var json = await db.StringGetAsync(key);
return json.HasValue ? JsonSerializer.Deserialize<T>(json) : default;
}
public async Task<List<T>> GetAllAsync<T>(string keyPattern)
{
var server = _connectionMultiplexer.GetServer(_connectionMultiplexer.GetEndPoints().First());
var keys = server.Keys(pattern: $"{keyPattern}*");
var resultList = new List<T>();
foreach ( var key in keys)
{
var entry = await GetAsync<T>(key);
if (entry != null)
{
resultList.Add(entry);
}
}
return resultList;
}
public async Task<bool> UpdateAsync<T>(string key, Action<T> updateAction)
{
var db = _connectionMultiplexer.GetDatabase();
var jsonData = await db.StringGetAsync(key);
if (!jsonData.HasValue) return false;
var obj = JsonSerializer.Deserialize<T>(jsonData);
if (obj == null) return false;
updateAction(obj);
return await SetAsync(key, obj);
}
public async Task<bool> SetAsync<T>(string key, T value)
{
var db = _connectionMultiplexer.GetDatabase();
var json = JsonSerializer.Serialize(value);
return await db.StringSetAsync(key, json);
}
public async Task<bool> CheckIfKeyExists(string key)
{
var db = _connectionMultiplexer.GetDatabase();
return await db.KeyExistsAsync(key);
}
public async Task<bool> DeleteAsync(string key)
{
var db = _connectionMultiplexer.GetDatabase();
return await db.KeyDeleteAsync(key);
}
}
}

View File

@@ -0,0 +1,28 @@
using DevOpsProject.CommunicationControl.Logic.Services.Interfaces;
using DevOpsProject.Shared.Configuration;
using Microsoft.Extensions.Options;
using StackExchange.Redis;
using System.Text.Json;
namespace DevOpsProject.CommunicationControl.Logic.Services
{
public class RedisPublishService : IPublishService
{
private readonly IConnectionMultiplexer _connectionMultiplexer;
private readonly RedisOptions _redisOptions;
public RedisPublishService(IConnectionMultiplexer connectionMultiplexer, IOptions<RedisOptions> redisOptions)
{
_connectionMultiplexer = connectionMultiplexer;
_redisOptions = redisOptions.Value;
}
public async Task Publish<T>(T message)
{
var pubsub = _connectionMultiplexer.GetSubscriber();
var messageJson = JsonSerializer.Serialize(message);
await pubsub.PublishAsync(_redisOptions.PublishChannel, messageJson);
}
}
}

View File

@@ -0,0 +1,35 @@
using DevOpsProject.CommunicationControl.Logic.Services.Interfaces;
using DevOpsProject.Shared.Models;
using Microsoft.Extensions.Options;
namespace DevOpsProject.CommunicationControl.Logic.Services
{
public class SpatialService : ISpatialService
{
private readonly IOptionsMonitor<OperationalAreaConfig> _operationalAreaConfig;
public SpatialService(IOptionsMonitor<OperationalAreaConfig> operationalAreaConfig)
{
_operationalAreaConfig = operationalAreaConfig;
}
public async Task<HiveOperationalArea> GetHiveOperationalArea(HiveModel hiveModel)
{
var operationalArea = new HiveOperationalArea
{
RadiusKM = _operationalAreaConfig.CurrentValue.Radius_KM,
InitialLocation = new Location
{
Latitude = _operationalAreaConfig.CurrentValue.Latitude,
Longitude = _operationalAreaConfig.CurrentValue.Longitude
},
InitialHeight = _operationalAreaConfig.CurrentValue.InitialHeight_KM,
Speed = _operationalAreaConfig.CurrentValue.InitialSpeed_KM,
TelemetryIntervalMs = _operationalAreaConfig.CurrentValue.TelemetryInterval_MS,
PingIntervalMs = _operationalAreaConfig.CurrentValue.PingInterval_MS
};
return operationalArea;
}
}
}

View File

@@ -0,0 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="StackExchange.Redis" Version="2.8.24" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,28 @@
using StackExchange.Redis;
class Program
{
/// <summary>
/// Sample app with only purpose to listen message bus and keep queue alive inside redis
/// </summary>
/// <returns></returns>
static async Task Main()
{
Console.WriteLine("Connecting to Redis...");
var redis = await ConnectionMultiplexer.ConnectAsync("localhost:6379");
var subscriber = redis.GetSubscriber();
string channelName = "HiveChannel";
await subscriber.SubscribeAsync(channelName, (channel, message) =>
{
Console.WriteLine($"Received message: {message}");
});
Console.WriteLine($"Listening for messages on channel: {channelName}");
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
}

View File

@@ -0,0 +1,36 @@
using System.Text;
using System.Text.Json;
namespace DevOpsProject.Shared.Clients
{
public class HiveHttpClient
{
private readonly HttpClient _httpClient;
public HiveHttpClient(HttpClient httpClient)
{
_httpClient = httpClient;
}
public async Task<string?> SendHiveControlCommandAsync(string scheme, string ip, int port, object payload)
{
var uriBuilder = new UriBuilder
{
Scheme = scheme,
Host = ip,
Port = port,
Path = "api/control"
};
var jsonContent = new StringContent(JsonSerializer.Serialize(payload), Encoding.UTF8, "application/json");
var response = await _httpClient.PostAsync(uriBuilder.Uri, jsonContent);
if (response.IsSuccessStatusCode)
{
return await response.Content.ReadAsStringAsync();
}
return null;
}
}
}

View File

@@ -0,0 +1,7 @@
namespace DevOpsProject.Shared.Configuration
{
public class RedisKeys
{
public string HiveKey { get; set; }
}
}

View File

@@ -0,0 +1,8 @@
namespace DevOpsProject.Shared.Configuration
{
public class RedisOptions
{
public string ConnectionString { get; set; }
public string PublishChannel { get; set; }
}
}

View File

@@ -0,0 +1,9 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>

View File

@@ -0,0 +1,9 @@
namespace DevOpsProject.Shared.Enums
{
public enum State
{
Stop,
Move,
Error
}
}

View File

@@ -0,0 +1,19 @@
namespace DevOpsProject.Shared.Exceptions
{
public class HiveConnectionException : Exception
{
public HiveConnectionException()
{
}
public HiveConnectionException(string message)
: base(message)
{
}
public HiveConnectionException(string message, Exception inner)
: base(message, inner)
{
}
}
}

View File

@@ -0,0 +1,19 @@
namespace DevOpsProject.Shared.Exceptions
{
public class HiveNotFoundException : Exception
{
public HiveNotFoundException()
{
}
public HiveNotFoundException(string message)
: base(message)
{
}
public HiveNotFoundException(string message, Exception inner)
: base(message, inner)
{
}
}
}

View File

@@ -0,0 +1,7 @@
namespace DevOpsProject.Shared.Messages
{
public abstract class BaseMessage
{
public string HiveID { get; set; }
}
}

View File

@@ -0,0 +1,11 @@
using DevOpsProject.Shared.Models;
namespace DevOpsProject.Shared.Messages
{
public class HiveConnectedMessage : BaseMessage
{
public bool IsSuccessfullyConnected { get; set; }
public HiveModel Hive { get; set; }
public HiveOperationalArea InitialOperationalArea { get; set; }
}
}

View File

@@ -0,0 +1,9 @@
using DevOpsProject.Shared.Models;
namespace DevOpsProject.Shared.Messages
{
public class HiveDisconnectedMessage : BaseMessage
{
public bool IsSuccessfullyDisconnected { get; set; }
}
}

View File

@@ -0,0 +1,10 @@
using DevOpsProject.Shared.Models;
namespace DevOpsProject.Shared.Messages
{
public class MoveHiveMessage : BaseMessage
{
public bool IsSuccessfullySent { get; set; }
public Location Destination { get;set; }
}
}

View File

@@ -0,0 +1,10 @@
using DevOpsProject.Shared.Models;
namespace DevOpsProject.Shared.Messages
{
public class TelemetrySentMessage : BaseMessage
{
public bool IsSuccessfullySent { get; set; }
public HiveTelemetryModel Telemetry { get; set; }
}
}

View File

@@ -0,0 +1,10 @@
namespace DevOpsProject.Shared.Models
{
public class HiveModel
{
public string HiveID { get; set; }
public string HiveIP { get; set; }
public int HivePort { get; set; }
public HiveTelemetryModel Telemetry { get; set; }
}
}

View File

@@ -0,0 +1,12 @@
namespace DevOpsProject.Shared.Models
{
public class HiveOperationalArea
{
public double RadiusKM { get; set; }
public Location InitialLocation { get; set; }
public float InitialHeight { get; set; }
public float Speed { get; set; }
public int TelemetryIntervalMs { get; set; }
public int PingIntervalMs { get; set; }
}
}

View File

@@ -0,0 +1,14 @@
using DevOpsProject.Shared.Enums;
namespace DevOpsProject.Shared.Models
{
public class HiveTelemetryModel
{
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; }
public DateTime Timestamp { get; set; }
}
}

View File

@@ -0,0 +1,8 @@
namespace DevOpsProject.Shared.Models
{
public struct Location
{
public float Latitude { get; set; }
public float Longitude { get; set; }
}
}

View File

@@ -0,0 +1,13 @@
namespace DevOpsProject.Shared.Models
{
public class OperationalAreaConfig
{
public float Latitude { get; set; }
public float Longitude { get; set; }
public float Radius_KM { get; set; }
public float InitialHeight_KM { get; set; }
public float InitialSpeed_KM { get; set; }
public int TelemetryInterval_MS { get; set; }
public int PingInterval_MS { get; set; }
}
}

View File

@@ -0,0 +1,40 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.12.35707.178
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DevOpsProject.CommunicationControl.API", "DevOpsProject\DevOpsProject.CommunicationControl.API.csproj", "{BB9B9EA1-0281-4242-9344-07DFF6A20574}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DevOpsProject.CommunicationControl.Logic", "DevOpsProject.CommunicationControl.Logic\DevOpsProject.CommunicationControl.Logic.csproj", "{5B279B4B-5842-413A-8E76-158C7472F45D}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DevOpsProject.Shared", "DevOpsProject.Shared\DevOpsProject.Shared.csproj", "{7C98DF1D-D8B9-4DC5-A0AB-723FE2E658BE}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DevOpsProject.Example.MessageListener", "DevOpsProject.Example.MessageListener\DevOpsProject.Example.MessageListener.csproj", "{CBB302CE-D22A-4DA0-8811-E4F8FDFC1C4B}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{BB9B9EA1-0281-4242-9344-07DFF6A20574}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{BB9B9EA1-0281-4242-9344-07DFF6A20574}.Debug|Any CPU.Build.0 = Debug|Any CPU
{BB9B9EA1-0281-4242-9344-07DFF6A20574}.Release|Any CPU.ActiveCfg = Release|Any CPU
{BB9B9EA1-0281-4242-9344-07DFF6A20574}.Release|Any CPU.Build.0 = Release|Any CPU
{5B279B4B-5842-413A-8E76-158C7472F45D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{5B279B4B-5842-413A-8E76-158C7472F45D}.Debug|Any CPU.Build.0 = Debug|Any CPU
{5B279B4B-5842-413A-8E76-158C7472F45D}.Release|Any CPU.ActiveCfg = Release|Any CPU
{5B279B4B-5842-413A-8E76-158C7472F45D}.Release|Any CPU.Build.0 = Release|Any CPU
{7C98DF1D-D8B9-4DC5-A0AB-723FE2E658BE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{7C98DF1D-D8B9-4DC5-A0AB-723FE2E658BE}.Debug|Any CPU.Build.0 = Debug|Any CPU
{7C98DF1D-D8B9-4DC5-A0AB-723FE2E658BE}.Release|Any CPU.ActiveCfg = Release|Any CPU
{7C98DF1D-D8B9-4DC5-A0AB-723FE2E658BE}.Release|Any CPU.Build.0 = Release|Any CPU
{CBB302CE-D22A-4DA0-8811-E4F8FDFC1C4B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{CBB302CE-D22A-4DA0-8811-E4F8FDFC1C4B}.Debug|Any CPU.Build.0 = Debug|Any CPU
{CBB302CE-D22A-4DA0-8811-E4F8FDFC1C4B}.Release|Any CPU.ActiveCfg = Release|Any CPU
{CBB302CE-D22A-4DA0-8811-E4F8FDFC1C4B}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

View File

@@ -0,0 +1,2 @@
<wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml" xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<s:String x:Key="/Default/CodeInspection/ExcludedFiles/FilesAndFoldersToSkip2/=7020124F_002D9FFC_002D4AC3_002D8F3D_002DAAB8E0240759_002Ff_003ACorsPolicyBuilder_002Ecs_002Fl_003A_002E_002E_003F_002E_002E_003F_002E_002E_003F_002E_002E_003F_002E_002E_003F_002E_002E_003FLibrary_003FApplication_0020Support_003FJetBrains_003FRider2024_002E2_003Fresharper_002Dhost_003FSourcesCache_003Ff2b268c5e2cd9f1f915a357be6a8df853a5e36d3641a02dea9c31d924ca17a1_003FCorsPolicyBuilder_002Ecs/@EntryIndexedValue">ForceIncluded</s:String></wpf:ResourceDictionary>

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"
}