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

5
.gitignore vendored Normal file
View File

@ -0,0 +1,5 @@
src/MapClient/node_modules
src/CommunicationControl/.idea
bin
obj
Logs

15
.vscode/launch.json vendored Normal file
View File

@ -0,0 +1,15 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "C#: Communication Control Debug",
"type": "dotnet",
"request": "launch",
"projectPath": "${workspaceFolder}/src/CommunicationControl/DevOpsProject/DevOpsProject.CommunicationControl.API.csproj"
}
]
}

37
.vscode/tasks.json vendored Normal file
View File

@ -0,0 +1,37 @@
{
"version": "2.0.0",
"tasks": [
{
"label": "build",
"command": "dotnet",
"type": "process",
"args": [
"build",
"/property:GenerateFullPaths=true",
"/consoleloggerparameters:NoSummary;ForceNoAlign"
],
"problemMatcher": "$msCompile"
},
{
"label": "publish",
"command": "dotnet",
"type": "process",
"args": [
"publish",
"/property:GenerateFullPaths=true",
"/consoleloggerparameters:NoSummary;ForceNoAlign"
],
"problemMatcher": "$msCompile"
},
{
"label": "watch",
"command": "dotnet",
"type": "process",
"args": [
"watch",
"run"
],
"problemMatcher": "$msCompile"
}
]
}

39
README.md Normal file
View File

@ -0,0 +1,39 @@
# Hive Emulator
## About
This is a demo project used in the Uni DevOps course
## Installation
### Run Redis
```bash
docker run --name redis -d -p 6379:6379 redis
```
### Map Component
```bash
cd src/MapClient
npm install
npm run dev
```
### Communiction Control
```bash
cd src/CommunicationControl
dotnet build DevOpsProject/
```
## Usage
1. Map Control is available at http://localhost:3000
2. Redis - Get available keys:
```bash
docker exec -it redis redis-cli
keys *
get [hiveKey]
```
3. Communication Control Swagger: http://localhost:8080

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

View File

@ -0,0 +1,22 @@
// For format details, see https://aka.ms/devcontainer.json. For config options, see the
// README at: https://github.com/devcontainers/templates/tree/main/src/javascript-node
{
"name": "Node.js",
"image": "mcr.microsoft.com/devcontainers/javascript-node:1-22-bookworm",
// Features to add to the dev container. More info: https://containers.dev/features.
// "features": {},
"runArgs": ["--name", "map_control_devcontainer", "--network=host"],
// Use 'forwardPorts' to make a list of ports inside the container available locally.
"forwardPorts": [3000],
"appPort": ["3000:3000"]
// Use 'postCreateCommand' to run commands after the container is created.
// "postCreateCommand": "yarn install",
// Configure tool-specific properties.
// "customizations": {},
// Uncomment to connect as root instead. More info: https://aka.ms/dev-containers-non-root.
// "remoteUser": "root"
}

20
src/MapClient/README.md Normal file
View File

@ -0,0 +1,20 @@
# Map UI for Communication Control
## Installation
1. Clone the repository:
```bash
git clone <>
```
2. Install dependencies:
```bash
npm install
```
3. Run
```bash
npm run dev
```

View File

@ -0,0 +1,38 @@
import js from '@eslint/js'
import globals from 'globals'
import react from 'eslint-plugin-react'
import reactHooks from 'eslint-plugin-react-hooks'
import reactRefresh from 'eslint-plugin-react-refresh'
export default [
{ ignores: ['dist'] },
{
files: ['**/*.{js,jsx}'],
languageOptions: {
ecmaVersion: 2020,
globals: globals.browser,
parserOptions: {
ecmaVersion: 'latest',
ecmaFeatures: { jsx: true },
sourceType: 'module',
},
},
settings: { react: { version: '18.3' } },
plugins: {
react,
'react-hooks': reactHooks,
'react-refresh': reactRefresh,
},
rules: {
...js.configs.recommended.rules,
...react.configs.recommended.rules,
...react.configs['jsx-runtime'].rules,
...reactHooks.configs.recommended.rules,
'react/jsx-no-target-blank': 'off',
'react-refresh/only-export-components': [
'warn',
{ allowConstantExport: true },
],
},
},
]

13
src/MapClient/index.html Normal file
View File

@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite + React</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.jsx"></script>
</body>
</html>

4955
src/MapClient/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,31 @@
{
"name": "client",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"lint": "eslint .",
"preview": "vite preview"
},
"dependencies": {
"axios": "^1.7.9",
"ol": "^10.4.0",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-router-dom": "^7.1.4"
},
"devDependencies": {
"@eslint/js": "^9.17.0",
"@types/react": "^18.3.18",
"@types/react-dom": "^18.3.5",
"@vitejs/plugin-react": "^4.3.4",
"eslint": "^9.17.0",
"eslint-plugin-react": "^7.37.2",
"eslint-plugin-react-hooks": "^5.0.0",
"eslint-plugin-react-refresh": "^0.4.16",
"globals": "^15.14.0",
"vite": "^6.0.5"
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 102 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>

After

Width:  |  Height:  |  Size: 1.5 KiB

42
src/MapClient/src/App.css Normal file
View File

@ -0,0 +1,42 @@
#root {
max-width: 1280px;
margin: 0 auto;
padding: 2rem;
text-align: center;
}
.logo {
height: 6em;
padding: 1.5em;
will-change: filter;
transition: filter 300ms;
}
.logo:hover {
filter: drop-shadow(0 0 2em #646cffaa);
}
.logo.react:hover {
filter: drop-shadow(0 0 2em #61dafbaa);
}
@keyframes logo-spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
@media (prefers-reduced-motion: no-preference) {
a:nth-of-type(2) .logo {
animation: logo-spin infinite 20s linear;
}
}
.card {
padding: 2em;
}
.read-the-docs {
color: #888;
}

View File

@ -0,0 +1,8 @@
import React from "react";
import Home from "./pages/Home";
const App = () => {
return <Home />;
};
export default App;

View File

@ -0,0 +1,48 @@
import axios from "axios";
const API_BASE_URL = "http://localhost:8080/api/client";
// Fetch the center coordinates for the initial map load
export const fetchCenterCoordinates = async () => {
try {
const response = await axios.get(`${API_BASE_URL}/area`);
return response.data;
} catch (error) {
console.error("Error fetching center coordinates:", error);
return null;
}
};
// Fetch all hives and extract their latitude/longitude
export const fetchHives = async () => {
try {
const response = await axios.get(`${API_BASE_URL}/hive`);
return response.data.map(hive => ({
id: hive.hiveID,
lat: hive.telemetry?.location?.latitude ?? null,
lon: hive.telemetry?.location?.longitude ?? null,
})).filter(hive => hive.lat !== null && hive.lon !== null); // Remove invalid locations
} catch (error) {
console.error("Error fetching hives:", error);
return [];
}
};
// Move all hives to a new location
export const moveHives = async (lat, lon, ids) => {
try {
await axios.patch(`${API_BASE_URL}/hive`, {
Hives: ids,
Destination: {
Latitude: lat,
Longitude: lon
}
});
console.log(`Moved hives to: ${lat}, ${lon}`);
} catch (error) {
console.error("Error moving hives:", error);
throw error;
}
};

View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>

After

Width:  |  Height:  |  Size: 4.0 KiB

View File

@ -0,0 +1,182 @@
import React, { useEffect, useRef, useState } from "react";
import "ol/ol.css";
import { Map, View } from "ol";
import TileLayer from "ol/layer/Tile";
import { OSM } from "ol/source";
import VectorLayer from "ol/layer/Vector";
import VectorSource from "ol/source/Vector";
import { fromLonLat, toLonLat } from "ol/proj";
import { Point } from "ol/geom";
import { Feature } from "ol";
import { Style, Icon, Text, Fill, Stroke } from "ol/style";
import Popup from "./Popup";
import { fetchCenterCoordinates, fetchHives, moveHives } from "../api/mapService";
// TODO: Hardcoded marker icon path
const MARKER_ICON_URL = "/256x256.png";
const MapView = () => {
const mapRef = useRef(null);
const vectorLayerRef = useRef(null);
const initialized = useRef(false);
const [hives, setHives] = useState([]);
const [popup, setPopup] = useState({ visible: false, coords: null });
const [mouseCoords, setMouseCoords] = useState({ lat: "", lon: "" });
const popoverRef = useRef(null);
useEffect(() => {
const initializeMap = async () => {
if (initialized.current) return;
initialized.current = true;
try {
const center = await fetchCenterCoordinates();
if (center) {
initMap(center.latitude, center.longitude);
await fetchAndDrawHives();
}
// 🔄 Auto-fetch hives every 30 seconds
const interval = setInterval(fetchAndDrawHives, 5000);
return () => clearInterval(interval);
} catch (error) {
console.error("Error initializing map:", error);
}
};
initializeMap();
}, []);
// Initialize OpenLayers Map
const initMap = (lat, lon) => {
const map = new Map({
target: "map-container",
layers: [new TileLayer({ source: new OSM() })],
view: new View({ center: fromLonLat([lon, lat]), zoom: 12 }),
});
map.on("pointermove", (event) => handleMouseMove(event, map));
map.on("singleclick", (event) => handleMapClick(event, map));
mapRef.current = map;
};
// Fetch hives and draw them on the map
const fetchAndDrawHives = async () => {
try {
const data = await fetchHives();
setHives(data);
drawHives(data);
} catch (error) {
console.error("❌ Error fetching hives:", error);
}
};
// Draw markers for all hives
const drawHives = (hives) => {
if (!mapRef.current) return;
if (vectorLayerRef.current) mapRef.current.removeLayer(vectorLayerRef.current);
const vectorSource = new VectorSource();
hives.forEach((hive) => {
const feature = new Feature({
geometry: new Point(fromLonLat([hive.lon, hive.lat])),
});
feature.setId(hive.id);
feature.setStyle(
new Style({
image: new Icon({ src: MARKER_ICON_URL, scale: 0.05 }),
text: new Text({
text: hive.id,
fill: new Fill({ color: "#000" }),
stroke: new Stroke({ color: "#fff", width: 2 }),
offsetY: -20,
}),
})
);
feature.set("id", hive.id);
feature.set("lat", hive.lat);
feature.set("lon", hive.lon);
vectorSource.addFeature(feature);
});
const vectorLayer = new VectorLayer({ source: vectorSource });
vectorLayerRef.current = vectorLayer;
mapRef.current.addLayer(vectorLayer);
mapRef.current.on("pointermove", (event) => handleMarkerHover(event, mapRef.current));
};
// Handle Mouse Move (Show live coordinates)
const handleMouseMove = (event, map) => {
if (!map) return;
const coords = toLonLat(event.coordinate);
setMouseCoords({
lat: coords[1].toFixed(6),
lon: coords[0].toFixed(6),
});
};
// Show popover when hovering over a marker
const handleMarkerHover = (event, map) => {
if (!popoverRef.current) return;
const features = map.getFeaturesAtPixel(event.pixel);
if (features.length > 0) {
const feature = features[0];
popoverRef.current.innerHTML = `ID: ${feature.get("id")}<br>Lat: ${feature.get("lat")}<br>Lon: ${feature.get("lon")}`;
popoverRef.current.style.left = `${event.pixel[0] + 10}px`;
popoverRef.current.style.top = `${event.pixel[1] + 10}px`;
popoverRef.current.style.display = "block";
} else {
popoverRef.current.style.display = "none";
}
};
// Show popup when clicking an empty spot (Move Hives)
const handleMapClick = (event, map) => {
if (!map.getFeaturesAtPixel(event.pixel).length) {
const coords = toLonLat(event.coordinate);
setPopup({ visible: true, coords: { lat: coords[1].toFixed(6), lon: coords[0].toFixed(6) } });
}
};
return (
<div style={{ width: "100%", height: "100vh", display: "flex", flexDirection: "column", alignItems: "center" }}>
<h1>Hive Map</h1>
{/* Latitude & Longitude Inputs */}
<div style={{ marginBottom: "10px", display: "flex", gap: "10px" }}>
<label>Latitude: <input type="text" value={mouseCoords.lat} disabled /></label>
<label>Longitude: <input type="text" value={mouseCoords.lon} disabled /></label>
</div>
{/* Map Container */}
<div id="map-container" style={{ width: "80%", height: "80vh", border: "1px solid #ddd", position: "relative" }}></div>
{/* Tooltip for Marker Hover */}
<div ref={popoverRef} style={{
position: "absolute",
display: "none",
background: "#fff",
padding: "5px",
borderRadius: "5px",
border: "1px solid #000",
pointerEvents: "none",
zIndex: 999
}}></div>
{/* Move All Hives Popup (Centered Modal) */}
<Popup
isVisible={popup.visible}
coords={popup.coords}
onConfirm={() => moveHives(popup.coords.lat, popup.coords.lon, hives.map(h => h.id))}
onCancel={() => setPopup({ visible: false })}
/>
</div>
);
};
export default MapView;

View File

@ -0,0 +1,52 @@
import React from "react";
const Popup = ({ isVisible, coords, onConfirm, onCancel }) => {
if (!isVisible || !coords) return null;
// Copy coordinates to clipboard
const copyCoordinates = async () => {
const textToCopy = `[${coords.lat}, ${coords.lon}]`;
try {
await navigator.clipboard.writeText(textToCopy);
alert("Coordinates copied to clipboard!");
} catch (error) {
console.error("Error copying coordinates:", error);
}
};
return (
<div style={{
position: "fixed",
top: "0",
left: "0",
width: "100vw",
height: "100vh",
backgroundColor: "rgba(0, 0, 0, 0.5)", // Semi-transparent background
display: "flex",
alignItems: "center",
justifyContent: "center",
zIndex: 1000
}}>
<div style={{
backgroundColor: "white",
padding: "20px",
boxShadow: "0px 0px 15px rgba(0,0,0,0.3)",
borderRadius: "8px",
textAlign: "center",
minWidth: "300px"
}}>
<h3>Move all hives to:</h3>
<p>Lat: {coords.lat} | Lon: {coords.lon}</p>
{/* Copy Coordinates Button */}
<button onClick={copyCoordinates} style={{ marginBottom: "10px", display: "block", width: "100%" }}>Copy Coordinates</button>
{/* Move Hives & Cancel Buttons */}
<button onClick={() => onConfirm(coords)} style={{ marginRight: "10px" }}>Move Hives</button>
<button onClick={onCancel}>Cancel</button>
</div>
</div>
);
};
export default Popup;

View File

@ -0,0 +1,68 @@
:root {
font-family: Inter, system-ui, Avenir, Helvetica, Arial, sans-serif;
line-height: 1.5;
font-weight: 400;
color-scheme: light dark;
color: rgba(255, 255, 255, 0.87);
background-color: #242424;
font-synthesis: none;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
a {
font-weight: 500;
color: #646cff;
text-decoration: inherit;
}
a:hover {
color: #535bf2;
}
body {
margin: 0;
display: flex;
place-items: center;
min-width: 320px;
min-height: 100vh;
}
h1 {
font-size: 3.2em;
line-height: 1.1;
}
button {
border-radius: 8px;
border: 1px solid transparent;
padding: 0.6em 1.2em;
font-size: 1em;
font-weight: 500;
font-family: inherit;
background-color: #1a1a1a;
cursor: pointer;
transition: border-color 0.25s;
}
button:hover {
border-color: #646cff;
}
button:focus,
button:focus-visible {
outline: 4px auto -webkit-focus-ring-color;
}
@media (prefers-color-scheme: light) {
:root {
color: #213547;
background-color: #ffffff;
}
a:hover {
color: #747bff;
}
button {
background-color: #f9f9f9;
}
}

View File

@ -0,0 +1,10 @@
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import './styles/global.css'; // Optional global styles
ReactDOM.createRoot(document.getElementById('root')).render(
<React.StrictMode>
<App />
</React.StrictMode>
);

View File

@ -0,0 +1,12 @@
import React from "react";
import MapView from "../components/MapView";
const Home = () => {
return (
<div>
<MapView />
</div>
);
};
export default Home;

View File

@ -0,0 +1,5 @@
body {
margin: 0;
font-family: Arial, sans-serif;
background-color: #f5f5f5;
}

View File

View File

@ -0,0 +1,10 @@
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
export default defineConfig({
plugins: [react()],
server: {
host: '0.0.0.0',
port: 3000
}
})