notifier service
This commit is contained in:
parent
f2a338a855
commit
954cd1c3de
55
MQTTProcessNotifier/MQTTConnection.cs
Normal file
55
MQTTProcessNotifier/MQTTConnection.cs
Normal file
@ -0,0 +1,55 @@
|
||||
using MQTTnet.Client;
|
||||
using MQTTnet;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using MQTTnet.Samples.Helpers;
|
||||
using MQTTnet.Server;
|
||||
using MQTTProcessNotifierLib;
|
||||
|
||||
namespace MQTTProcessNotifier
|
||||
{
|
||||
internal class MQTTConnection
|
||||
{
|
||||
public static async Task<IMqttClient> Connect_Client(MonitoringConfig config, ILogger logger)
|
||||
{
|
||||
var mqttFactory = new MqttFactory();
|
||||
var mqttClient = mqttFactory.CreateMqttClient();
|
||||
|
||||
var willTopic = $"{config.MQTTEntityName}/{config.SystemName}/status";
|
||||
var mqttClientOptions = new MqttClientOptionsBuilder()
|
||||
.WithTcpServer(config.MQTTHostName)
|
||||
.WithCredentials(config.MQTTUserName, config.MQTTPassword)
|
||||
.WithWillDelayInterval(config.TimeoutSeconds * 60 * 1000)
|
||||
.WithWillPayload("disconnected")
|
||||
.WithWillTopic(willTopic)
|
||||
.Build();
|
||||
var response = await mqttClient.ConnectAsync(mqttClientOptions, CancellationToken.None);
|
||||
logger.LogInformation("The MQTT client is connected.");
|
||||
response.DumpToConsole();
|
||||
return mqttClient;
|
||||
|
||||
}
|
||||
public static async Task Disconnect_Client(IMqttClient client)
|
||||
{
|
||||
var mqttFactory = new MqttFactory();
|
||||
var mqttClientDisconnectOptions = mqttFactory.CreateClientDisconnectOptionsBuilder().Build();
|
||||
await client.DisconnectAsync(mqttClientDisconnectOptions, CancellationToken.None);
|
||||
client.Dispose();
|
||||
}
|
||||
public static Task<MqttClientPublishResult> Publish_Message(IMqttClient client, string topic, string message, ILogger logger)
|
||||
{
|
||||
var applicationMessage = new MqttApplicationMessageBuilder()
|
||||
.WithTopic(topic)
|
||||
.WithPayload(message)
|
||||
.WithMessageExpiryInterval(5*60*1000)
|
||||
.Build();
|
||||
|
||||
logger.LogInformation($"Publishing message to topic {topic} with payload {message}");
|
||||
return client.PublishAsync(applicationMessage, CancellationToken.None);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
19
MQTTProcessNotifier/MQTTProcessNotifier.csproj
Normal file
19
MQTTProcessNotifier/MQTTProcessNotifier.csproj
Normal file
@ -0,0 +1,19 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.Worker">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net7.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<UserSecretsId>dotnet-MQTTProcessNotifier-311d0628-525d-4ab7-b11f-d23b6347a970</UserSecretsId>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Extensions.Hosting" Version="7.0.0" />
|
||||
<PackageReference Include="MQTTnet" Version="4.1.4.563" />
|
||||
<PackageReference Include="Newtonsoft.Json" Version="13.0.2" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\MQTTProcessNotifierLib\MQTTProcessNotifierLib.csproj" />
|
||||
</ItemGroup>
|
||||
</Project>
|
37
MQTTProcessNotifier/MQTTProcessNotifier.sln
Normal file
37
MQTTProcessNotifier/MQTTProcessNotifier.sln
Normal file
@ -0,0 +1,37 @@
|
||||
|
||||
Microsoft Visual Studio Solution File, Format Version 12.00
|
||||
# Visual Studio Version 17
|
||||
VisualStudioVersion = 17.4.33122.133
|
||||
MinimumVisualStudioVersion = 10.0.40219.1
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MQTTProcessNotifier", "MQTTProcessNotifier.csproj", "{37205DB2-0B26-4DBA-8477-B2D3EE6FF0AD}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ConfigUI", "..\ConfigUI\ConfigUI.csproj", "{B1110F79-C92D-4B51-80C7-33D022ABF173}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MQTTProcessNotifierLib", "..\MQTTProcessNotifierLib\MQTTProcessNotifierLib.csproj", "{7B7516A7-017F-4B75-A904-429109B00837}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
Release|Any CPU = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
||||
{37205DB2-0B26-4DBA-8477-B2D3EE6FF0AD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{37205DB2-0B26-4DBA-8477-B2D3EE6FF0AD}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{37205DB2-0B26-4DBA-8477-B2D3EE6FF0AD}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{37205DB2-0B26-4DBA-8477-B2D3EE6FF0AD}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{B1110F79-C92D-4B51-80C7-33D022ABF173}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{B1110F79-C92D-4B51-80C7-33D022ABF173}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{B1110F79-C92D-4B51-80C7-33D022ABF173}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{B1110F79-C92D-4B51-80C7-33D022ABF173}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{7B7516A7-017F-4B75-A904-429109B00837}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{7B7516A7-017F-4B75-A904-429109B00837}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{7B7516A7-017F-4B75-A904-429109B00837}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{7B7516A7-017F-4B75-A904-429109B00837}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
EndGlobalSection
|
||||
GlobalSection(ExtensibilityGlobals) = postSolution
|
||||
SolutionGuid = {6A8AE2A3-E647-4632-A3B8-60E6F7DBCE9B}
|
||||
EndGlobalSection
|
||||
EndGlobal
|
10
MQTTProcessNotifier/Program.cs
Normal file
10
MQTTProcessNotifier/Program.cs
Normal file
@ -0,0 +1,10 @@
|
||||
using MQTTProcessNotifier;
|
||||
|
||||
IHost host = Host.CreateDefaultBuilder(args)
|
||||
.ConfigureServices(services =>
|
||||
{
|
||||
services.AddHostedService<Worker>();
|
||||
})
|
||||
.Build();
|
||||
|
||||
host.Run();
|
11
MQTTProcessNotifier/Properties/launchSettings.json
Normal file
11
MQTTProcessNotifier/Properties/launchSettings.json
Normal file
@ -0,0 +1,11 @@
|
||||
{
|
||||
"profiles": {
|
||||
"MQTTProcessNotifier": {
|
||||
"commandName": "Project",
|
||||
"dotnetRunMessages": true,
|
||||
"environmentVariables": {
|
||||
"DOTNET_ENVIRONMENT": "Development"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
91
MQTTProcessNotifier/Worker.cs
Normal file
91
MQTTProcessNotifier/Worker.cs
Normal file
@ -0,0 +1,91 @@
|
||||
using MQTTnet.Client;
|
||||
using MQTTnet.Samples.Helpers;
|
||||
using Newtonsoft.Json;
|
||||
using System.Diagnostics;
|
||||
using System.Xml;
|
||||
using MQTTProcessNotifierLib;
|
||||
|
||||
namespace MQTTProcessNotifier;
|
||||
public class Worker : BackgroundService
|
||||
{
|
||||
private readonly ILogger<Worker> _logger;
|
||||
private IMqttClient? client;
|
||||
private string parentTopic;
|
||||
private List<MonitoredProcess>? monitoredProcesses;
|
||||
public Worker(ILogger<Worker> logger)
|
||||
{
|
||||
this._logger = logger;
|
||||
this.parentTopic = "default";
|
||||
}
|
||||
private List<MonitoredProcess> findMatchingProcesses(List<Process> runningProcesses, List<MonitoredProcess> monitoredProcesses)
|
||||
{
|
||||
monitoredProcesses.ForEach(
|
||||
monitoredProcess =>
|
||||
monitoredProcess.Running = runningProcesses
|
||||
.FindAll(
|
||||
(Process windowsProcess) =>
|
||||
windowsProcess.ProcessName == monitoredProcess.ProcessName).Count > 0
|
||||
);
|
||||
monitoredProcesses.ForEach(x => _logger.LogDebug(x.ToString()));
|
||||
return monitoredProcesses;
|
||||
}
|
||||
private List<MonitoredProcess> getListOfMonitoredProcesses(MonitoringConfig config)
|
||||
{
|
||||
var list = new List<MonitoredProcess>();
|
||||
config.ProcessNames.ForEach(processName => list.Add(new MonitoredProcess(processName, processName.ToLower())));
|
||||
return list;
|
||||
}
|
||||
private MonitoringConfig ReadConfig()
|
||||
{
|
||||
var localAppDataPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
|
||||
var configFolderPath = Path.Combine(localAppDataPath, "processnotifier");
|
||||
if (Directory.Exists(configFolderPath))
|
||||
{
|
||||
var configPath = Path.Combine(localAppDataPath, "processnotifier", "config.json");
|
||||
var fileContent = File.ReadAllText(configPath);
|
||||
if (fileContent == ""|| fileContent == null) return new MonitoringConfig("processnotifier", new List<string>(), "localhost", "processnotifier", "", "processnotifier", 30);
|
||||
else return JsonConvert.DeserializeObject<MonitoringConfig>(fileContent);
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new Exception("No Config found!");
|
||||
}
|
||||
}
|
||||
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
var config = this.ReadConfig();
|
||||
|
||||
this.parentTopic = $"{config.SystemName}";
|
||||
this.monitoredProcesses = getListOfMonitoredProcesses(config);
|
||||
|
||||
this.client = await MQTTConnection.Connect_Client(config, _logger);
|
||||
monitoredProcesses.ForEach(x => _logger.LogDebug(x.ToString()));
|
||||
while (!stoppingToken.IsCancellationRequested)
|
||||
{
|
||||
await MQTTConnection.Publish_Message(client, $"{config.MQTTEntityName}/{parentTopic}/status", "connected", _logger);
|
||||
|
||||
Process[] allProcesses = Process.GetProcesses();
|
||||
this.findMatchingProcesses(allProcesses.ToList(), monitoredProcesses)
|
||||
.ForEach(async item =>
|
||||
await MQTTConnection.Publish_Message(client, $"{config.MQTTEntityName}/{parentTopic}/{item.TopicID}", $"{(item.Running ? "on" : "off")}", _logger)
|
||||
);
|
||||
await Task.Delay(5000, stoppingToken);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogInformation(ex.GetType().ToString());
|
||||
if (ex.GetType() == typeof(TaskCanceledException))
|
||||
{
|
||||
_logger.LogError(ex.Message);
|
||||
}
|
||||
else
|
||||
{
|
||||
_logger.LogError(ex.Message);
|
||||
Environment.Exit(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
8
MQTTProcessNotifier/appsettings.Development.json
Normal file
8
MQTTProcessNotifier/appsettings.Development.json
Normal file
@ -0,0 +1,8 @@
|
||||
{
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
"Microsoft.Hosting.Lifetime": "Information"
|
||||
}
|
||||
}
|
||||
}
|
8
MQTTProcessNotifier/appsettings.json
Normal file
8
MQTTProcessNotifier/appsettings.json
Normal file
@ -0,0 +1,8 @@
|
||||
{
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
"Microsoft.Hosting.Lifetime": "Information"
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user