Proof Of Concept initial

Adds initial files for a proof-of-concept project, including Dockerfile, .gitignore, project files, and MQTT-related services.

This commit sets up the basic structure and configuration for exploring and validating the core concepts of the project.
This commit is contained in:
2025-08-06 15:40:21 +02:00
parent bbc704fe6b
commit 043f504cdd
11 changed files with 1019 additions and 41 deletions

View File

@@ -0,0 +1,21 @@

Microsoft Visual Studio Solution File, Format Version 12.00
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ProofOfConcept", "ProofOfConcept\ProofOfConcept.csproj", "{93F01B86-2434-42E2-AE67-774BA61CFF7B}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{76B8DCB6-06D8-4E9B-8144-693F7FC28DB9}"
ProjectSection(SolutionItems) = preProject
compose.yaml = compose.yaml
EndProjectSection
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{93F01B86-2434-42E2-AE67-774BA61CFF7B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{93F01B86-2434-42E2-AE67-774BA61CFF7B}.Debug|Any CPU.Build.0 = Debug|Any CPU
{93F01B86-2434-42E2-AE67-774BA61CFF7B}.Release|Any CPU.ActiveCfg = Release|Any CPU
{93F01B86-2434-42E2-AE67-774BA61CFF7B}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
EndGlobal

View File

@@ -1,10 +1,10 @@
FROM mcr.microsoft.com/dotnet/aspnet:10.0 AS base
FROM mcr.microsoft.com/dotnet/aspnet:10.0-preview AS base
USER $APP_UID
WORKDIR /app
EXPOSE 8080
EXPOSE 8081
FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build
FROM mcr.microsoft.com/dotnet/sdk:10.0-preview AS build
ARG BUILD_CONFIGURATION=Release
WORKDIR /src
COPY ["ProofOfConcept/ProofOfConcept.csproj", "ProofOfConcept/"]

View File

@@ -0,0 +1,31 @@
using Microsoft.Extensions.Caching.Memory;
using ProofOfConcept.Services;
var builder = WebApplication.CreateSlimBuilder(args);
// builder.Services.ConfigureHttpJsonOptions(options => { options.SerializerOptions.TypeInfoResolverChain.Insert(0, AppJsonSerializerContext.Default); });
builder.Services.AddOpenApi();
builder.Services.AddMediator();
builder.Services.AddMemoryCache();
builder.Services.AddHybridCache();
builder.Services.AddSingleton<IMessageProcessor, MessageProcessor>();
builder.Services.AddHostedService<MQTTServer>();
builder.Services.AddHostedService<MQTTClient>();
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.MapOpenApi();
}
//Map tesla required public key file
app.MapGet("/.well-known/appspecific/com.tesla.3p.public-key.pem", (IMemoryCache memoryCache) => memoryCache.GetOrCreateAsync("publicKeyCert", async (_) => await File.ReadAllTextAsync("Resources/Signature/public-key.pem")));
//Map an under constrcution page...
app.Map("/", ()=> "Under construction...");
app.Run();

View File

@@ -0,0 +1,42 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<NoDefaultLaunchSettingsFile>true</NoDefaultLaunchSettingsFile>
<InvariantGlobalization>true</InvariantGlobalization>
<PublishAot>true</PublishAot>
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Mediator.Abstractions" Version="2.1.7" />
<PackageReference Include="Mediator.SourceGenerator" Version="2.1.7">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="10.0.0-preview.6.25358.103"/>
<PackageReference Include="Microsoft.Extensions.Caching.Hybrid" Version="9.7.0" />
<PackageReference Include="MQTTnet" Version="5.0.1.1416" />
<PackageReference Include="MQTTnet.Server" Version="5.0.1.1416" />
</ItemGroup>
<ItemGroup>
<Content Include="..\.dockerignore">
<Link>.dockerignore</Link>
</Content>
</ItemGroup>
<ItemGroup>
<Folder Include="Models\" />
<Folder Include="Utilities\" />
</ItemGroup>
<ItemGroup>
<None Update="Resources\Signature\public-key.pem">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>

View File

@@ -1,20 +1,61 @@
using Microsoft.Extensions.Options;
using MQTTnet;
namespace ProofOfConcept.Services;
public class MQTTClient
public class MQTTClient : IHostedService
{
private ILogger<MQTTClient> logger;
private MQTTClientConfiguration configuration;
private MQTTServerConfiguration serverConfiguration;
public MQTTClient(ILogger<MQTTClient> logger, IOptionsMonitor<MQTTClientConfiguration> options)
private readonly IMqttClient client;
public MQTTClient(ILogger<MQTTClient> logger, IOptions<MQTTClientConfiguration> options, IOptions<MQTTServerConfiguration> serverOptions, IMessageProcessor messageProcessor)
{
this.logger = logger;
this.configuration = options.CurrentValue;
options.OnChange(newValue =>
this.configuration = options.Value;
this.serverConfiguration = serverOptions.Value;
client = new MqttClientFactory().CreateMqttClient();
this.client.ApplicationMessageReceivedAsync += (e) =>
{
this.configuration = newValue;
logger.LogInformation("Configuration of {ClassName} changed", nameof(MQTTClient));
});
logger.LogInformation("Message received: {Message}", e.ApplicationMessage.Payload);
messageProcessor.ProcessMessage(e.ApplicationMessage.Payload.ToString());
return Task.CompletedTask;
};
}
public async Task StartAsync(CancellationToken cancellationToken)
{
this.logger.LogTrace("Stating...");
MqttClientOptions options = new MqttClientOptionsBuilder()
.WithTcpServer("localhost", this.serverConfiguration.Port)
.WithClientId(this.serverConfiguration.LocalClient.ClientID)
.WithCredentials(this.serverConfiguration.LocalClient.Username, this.serverConfiguration.LocalClient.Password)
.Build();
await this.client.ConnectAsync(options, cancellationToken);
this.logger.LogTrace("Connected");
await this.client.SubscribeAsync("telemetry", cancellationToken: cancellationToken);
this.logger.LogTrace("Subscribed");
this.logger.LogInformation("Started");
}
public async Task StopAsync(CancellationToken cancellationToken)
{
logger.LogTrace("Stopping...");
await this.client.UnsubscribeAsync("telemetry", cancellationToken: cancellationToken);
this.logger.LogTrace("Unsubscribed");
await this.client.DisconnectAsync(cancellationToken: cancellationToken);
this.logger.LogTrace("Disconnected");
logger.LogInformation("Stopped");
}
}

View File

@@ -1,24 +1,154 @@
using System.Net;
using Microsoft.Extensions.Options;
using MQTTnet.Protocol;
using MQTTnet.Server;
namespace ProofOfConcept.Services;
public class MQTTServer
public class MQTTServer : IHostedService
{
private ILogger<MQTTServer> logger;
private MQTTServerConfiguration configuration;
private readonly ILogger<MQTTServer> logger;
private readonly MQTTServerConfiguration configuration;
public MQTTServer(ILogger<MQTTServer> logger, IOptionsMonitor<MQTTServerConfiguration> options)
private readonly MqttServer server;
public MQTTServer(ILogger<MQTTServer> logger, IOptions<MQTTServerConfiguration> options)
{
this.logger = logger;
this.configuration = options.CurrentValue;
this.configuration = options.Value;
options.OnChange(newValue =>
MqttServerOptions mqttServerOptions = new MqttServerOptionsBuilder().WithDefaultEndpoint().WithDefaultEndpointPort(this.configuration.Port).WithKeepAlive().Build();
this.server = new MqttServerFactory().CreateMqttServer(mqttServerOptions);
this.server.ClientConnectedAsync += (e) =>
{
this.configuration = newValue;
logger.LogInformation("Configuration of {ClassName} changed", nameof(MQTTServer));
});
logger.LogInformation("Client connected from: {IPAddress}. ClientID: {ClientID}", e.RemoteEndPoint.ToString(), e.ClientId);
return Task.CompletedTask;
};
this.server.ClientDisconnectedAsync += (e) =>
{
logger.LogInformation("Client {ClientID} disconnected from: {IPAddress}. Reason: {ReasonString} ({ReasonCode})", e.ClientId, e.RemoteEndPoint.ToString(), e.ReasonString, e.ReasonCode);
return Task.CompletedTask;
};
this.server.ClientSubscribedTopicAsync += (e) =>
{
logger.LogInformation("Client {ClientID} subscribed to topic: {Topic}", e.ClientId, e.TopicFilter.Topic);
return Task.CompletedTask;
};
this.server.ClientUnsubscribedTopicAsync += (e) =>
{
logger.LogInformation("Client {ClientID} unsubscribed from topic: {Topic}", e.ClientId, e.TopicFilter);
return Task.CompletedTask;
};
this.server.InterceptingPublishAsync += (e) =>
{
if (e.ApplicationMessage.Topic == "telemetry" && e.ClientId != this.configuration.TelemetryClient.ClientID)
{
logger.LogWarning("Client {ClientID} tried to publish to telemetry topic", e.ClientId);
e.Response.ReasonCode = MqttPubAckReasonCode.NotAuthorized;
return Task.CompletedTask;
}
logger.LogInformation("Client {ClientID} published message to topic: {Topic}", e.ClientId, e.ApplicationMessage.Topic);
return Task.CompletedTask;
};
this.server.ValidatingConnectionAsync += (e) =>
{
//Local client (by clientID)
if (e.ClientId == this.configuration.LocalClient.ClientID)
{
//Not local connection (IP is not loopback)
if (e.RemoteEndPoint is IPEndPoint ipEndPoint && !IPAddress.IsLoopback(ipEndPoint.Address))
{
logger.LogWarning("Local client tried to connect from non-loopback address: {IPAddress}", ipEndPoint.ToString());
e.ReasonCode = MqttConnectReasonCode.NotAuthorized;
}
//Invalid username or password
else if (e.UserName != configuration.LocalClient.Username || e.Password != configuration.LocalClient.Password)
{
logger.LogWarning("Local client tried to connect with invalid credentials");
e.ReasonCode = MqttConnectReasonCode.NotAuthorized;
}
}
//Telemetry client
else if (e.ClientId == this.configuration.TelemetryClient.ClientID)
{
if (e.UserName != configuration.TelemetryClient.Username || e.Password != configuration.TelemetryClient.Password)
{
logger.LogWarning("Telemetry client tried to connect with invalid credentials");
e.ReasonCode = MqttConnectReasonCode.NotAuthorized;
}
}
//Observer
else if ((this.configuration.Observer.ClientID is not null && e.ClientId == this.configuration.Observer.ClientID) || this.configuration.Observer.ClientID is null)
{
if (e.UserName != configuration.Observer.Username || e.Password != configuration.Observer.Password)
{
logger.LogWarning("Observer tried to connect with invalid credentials");
e.ReasonCode = MqttConnectReasonCode.NotAuthorized;
}
}
else
e.ReasonCode = MqttConnectReasonCode.Banned;
return Task.CompletedTask;
};
}
public async Task StartAsync(CancellationToken cancellationToken)
{
this.logger.LogTrace("Starting MQTT Server...");
await this.server.StartAsync();
this.logger.LogInformation("MQTT Server started");
}
public async Task StopAsync(CancellationToken cancellationToken)
{
this.logger.LogTrace("Stopping MQTT Server...");
await this.server.StopAsync();
this.logger.LogInformation("MQTT Server stopped");
}
}
public class MQTTServerConfiguration
{
public ushort Port { get; set; } = 1883;
public MQTTAuthenticationData TelemetryClient { get; set; } = new MQTTAuthenticationData("telemetry", "fleet", "9R0FXNs5NEIEbI4"); //Must have a known client id
public MQTTAuthenticationData LocalClient { get; set; } = new MQTTAuthenticationData("local", "client", "xuhvoc-parrox-xuzsE4"); //Must have a known client id
public MQTTAuthenticationData Observer { get; set; } = new MQTTAuthenticationData("observer", "JC740d4c4E9dveh");
}
public class MQTTAuthenticationData
{
public string? ClientID { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public MQTTAuthenticationData(string clientId, string username, string password)
{
ClientID = clientId;
Username = username;
Password = password;
}
public MQTTAuthenticationData(string username, string password)
{
ClientID = null;
Username = username;
Password = password;
}
}

View File

@@ -1,20 +1,31 @@
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Options;
namespace ProofOfConcept.Services;
public class MessageProcessor
public interface IMessageProcessor
{
private ILogger<MessageProcessor> logger;
Task ProcessMessage(string jsonMessage);
}
public class MessageProcessor : IMessageProcessor
{
private readonly ILogger<MessageProcessor> logger;
private MessageProcessorConfiguration configuration;
public MessageProcessor(ILogger<MessageProcessor> logger, IOptionsMonitor<MessageProcessorConfiguration> options)
private readonly IMemoryCache memoryCache;
public MessageProcessor(ILogger<MessageProcessor> logger, IOptions<MessageProcessorConfiguration> options, IMemoryCache memoryCache)
{
this.logger = logger;
this.configuration = options.CurrentValue;
this.configuration = options.Value;
options.OnChange(newValue =>
{
this.configuration = newValue;
logger.LogInformation("Configuration of {ClassName} changed", nameof(MessageProcessor));
});
this.memoryCache = memoryCache;
}
public async Task ProcessMessage(string jsonMessage)
{
this.logger.LogTrace("Processing message from Tesla: {Message}", jsonMessage);
}
}

View File

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

View File

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