Move EnergyManager code to seperate class

This commit is contained in:
2023-02-02 14:15:39 +01:00
parent a7693e34ed
commit 31bf148e0f
2 changed files with 266 additions and 60 deletions

View File

@@ -1,18 +1,16 @@
using MQTTnet;
using MQTTnet.Client;
using NModbus;
using NModbus;
using System.Net.Sockets;
namespace TestApp
{
internal class Program
{
private static IMqttClient _MqttClient;
private static Dictionary<UInt64, UInt64> _CurrentValues = new Dictionary<ulong, ulong>();
private static EnergyManager _EnergyManager;
static async Task Main(string[] args)
{
await ConnectMQTT();
_EnergyManager = await EnergyManager.Create();
while (true)
{
@@ -39,7 +37,7 @@ namespace TestApp
{
try
{
var currentWirkleistung = _CurrentValues.GetValueOrDefault(1099528667391UL) / 1000;
var currentWirkleistung = _EnergyManager.ActivePowerPositive;
ushort input = master.ReadHoldingRegisters(1, 1000, 1)[0];
ushort output = (ushort)(input + currentWirkleistung);
@@ -53,57 +51,5 @@ namespace TestApp
}
}
}
private static async Task ConnectMQTT() {
var factory = new MqttFactory();
_MqttClient = factory.CreateMqttClient();
var clientOptions = new MqttClientOptionsBuilder()
.WithTcpServer("localhost")
.Build();
Console.WriteLine("Connecting to local MQTT ...");
await _MqttClient.ConnectAsync(clientOptions);
Console.WriteLine("Connected to local MQTT!");
_MqttClient.ApplicationMessageReceivedAsync += Client_ApplicationMessageReceivedAsync;
var subscribeOptions = factory.CreateSubscribeOptionsBuilder()
.WithTopicFilter(
f => {
f.WithTopic("gdr/local/values/smart-meter");
}
)
.Build();
Console.WriteLine("Subscribing to smart-meter values ...");
var response = await _MqttClient.SubscribeAsync(subscribeOptions);
Console.WriteLine("Subscribed to smart-meter values!");
}
private static Task Client_ApplicationMessageReceivedAsync(MqttApplicationMessageReceivedEventArgs arg)
{
switch (arg.ApplicationMessage.Topic) {
case "gdr/local/values/smart-meter":
ParseGDRs(arg.ApplicationMessage.Payload);
break;
}
return Task.CompletedTask;
}
private static void ParseGDRs(byte[] payload)
{
var gdrs = GDRs.Parser.ParseFrom(payload);
if (!gdrs.GDRs_.TryGetValue("smart-meter", out GDR smartMeterGDR)) {
return;
}
foreach (var value in smartMeterGDR.Values) {
_CurrentValues[value.Key] = value.Value;
}
}
}
}
}