Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 47 additions & 0 deletions ServiceHub/Modules/ServiceHub.Modules.MQTT/MqttModule.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
using MQTTnet.Diagnostics.Logger;
using MQTTnet.Server;
using ServiceHub.Contracts.Enums;
using ServiceHub.Contracts.Interfaces;

namespace ServiceHub.Modules.MQTT
{
public class MqttModule : IServiceModule
{
private MqttServer? _server = null;
private ILogContext? _log = null;

public string Name => "MqttModule";

public void Initialize(ILogContext log, IServiceContext config)
{
_log = log;
_log.Info($"{Name} initialized.");
}

public Task StartAsync(CancellationToken token)
{
Stop();

var logger = new MqttNetEventLogger();

logger.LogMessagePublished += (o, e) =>
{
switch (e.LogMessage.Level)
{
case MqttNetLogLevel.Error: _log?.Error($"{Name} {e.LogMessage.Message}"); break;
case MqttNetLogLevel.Warning: _log?.Warning($"{Name} {e.LogMessage.Message}"); break;
case MqttNetLogLevel.Info:
case MqttNetLogLevel.Verbose: _log?.Info($"{Name} {e.LogMessage.Message}"); break;
}
};

_server = new MqttServerFactory(logger).CreateMqttServer(new MqttServerOptions());

return _server.StartAsync();
}

public ServiceState State() => (_server?.IsStarted ?? false ) ? ServiceState.Running : ServiceState.Stoped;

public void Stop() => _server?.StopAsync().Wait();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="MQTTnet.Server" Version="5.0.1.1416" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\..\ServiceHub.Contracts\ServiceHub.Contracts.csproj" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
Expand Up @@ -14,17 +14,17 @@ public class StaticWebModule : IServiceModule
private WebServer? _server;
private CancellationToken _token;
private ILogContext? _logContext;
private IConfigContext? _configContext;
private IServiceContext? _configContext;

public string Name => "StaticWebModule";

public void Initialize(ILogContext log, IConfigContext config)
public void Initialize(ILogContext log, IServiceContext config)
{
_logContext = log;
_configContext = config;

var port = _configContext.Get("port") ?? "8080";
var root = _configContext.Get("directory") ?? "wwwroot";
var port = _configContext.Get("parameters:port") ?? "8080";
var root = _configContext.Get("parameters:directory") ?? "wwwroot";

_port = int.Parse(port);
_directory = root;
Expand All @@ -34,6 +34,8 @@ public void Initialize(ILogContext log, IConfigContext config)

public async Task StartAsync(CancellationToken token)
{
Stop();

_token = token;

var fileProvider = new PhysicalFileProvider(_directory);
Expand Down
13 changes: 0 additions & 13 deletions ServiceHub/ServiceHub.Contracts/Interfaces/IConfigContext.cs

This file was deleted.

22 changes: 22 additions & 0 deletions ServiceHub/ServiceHub.Contracts/Interfaces/IServiceContext.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
using ServiceHub.Contracts.Classes;
using System.Text.Json;

namespace ServiceHub.Contracts.Interfaces
{
public interface IServiceContext
{
string? Value { get; }

void SetNode(string path);

void ResetNode();

IServiceContext[] Items { get; }

void LoadJson(string json);

string? Get(string path);

IServiceContext? GetConfig(string path);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ namespace ServiceHub.Contracts.Interfaces
public interface IServiceModule
{
string Name { get; }
void Initialize(ILogContext log, IConfigContext config);
void Initialize(ILogContext log, IServiceContext config);
Task StartAsync(CancellationToken token);
void Stop();
ServiceState State();
Expand Down
38 changes: 28 additions & 10 deletions ServiceHub/ServiceHub.Core/Classes/SimpleContext.cs
Original file line number Diff line number Diff line change
@@ -1,23 +1,37 @@
using ServiceHub.Contracts.Interfaces;
using System.Text.Json;
using System.Xml.Linq;

namespace ServiceHub.Core.Classes
{
public class SimpleContext : IConfigContext
public class SimpleContext : IServiceContext
{
internal ConfigNode Root { get; } = new();
private ConfigNode Root { get; } = new ();

private ConfigNode? Node { get; set; } = null;

public string? Value
{
get
{
if (Root == null)
return null;
return Root.Value;
if (Node == null)
return Root.Value;
return Node.Value;
}
}

public IConfigContext[] Items { get => Root.Items.Select(x => new SimpleContext(x)).ToArray(); }
public void SetNode(string path)
{
if (Root == null)
return;
Node = Traverse(path);
}

public void ResetNode() {
Node = null;
}

public IServiceContext[] Items { get => (Node ?? Root).Items.Select(x => new SimpleContext(x)).ToArray(); }

public SimpleContext() { }
internal SimpleContext(ConfigNode root) { Root = root; }
Expand Down Expand Up @@ -59,12 +73,16 @@ private void LoadElement(ConfigNode node, JsonElement element)

public string? Get(string path) => Traverse(path)?.Value;

public IConfigContext? GetConfig(string path) => Traverse(path);
public IServiceContext? GetConfig(string path)
{
var data = Traverse(path);
return data == null ? null : (IServiceContext) new SimpleContext(data);
}

private IConfigContext? Traverse(string path)
private ConfigNode? Traverse(string path)
{
var parts = path.Split(':', StringSplitOptions.RemoveEmptyEntries);
ConfigNode current = Root;
ConfigNode? current = Node ?? Root;

foreach (var part in parts)
{
Expand All @@ -78,7 +96,7 @@ private void LoadElement(ConfigNode node, JsonElement element)
return null;
}

return new SimpleContext(current);
return current;
}
}
}
10 changes: 5 additions & 5 deletions ServiceHub/ServiceHub.Core/Model/ServiceInstance.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ internal sealed class ServiceInstance
{
private string _serviceName;
private IServiceModule? _serviceModule { get; set; }
private IConfigContext _config { get; set; }
private IServiceContext _config { get; set; }
private ILogContext _log { get; set; }
public ServiceState State => _serviceModule?.State() ?? ServiceState.Error;

Expand All @@ -17,7 +17,7 @@ internal sealed class ServiceInstance

public void Stop(CancellationToken ct) => _serviceModule?.Stop();

public ServiceInstance(ILogContext log, IConfigContext config, Type type)
public ServiceInstance(ILogContext log, IServiceContext config, Type type)
{
_config = config;
_log = log;
Expand All @@ -26,7 +26,7 @@ public ServiceInstance(ILogContext log, IConfigContext config, Type type)
if (string.IsNullOrEmpty(_serviceName))
throw new ArgumentNullException("name");

IConfigContext? contextValue = config.GetConfig("parameters");
IServiceContext? contextValue = config.GetConfig("parameters");
if (contextValue == null)
throw new ArgumentNullException("parameters");

Expand All @@ -35,8 +35,8 @@ public ServiceInstance(ILogContext log, IConfigContext config, Type type)
if (!typeof(IServiceModule).IsAssignableFrom(type) || type.IsAbstract)
throw new Exception($"The {type.Name} Module is not valid" );

_serviceModule = (IServiceModule)Activator.CreateInstance(type);
_serviceModule?.Initialize(log, contextValue);
_serviceModule = (IServiceModule?)Activator.CreateInstance(type);
_serviceModule?.Initialize(log, config);
}
catch (Exception ex)
{
Expand Down
4 changes: 2 additions & 2 deletions ServiceHub/ServiceHub.Core/ServiceHub.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ private ServiceHub() { }

#region Public Methods

public bool InitModule(ILogContext log, IConfigContext config)
public bool InitModule(ILogContext log, IServiceContext config)
{
var typeService = config.Get("type") ?? string.Empty;

Expand Down Expand Up @@ -87,7 +87,7 @@ public void LoadModules(ILogContext log, string folderPath)
if (!typeof(IServiceModule).IsAssignableFrom(type) || type.IsAbstract)
continue;

var name = ((IServiceModule)Activator.CreateInstance(type))?.Name;
var name = ((IServiceModule?)Activator.CreateInstance(type))?.Name;
if (!string.IsNullOrWhiteSpace(name))
{
_availableModules.Add(name ?? string.Empty, type);
Expand Down
20 changes: 16 additions & 4 deletions ServiceHub/ServiceHub.Host/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,11 @@ static void Main(string[] args)
""port"": ""8080"",
""root"": ""wwwroot""
}
},
{
""name"": ""MqttIot"",
""type"": ""MqttModule"",
""parameters"": { }
}
]
}");
Expand All @@ -28,12 +33,19 @@ static void Main(string[] args)
throw new Exception("Json Config is not valid");

log.Info("ServiceHub running...");
foreach (var localContext in context.GetConfig("services").Items)
{
Core.ServiceHub.Instance.InitModule(log, localContext);
Core.ServiceHub.Instance.Start(localContext.Get("name"));

var servicesCount = context.GetConfig("services")?.Items.Count() ?? 0;

for (int i = 0; i<servicesCount; i++)
{
context.SetNode($"services:{i}");
Core.ServiceHub.Instance.InitModule(log, context);
context.ResetNode();
}

foreach (var item in Core.ServiceHub.Instance.ServicesInitialized)
Core.ServiceHub.Instance.Start(item);

log.Info("Press any key to stop...");
Console.ReadKey();

Expand Down
1 change: 1 addition & 0 deletions ServiceHub/ServiceHub.slnx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
<Solution>
<Folder Name="/Modules/">
<Project Path="Modules/ServiceHub.Modules.MQTT/ServiceHub.Modules.MQTT.csproj" Id="843066df-dcc6-4628-89ae-7a8434b09fc8" />
<Project Path="Modules/ServiceHub.Modules.StaticWeb/ServiceHub.Modules.StaticWeb.csproj" Id="28cb6fb7-ed37-43c0-b33c-4ed5abed6da5" />
</Folder>
<Project Path="ServiceHub.Contracts/ServiceHub.Contracts.csproj" Id="7da400b7-55ec-4153-b60d-ac2d50c570f6" />
Expand Down